@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 673 lines 25.7 KB
Raw
1 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
3 import { describe, expect, it } from "@effect/vitest";
4 import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
5 import * as Effect from "effect/Effect";
6 import * as DateTime from "effect/DateTime";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9 import * as Schema from "effect/Schema";
10 import * as Stream from "effect/Stream";
11 import type * as Cloudflare from "@alchemy.run/cloudflare";
12 import * as FcmDeliveryQueueConsumer from "./FcmDeliveryQueueConsumer.ts";
13
14 import * as RelayConfiguration from "../Config.ts";
15 import * as RelayDb from "../db.ts";
16 import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
17 import * as AgentActivityRows from "./AgentActivityRows.ts";
18 import * as LiveActivities from "./LiveActivities.ts";
19 import * as FcmDeliveryQueueSender from "./FcmDeliveryQueueSender.ts";
20 import * as FcmClient from "./FcmClient.ts";
21 import * as FcmDeliveries from "./FcmDeliveries.ts";
22 import { androidActivityData, fitFcmData } from "./fcmPayloads.ts";
23 import { makeAggregateState } from "./agentActivityAggregate.ts";
24
25 const aggregateFor = (states: ReadonlyArray<RelayAgentActivityState>) =>
26 makeAggregateState({ activeStates: states, terminalState: null, nowMs: 0 })!;
27
28 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
29 const state: RelayAgentActivityState = {
30 environmentId: EnvironmentId.make("env"),
31 threadId: ThreadId.make("thread"),
32 projectTitle: "Project",
33 threadTitle: "Fix notifications",
34 phase: "running",
35 headline: "Working",
36 modelTitle: "Codex",
37 updatedAt: "1970-01-01T00:00:00.000Z",
38 deepLink: "/threads/env/thread",
39 };
40 const preferences = {
41 notificationsEnabled: true,
42 liveActivitiesEnabled: true,
43 notifyOnApproval: true,
44 notifyOnInput: true,
45 notifyOnCompletion: true,
46 notifyOnFailure: true,
47 };
48 const target: LiveActivities.TargetRow = {
49 user_id: "user",
50 device_id: "phone",
51 platform: "android",
52 ios_major_version: null,
53 app_version: null,
54 bundle_id: "com.t3tools.t3code.dev",
55 aps_environment: null,
56 push_token: "fcm-token",
57 push_to_start_token: null,
58 preferences_json: encodeJson(preferences),
59 activity_push_token: null,
60 remote_start_queued_at: null,
61 remote_started_at: null,
62 ended_at: null,
63 last_aggregate_json: null,
64 last_live_activity_delivery_at: null,
65 };
66 const config = {
67 relayIssuer: "https://relay.test",
68 fcmServiceAccount: Redacted.make("configured"),
69 apns: {
70 environment: "sandbox",
71 teamId: "unused",
72 keyId: "unused",
73 bundleId: "unused",
74 privateKey: Redacted.make("unused"),
75 },
76 clerkSecretKey: Redacted.make("unused"),
77 clerkPublishableKey: "unused",
78 clerkJwtAudience: "unused",
79 apnsDeliveryJobSigningSecret: Redacted.make("unused"),
80 cloudMintPrivateKey: Redacted.make("unused"),
81 cloudMintPublicKey: "unused",
82 managedEndpointBaseDomain: undefined,
83 managedEndpointNamespace: undefined,
84 } satisfies RelayConfiguration.RelayConfiguration["Service"];
85
86 function harness() {
87 const sent: Array<Parameters<FcmClient.FcmClient["Service"]["send"]>[0]> = [];
88 const queued: FcmDeliveries.FcmDeliveryJob[] = [];
89 const marked: Array<Parameters<LiveActivities.LiveActivities["Service"]["markDelivery"]>[0]> = [];
90 const current = {
91 target: { ...target },
92 state: { ...state } as RelayAgentActivityState | null,
93 otherStates: [] as RelayAgentActivityState[],
94 mutedEnvironments: [] as string[],
95 notificationOnlyEnvironments: [] as string[],
96 revokedEnvironments: [] as string[],
97 linked: true,
98 deliveryFailure: null as FcmClient.FcmClientError | null,
99 };
100 const layerServices = Layer.mergeAll(
101 NodeCryptoLayer.layer,
102 Layer.succeed(RelayConfiguration.RelayConfiguration, config),
103 Layer.succeed(FcmDeliveryQueueSender.FcmDeliveryQueueSender, {
104 send: (job) =>
105 Effect.sync(() => {
106 queued.push(job);
107 }),
108 }),
109 Layer.succeed(FcmClient.FcmClient, {
110 send: (input) =>
111 Effect.suspend(() =>
112 current.deliveryFailure
113 ? Effect.fail(current.deliveryFailure)
114 : Effect.sync(() => {
115 sent.push(input);
116 return { unregistered: false };
117 }),
118 ),
119 }),
120 Layer.succeed(LiveActivities.LiveActivities, {
121 register: () => Effect.void,
122 listTargets: () => Effect.sync(() => [current.target]),
123 listIdleArmedTargets: () => Effect.succeed([]),
124 markDelivery: (input) =>
125 Effect.sync(() => {
126 marked.push(input);
127 current.target.last_aggregate_json = input.aggregate ? encodeJson(input.aggregate) : null;
128 }),
129
130 invalidateDeliveryToken: () => Effect.void,
131 }),
132 Layer.succeed(AgentActivityRows.AgentActivityRows, {
133 upsert: () => Effect.void,
134 remove: () => Effect.void,
135 pruneTerminal: () => Effect.void,
136 listForUser: () =>
137 Effect.sync(() =>
138 current.linked
139 ? [...(current.state ? [current.state] : []), ...current.otherStates].filter(
140 (row) =>
141 !current.revokedEnvironments.includes(row.environmentId) &&
142 !current.notificationOnlyEnvironments.includes(row.environmentId),
143 )
144 : [],
145 ),
146 getForUserThread: (input) =>
147 Effect.sync(() =>
148 current.linked
149 ? ([current.state, ...current.otherStates].find(
150 (row) =>
151 row?.environmentId === input.environmentId && row.threadId === input.threadId,
152 ) ?? null)
153 : null,
154 ),
155 }),
156 Layer.succeed(EnvironmentLinks.EnvironmentLinks, {
157 upsert: () => Effect.void,
158 listDeliveryUsersForEnvironment: (input) =>
159 Effect.sync(() =>
160 current.linked && !current.revokedEnvironments.includes(input.environmentId)
161 ? [
162 {
163 userId: "user",
164 notificationsEnabled: !current.mutedEnvironments.includes(input.environmentId),
165 liveActivitiesEnabled: !current.notificationOnlyEnvironments.includes(
166 input.environmentId,
167 ),
168 },
169 ]
170 : [],
171 ),
172 listForUser: () => Effect.succeed([]),
173 findActiveManagedForEnvironment: () => Effect.succeed([]),
174 updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"),
175 setHoldWebhooksWhileOffline: () => Effect.void,
176 revokeForUser: () => Effect.succeed(false),
177 getForUser: (input) =>
178 Effect.sync(() =>
179 current.linked && !current.revokedEnvironments.includes(input.environmentId)
180 ? {
181 environmentId: EnvironmentId.make(input.environmentId),
182 label: "Desktop",
183 environmentPublicKey: "key",
184 linkedAt: state.updatedAt,
185 endpoint: {
186 httpBaseUrl: "https://env.test",
187 wsBaseUrl: "wss://env.test",
188 providerKind: "manual",
189 },
190 }
191 : null,
192 ),
193 }),
194 Layer.succeed(RelayDb.RelayDb, {} as RelayDb.RelayDb["Service"]),
195 );
196 return {
197 sent,
198 queued,
199 marked,
200 current,
201 layer: FcmDeliveries.layer.pipe(Layer.provide(layerServices)),
202 job: {
203 userId: "user",
204 deviceId: "phone",
205 token: "fcm-token",
206 state,
207 queuedAt: 0,
208 } satisfies FcmDeliveries.FcmDeliveryJob,
209 };
210 }
211
212 describe("Android delivery routing", () => {
213 const secondState: RelayAgentActivityState = {
214 ...state,
215 threadId: ThreadId.make("second-thread"),
216 threadTitle: "Second thread",
217 deepLink: "/threads/env/second-thread",
218 };
219
220 it.effect.each([
221 {
222 firstPhase: "waiting_for_approval",
223 secondPhase: "waiting_for_input",
224 title: "2 agents need attention",
225 active: "true",
226 },
227 { firstPhase: "completed", secondPhase: "failed", title: "2 agents finished", active: "false" },
228 ] as const)(
229 "routes grouped $firstPhase and $secondPhase to the overview once across their queued jobs",
230 ({ firstPhase, secondPhase, title, active }) => {
231 const h = harness();
232 h.current.otherStates = [secondState];
233 return Effect.gen(function* () {
234 const delivery = yield* FcmDeliveries.FcmDeliveries;
235 yield* delivery.process(h.job);
236 h.current.state = { ...state, phase: firstPhase };
237 h.current.otherStates = [{ ...secondState, phase: secondPhase }];
238 yield* delivery.process({ ...h.job, state: h.current.state });
239 yield* delivery.process({ ...h.job, state: h.current.otherStates[0] });
240 yield* delivery.process({ ...h.job, state: h.current.state });
241 const alerts = h.sent.filter((message) => message.alert);
242 expect(alerts).toHaveLength(1);
243 expect(alerts[0]?.data).toMatchObject({
244 alert_title: title,
245 alert_body: "Fix notifications, Second thread",
246 alert_path: "/",
247 active,
248 });
249 expect(h.marked.at(-1)?.aggregate?.activities).toHaveLength(2);
250 }).pipe(Effect.provide(h.layer));
251 },
252 );
253
254 it.effect("filters disabled event types before counting a group", () => {
255 const h = harness();
256 h.current.target.last_aggregate_json = encodeJson(aggregateFor([state, secondState]));
257 h.current.target.preferences_json = encodeJson({ ...preferences, notifyOnApproval: false });
258 h.current.state = { ...state, phase: "waiting_for_approval" };
259 h.current.otherStates = [{ ...secondState, phase: "waiting_for_input" }];
260 return Effect.gen(function* () {
261 const delivery = yield* FcmDeliveries.FcmDeliveries;
262 yield* delivery.process({ ...h.job, state: h.current.state });
263 expect(h.sent[0]?.data).toMatchObject({
264 alert_title: "Second thread",
265 alert_body: "Input: Project",
266 alert_path: "/threads/env/second-thread",
267 });
268 }).pipe(Effect.provide(h.layer));
269 });
270
271 it.effect("excludes already delivered attention and stale completions from groups", () => {
272 const h = harness();
273 h.current.state = { ...state, phase: "waiting_for_approval" };
274 h.current.target.last_aggregate_json = encodeJson(aggregateFor([h.current.state, secondState]));
275 h.current.otherStates = [
276 { ...secondState, phase: "completed", updatedAt: "1969-12-31T23:57:00.000Z" },
277 ];
278 return Effect.gen(function* () {
279 const delivery = yield* FcmDeliveries.FcmDeliveries;
280 yield* delivery.process({ ...h.job, state: h.current.state });
281 expect(h.sent.every((message) => !message.alert)).toBe(true);
282 }).pipe(Effect.provide(h.layer));
283 });
284
285 it.effect("prioritizes attention over simultaneous completions like iOS", () => {
286 const h = harness();
287 h.current.target.last_aggregate_json = encodeJson(aggregateFor([state, secondState]));
288 h.current.state = { ...state, phase: "completed" };
289 h.current.otherStates = [{ ...secondState, phase: "waiting_for_input" }];
290 return Effect.gen(function* () {
291 const delivery = yield* FcmDeliveries.FcmDeliveries;
292 yield* delivery.process({ ...h.job, state: h.current.state });
293 expect(h.sent[0]?.data).toMatchObject({
294 alert_title: "Second thread",
295 alert_body: "Input: Project",
296 });
297 yield* delivery.process({ ...h.job, state: h.current.otherStates[0] });
298 expect(h.sent.filter((message) => message.alert)).toHaveLength(1);
299 }).pipe(Effect.provide(h.layer));
300 });
301
302 it.effect.each(["completed", "waiting_for_approval", "waiting_for_input", "failed"] as const)(
303 "deleting one thread preserves another thread's %s alert",
304 (phase) => {
305 const h = harness();
306 h.current.otherStates = [secondState];
307 return Effect.gen(function* () {
308 const delivery = yield* FcmDeliveries.FcmDeliveries;
309 yield* delivery.process(h.job);
310 h.current.otherStates = [];
311 h.current.state = { ...state, phase };
312 yield* delivery.enqueue({ target, state: null });
313 yield* delivery.process(h.queued[0]);
314 expect(h.sent.at(-1)?.alert).toBe(false);
315 yield* delivery.process({ ...h.job, state: h.current.state });
316 expect(h.sent.filter((message) => message.alert)).toHaveLength(1);
317 yield* delivery.process({ ...h.job, state: h.current.state });
318 expect(h.sent.filter((message) => message.alert)).toHaveLength(1);
319 }).pipe(Effect.provide(h.layer));
320 },
321 );
322
323 it.effect("registration replay establishes a baseline without alerting", () => {
324 const h = harness();
325 h.current.state = { ...state, phase: "waiting_for_approval" };
326 h.current.otherStates = [{ ...secondState, phase: "waiting_for_input" }];
327 return Effect.gen(function* () {
328 const delivery = yield* FcmDeliveries.FcmDeliveries;
329 yield* delivery.enqueue({ target, state: null, replay: true });
330 yield* delivery.process(h.queued[0]);
331 yield* delivery.process({ ...h.job, state: h.current.state });
332 expect(h.sent.every((message) => !message.alert)).toBe(true);
333 expect(h.marked[0]?.aggregate?.activities).toHaveLength(2);
334 }).pipe(Effect.provide(h.layer));
335 });
336
337 it.effect.each(["mutedEnvironments", "revokedEnvironments"] as const)(
338 "excludes %s when forming cross-environment groups",
339 (restriction) => {
340 const h = harness();
341 const other = { ...secondState, environmentId: EnvironmentId.make("other-env") };
342 h.current.target.last_aggregate_json = encodeJson(aggregateFor([state, other]));
343 h.current.state = { ...state, phase: "waiting_for_approval" };
344 h.current.otherStates = [{ ...other, phase: "waiting_for_input" }];
345 h.current[restriction] = [other.environmentId];
346 return Effect.gen(function* () {
347 const delivery = yield* FcmDeliveries.FcmDeliveries;
348 yield* delivery.process({ ...h.job, state: h.current.state });
349 expect(h.sent[0]?.data).toMatchObject({
350 alert_title: "Fix notifications",
351 alert_body: "Approval: Project",
352 });
353 }).pipe(Effect.provide(h.layer));
354 },
355 );
356
357 it("gives a group a stable retry identity independent of row order", () => {
358 const other = {
359 ...secondState,
360 environmentId: EnvironmentId.make("other-env"),
361 threadId: state.threadId,
362 };
363 const input = {
364 previousAggregate: aggregateFor([state, other]),
365 nextAggregate: aggregateFor([
366 { ...state, phase: "completed" },
367 { ...other, phase: "failed" },
368 ]),
369 preferences,
370 nowMs: 0,
371 };
372 const alert = FcmDeliveries.androidAlertForAggregate(input);
373 expect(alert?.alert_title).toBe("2 agents finished");
374 expect(
375 FcmDeliveries.androidAlertForAggregate({
376 ...input,
377 nextAggregate: {
378 ...input.nextAggregate,
379 activities: input.nextAggregate.activities.toReversed(),
380 },
381 })?.alert_id,
382 ).toBe(alert?.alert_id);
383 expect(
384 FcmDeliveries.androidAlertForAggregate({
385 ...input,
386 nextAggregate: {
387 ...input.nextAggregate,
388 activities: input.nextAggregate.activities.map((row) => ({
389 ...row,
390 updatedAt: "1970-01-01T00:00:01.000Z",
391 })),
392 },
393 })?.alert_id,
394 ).not.toBe(alert?.alert_id);
395 });
396
397 it("distinguishes matching thread IDs in different environments", () => {
398 const other = {
399 ...secondState,
400 environmentId: EnvironmentId.make("other-env"),
401 threadId: state.threadId,
402 };
403 const alreadyWaiting = { ...state, phase: "waiting_for_approval" as const };
404 expect(
405 FcmDeliveries.androidAlertForAggregate({
406 previousAggregate: aggregateFor([alreadyWaiting, other]),
407 nextAggregate: aggregateFor([alreadyWaiting, { ...other, phase: "waiting_for_input" }]),
408 preferences,
409 nowMs: 0,
410 }),
411 ).toMatchObject({ alert_title: "Second thread", alert_body: "Input: Project" });
412 });
413
414 it("keeps notification groups distinct when identifiers contain slashes", () => {
415 const left = FcmDeliveries.androidAlertForState(
416 {
417 ...state,
418 environmentId: EnvironmentId.make("a/b"),
419 threadId: ThreadId.make("c"),
420 phase: "completed",
421 },
422 preferences,
423 0,
424 );
425 const right = FcmDeliveries.androidAlertForState(
426 {
427 ...state,
428 environmentId: EnvironmentId.make("a"),
429 threadId: ThreadId.make("b/c"),
430 phase: "completed",
431 },
432 preferences,
433 0,
434 );
435 expect(left?.alert_group).not.toBe(right?.alert_group);
436 });
437
438 it.effect(
439 "queues Android devices and sends the latest aggregate instead of a stale running state",
440 () => {
441 const h = harness();
442 return Effect.gen(function* () {
443 const delivery = yield* FcmDeliveries.FcmDeliveries;
444 yield* delivery.enqueue({ target, state });
445 h.current.state = { ...state, phase: "completed" };
446 yield* delivery.process(h.queued[0]);
447 expect(h.sent).toHaveLength(0);
448 yield* delivery.process({ ...h.job, state: h.current.state });
449 expect(h.sent[0]?.data).toMatchObject({
450 active: "false",
451 alert_title: "Fix notifications",
452 alert_body: "Done: Project",
453 alert_path: "/threads/env/thread",
454 });
455 }).pipe(Effect.provide(h.layer));
456 },
457 );
458
459 it.effect("keeps completion alerts working with ongoing activity disabled", () => {
460 const h = harness();
461 h.current.state = { ...state, phase: "completed" };
462 h.current.target.preferences_json = encodeJson({
463 ...preferences,
464 liveActivitiesEnabled: false,
465 });
466 return Effect.gen(function* () {
467 const delivery = yield* FcmDeliveries.FcmDeliveries;
468 yield* delivery.process({ ...h.job, state: h.current.state });
469 expect(h.sent[0]?.data).toMatchObject({
470 active: "false",
471 alert_title: "Fix notifications",
472 alert_body: "Done: Project",
473 });
474 expect(h.sent[0]?.data.user_id).toBe("user");
475 }).pipe(Effect.provide(h.layer));
476 });
477
478 it.effect("drops jobs for rotated tokens, expired jobs, and revoked links", () => {
479 const h = harness();
480 return Effect.gen(function* () {
481 const delivery = yield* FcmDeliveries.FcmDeliveries;
482 yield* delivery.process({ ...h.job, token: "old-token" });
483 yield* delivery.process({ ...h.job, queuedAt: -400_000 });
484 h.current.linked = false;
485 yield* delivery.process(h.job);
486 expect(h.sent).toHaveLength(0);
487 }).pipe(Effect.provide(h.layer));
488 });
489
490 it.effect("ends an existing ongoing notification when the environment stops publishing", () => {
491 const h = harness();
492 h.current.target.last_aggregate_json = encodeJson(aggregateFor([state]));
493 h.current.state = null;
494 return Effect.gen(function* () {
495 const delivery = yield* FcmDeliveries.FcmDeliveries;
496 yield* delivery.process({ ...h.job, state: null });
497 expect(h.sent[0]?.data).toMatchObject({ active: "false" });
498 expect(h.sent[0]?.alert).toBe(false);
499 expect(h.marked[0]?.kind).toBe("live_activity_end");
500 }).pipe(Effect.provide(h.layer));
501 });
502
503 it.effect("leaves iOS devices on their existing delivery path", () => {
504 const h = harness();
505 return Effect.gen(function* () {
506 const delivery = yield* FcmDeliveries.FcmDeliveries;
507 expect(yield* delivery.enqueue({ target: { ...target, platform: "ios" }, state })).toBeNull();
508 expect(h.queued).toHaveLength(0);
509 }).pipe(Effect.provide(h.layer));
510 });
511
512 it.effect(
513 "continues ongoing activity when alerts are disabled, with or without a previous card",
514 () => {
515 const h = harness();
516 h.current.state = { ...state, phase: "waiting_for_approval" };
517 h.current.target.preferences_json = encodeJson({
518 ...preferences,
519 notificationsEnabled: false,
520 });
521 return Effect.gen(function* () {
522 const delivery = yield* FcmDeliveries.FcmDeliveries;
523 yield* delivery.process({ ...h.job, state: h.current.state });
524 expect(h.sent).toHaveLength(1);
525 expect(h.sent[0]?.data.active).toBe("true");
526 expect(h.sent[0]?.alert).toBe(false);
527 expect(h.sent[0]?.data.alert_id).toBeUndefined();
528 h.current.target.preferences_json = encodeJson({ ...preferences, notifyOnApproval: false });
529 h.current.target.last_aggregate_json = encodeJson(aggregateFor([state]));
530 yield* delivery.process({ ...h.job, state: h.current.state });
531 expect(h.sent[1]?.data.active).toBe("true");
532 expect(h.sent[1]?.data.alert_id).toBeUndefined();
533 expect(h.marked.at(-1)?.kind).toBe("live_activity_update");
534 }).pipe(Effect.provide(h.layer));
535 },
536 );
537
538 it.effect("replays an empty card to repair an orphan without a delivery baseline", () => {
539 const h = harness();
540 h.current.state = null;
541 return Effect.gen(function* () {
542 const delivery = yield* FcmDeliveries.FcmDeliveries;
543 yield* delivery.process({ ...h.job, state: null });
544 expect(h.sent[0]?.data.activity_expires_at).toBe("0");
545 expect(h.sent[0]?.alert).toBe(false);
546 }).pipe(Effect.provide(h.layer));
547 });
548
549 it("fits five Unicode rows and a grouped alert in the FCM budget without corrupting text or routes", () => {
550 const longTitle = '🤖漢字"\\'.repeat(30);
551 const aggregate = aggregateFor(
552 Array.from({ length: 5 }, (_, i) => ({
553 ...state,
554 threadId: ThreadId.make(`thread-${i}`),
555 threadTitle: longTitle,
556 projectTitle: longTitle,
557 })),
558 );
559 const data = fitFcmData({
560 ...androidActivityData(aggregate),
561 t3_kind: "agent_activity",
562 device_id: "d".repeat(128),
563 user_id: "u".repeat(128),
564 updated_at: "1788780000000",
565 alert_id: "a".repeat(64),
566 alert_title: "5 agents finished",
567 alert_body: Array(5).fill(longTitle).join(", "),
568 alert_path: "/threads/env/thread",
569 });
570 expect(new TextEncoder().encode(JSON.stringify(data)).length).toBeLessThanOrEqual(3800);
571 expect(data.alert_path).toBe("/threads/env/thread");
572 expect(data.activity_path).toBe("/threads/env/thread");
573 expect(data.alert_id).toBe("a".repeat(64));
574 expect(data.activity_line_4).toContain("Working\t");
575 for (const value of Object.values(data))
576 expect(new TextDecoder().decode(new TextEncoder().encode(value))).toBe(value);
577 });
578 });
579
580 describe("delivery policy regressions", () => {
581 it.effect("alerts a quick completion even with a previous unrelated card", () => {
582 const h = harness();
583 const old = { ...state, threadId: ThreadId.make("old"), phase: "completed" as const };
584 h.current.target.last_aggregate_json = encodeJson(aggregateFor([old]));
585 h.current.otherStates = [old];
586 h.current.state = { ...state, phase: "completed" };
587 return Effect.gen(function* () {
588 const d = yield* FcmDeliveries.FcmDeliveries;
589 yield* d.process(h.job);
590 yield* d.process({ ...h.job, state: h.current.state });
591 expect(h.sent.filter((x) => x.alert)).toHaveLength(1);
592 }).pipe(Effect.provide(h.layer));
593 });
594 });
595
596 describe("notification-only environments", () => {
597 it.effect("alerts independently while another environment has a live card", () => {
598 const h = harness();
599 const other = {
600 ...state,
601 environmentId: EnvironmentId.make("other"),
602 threadId: ThreadId.make("other"),
603 };
604 h.current.target.last_aggregate_json = encodeJson(aggregateFor([other]));
605 h.current.otherStates = [other];
606 h.current.state = { ...state, phase: "waiting_for_input" };
607 h.current.notificationOnlyEnvironments = [state.environmentId];
608 return Effect.gen(function* () {
609 const deliveries = yield* FcmDeliveries.FcmDeliveries;
610 yield* deliveries.process({ ...h.job, state: h.current.state });
611 expect(h.sent).toHaveLength(1);
612 expect(h.sent[0]?.alert).toBe(true);
613 expect(h.sent[0]?.data.alert_path).toBe(state.deepLink);
614 }).pipe(Effect.provide(h.layer));
615 });
616 });
617
618 it("stops reducing five-character row fields and fits the remaining alert", () => {
619 const data = fitFcmData({
620 device_id: "x".repeat(3710),
621 activity_line_0: "Approval\taaaaa\tbbbbb",
622 alert_body: "y".repeat(200),
623 });
624 expect(data.activity_line_0).toBe("Approval\taaaaa\tbbbbb");
625 expect(new TextEncoder().encode(encodeJson(data)).length).toBeLessThanOrEqual(3800);
626 });
627
628 describe("FCM queue message isolation", () => {
629 it.effect.each(["invalid-job", "fcm-rejection"] as const)(
630 "retries only the %s message and delivers the rest of its batch",
631 (failure) => {
632 const h = harness();
633 const outcomes = new Map<string, "ack" | "retry">();
634 const message = (id: string, body: unknown): Cloudflare.Queues.Message<unknown> => ({
635 id,
636 body,
637 timestamp: DateTime.toDateUtc(DateTime.makeUnsafe(0)),
638 attempts: 1,
639 ack: () => {
640 if (!outcomes.has(id)) outcomes.set(id, "ack");
641 },
642 retry: () => {
643 if (!outcomes.has(id)) outcomes.set(id, "retry");
644 },
645 });
646 const batch = [
647 message("failed", failure === "invalid-job" ? {} : h.job),
648 message("healthy", h.job),
649 ];
650 return Effect.gen(function* () {
651 yield* Stream.fromIterable(batch).pipe(
652 Stream.tap((item) =>
653 Effect.sync(() => {
654 h.current.deliveryFailure =
655 item.id === "failed" && failure === "fcm-rejection"
656 ? new FcmClient.FcmClientError({ operation: "send", status: 400 })
657 : null;
658 }),
659 ),
660 Stream.runForEach(FcmDeliveryQueueConsumer.processMessage),
661 );
662 // Cloudflare ignores Alchemy's final batch acknowledgements for already-retried messages.
663 for (const item of batch) item.ack();
664 expect([...outcomes]).toEqual([
665 ["failed", "retry"],
666 ["healthy", "ack"],
667 ]);
668 expect(h.sent).toHaveLength(1);
669 expect(h.marked).toHaveLength(1);
670 }).pipe(Effect.provide(h.layer));
671 },
672 );
673 });