Open History to see the last commit
1import type {
2 RelayAgentActivityAggregateState,
3 RelayAgentActivityState,
4 RelayDeliveryResult,
5 RelayPublishResponse,
6} from "@t3tools/contracts/relay";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12
13import {
14 isExpiredAgentActivityState,
15 isTerminalPhase,
16 MAX_ACTIVITY_ROWS,
17 sanitizeAgentActivityAggregateState,
18} from "./agentActivityPayloads.ts";
19
20export { isExpiredAgentActivityState } from "./agentActivityPayloads.ts";
21import * as AgentActivityRows from "./AgentActivityRows.ts";
22import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
23import * as LiveActivities from "./LiveActivities.ts";
24import * as ApnsDeliveries from "./ApnsDeliveries.ts";
25
26export type AgentActivityPublishError =
27 | AgentActivityRows.AgentActivityRowUpsertPersistenceError
28 | AgentActivityRows.AgentActivityRowDeletePersistenceError
29 | AgentActivityRows.AgentActivityRowListPersistenceError
30 | EnvironmentLinks.EnvironmentLinkUserListPersistenceError
31 | LiveActivities.LiveActivityTargetListPersistenceError
32 | ApnsDeliveries.ApnsDeliveryError;
33
34export class AgentActivityPublisher extends Context.Service<
35 AgentActivityPublisher,
36 {
37 readonly publish: (input: {
38 readonly environmentId: string;
39 readonly environmentPublicKey: string;
40 readonly threadId: string;
41 readonly state: RelayAgentActivityState | null;
42 }) => Effect.Effect<RelayPublishResponse, AgentActivityPublishError>;
43 readonly replayForLiveActivityRegistration: (input: {
44 readonly userId: string;
45 readonly deviceId: string;
46 }) => Effect.Effect<RelayDeliveryResult | null, AgentActivityPublishError>;
47 }
48>()("t3code-relay/agentActivity/AgentActivityPublisher") {}
49
50export const make = Effect.gen(function* () {
51 const rows = yield* AgentActivityRows.AgentActivityRows;
52 const links = yield* EnvironmentLinks.EnvironmentLinks;
53 const liveActivities = yield* LiveActivities.LiveActivities;
54 const apnsDeliveries = yield* ApnsDeliveries.ApnsDeliveries;
55
56 const publishForDeliveryUser = Effect.fnUntraced(function* (input: {
57 readonly deliveryUser: EnvironmentLinks.AgentAwarenessDeliveryUserRecord;
58 readonly state: RelayAgentActivityState | null;
59 readonly nowMs: number;
60 }) {
61 const activeStates = yield* rows.listForUser({ userId: input.deliveryUser.userId });
62 const liveActivityAggregate = input.deliveryUser.liveActivitiesEnabled
63 ? makeAggregateState({
64 activeStates,
65 terminalState: input.state && isTerminalPhase(input.state) ? input.state : null,
66 nowMs: input.nowMs,
67 })
68 : null;
69 const notificationOnlyAggregate =
70 input.deliveryUser.notificationsEnabled &&
71 !input.deliveryUser.liveActivitiesEnabled &&
72 input.state !== null
73 ? makeAggregateState({
74 activeStates: isTerminalPhase(input.state) ? [] : [input.state],
75 terminalState: isTerminalPhase(input.state) ? input.state : null,
76 nowMs: input.nowMs,
77 })
78 : null;
79 const targets = yield* liveActivities.listTargets({ userId: input.deliveryUser.userId });
80 const deliveriesByTarget = yield* Effect.forEach(
81 targets,
82 (target) =>
83 Effect.all(
84 [
85 apnsDeliveries.sendForTarget({
86 target,
87 aggregate: liveActivityAggregate,
88 nowMs: input.nowMs,
89 }),
90 notificationOnlyAggregate === null
91 ? Effect.succeed(null)
92 : apnsDeliveries.sendPushNotificationForTarget({
93 target,
94 aggregate: notificationOnlyAggregate,
95 }),
96 ],
97 { concurrency: 2 },
98 ),
99 { concurrency: 4 },
100 );
101 return deliveriesByTarget.flat();
102 });
103
104 return AgentActivityPublisher.of({
105 replayForLiveActivityRegistration: Effect.fn(
106 "relay.agent_activity_publisher.replay_for_live_activity_registration",
107 )(function* (input) {
108 yield* Effect.annotateCurrentSpan({
109 "relay.mobile.device_id": input.deviceId,
110 "relay.operation": "replayForLiveActivityRegistration",
111 });
112 const { activeStates, targets } = yield* Effect.all(
113 {
114 activeStates: rows.listForUser({ userId: input.userId }),
115 targets: liveActivities.listTargets({ userId: input.userId }),
116 },
117 { concurrency: 2 },
118 );
119 const target = targets.find((row) => row.device_id === input.deviceId) ?? null;
120 if (target === null) {
121 return null;
122 }
123 const now = yield* DateTime.now;
124 const aggregate = makeAggregateState({
125 activeStates,
126 terminalState: null,
127 nowMs: now.epochMilliseconds,
128 });
129 return yield* apnsDeliveries.sendForTarget({
130 target,
131 aggregate,
132 nowMs: now.epochMilliseconds,
133 });
134 }),
135 publish: Effect.fn("relay.agent_activity_publisher.publish")(function* (input) {
136 yield* Effect.annotateCurrentSpan({
137 "relay.environment_id": input.environmentId,
138 "relay.thread_id": input.threadId,
139 "relay.agent_activity.phase": input.state?.phase ?? "deleted",
140 });
141 if (input.state) {
142 // Terminal states are persisted too (pruned by the cron after they
143 // age out) so a thread that finishes while other agents are active
144 // stays visible as Done/Failed in subsequent aggregates instead of
145 // silently vanishing from the Live Activity.
146 yield* rows.upsert({
147 environmentPublicKey: input.environmentPublicKey,
148 state: input.state,
149 });
150 } else {
151 yield* rows.remove({
152 environmentId: input.environmentId,
153 environmentPublicKey: input.environmentPublicKey,
154 threadId: input.threadId,
155 });
156 }
157
158 const deliveryUsers = yield* links.listDeliveryUsersForEnvironment({
159 environmentId: input.environmentId,
160 environmentPublicKey: input.environmentPublicKey,
161 });
162 const now = yield* DateTime.now;
163 const deliveriesByUser = yield* Effect.forEach(
164 deliveryUsers,
165 (deliveryUser) =>
166 publishForDeliveryUser({
167 deliveryUser,
168 state: input.state,
169 nowMs: now.epochMilliseconds,
170 }),
171 { concurrency: 4 },
172 );
173 const deliveries = deliveriesByUser.flat();
174 return {
175 ok: true,
176 deliveries: deliveries.filter(
177 (delivery): delivery is RelayDeliveryResult => delivery !== null,
178 ),
179 };
180 }),
181 });
182});
183
184function statusForPhase(phase: RelayAgentActivityState["phase"]): string {
185 switch (phase) {
186 case "waiting_for_approval":
187 return "Approval";
188 case "waiting_for_input":
189 return "Input";
190 case "completed":
191 return "Done";
192 case "failed":
193 return "Failed";
194 case "starting":
195 // Matches the web sidebar's pill wording (Sidebar.logic.ts) so the same
196 // thread reads the same across surfaces.
197 return "Connecting";
198 case "running":
199 return "Working";
200 case "stale":
201 return "Waiting";
202 }
203}
204
205function aggregateRowForState(state: RelayAgentActivityState) {
206 return {
207 environmentId: state.environmentId,
208 threadId: state.threadId,
209 projectTitle: state.projectTitle,
210 threadTitle: state.threadTitle,
211 modelTitle: state.modelTitle,
212 phase: state.phase,
213 status: statusForPhase(state.phase),
214 updatedAt: state.updatedAt,
215 deepLink: state.deepLink,
216 };
217}
218
219function terminalAggregateState(state: RelayAgentActivityState): RelayAgentActivityAggregateState {
220 return sanitizeAgentActivityAggregateState({
221 title: "T3 Code",
222 subtitle: state.phase === "failed" ? "Agent work failed" : "Agent work completed",
223 activeCount: 0,
224 updatedAt: state.updatedAt,
225 activities: [aggregateRowForState(state)],
226 });
227}
228
229// How long a finished thread keeps its Done/Failed row in the aggregate while
230// other agents are still active. Long enough to be seen on the lock screen,
231// short enough that the activity list stays about live work.
232export const TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS = 15 * 60 * 1_000;
233
234function isRecentTerminalState(state: RelayAgentActivityState, nowMs: number): boolean {
235 if (!isTerminalPhase(state)) {
236 return false;
237 }
238 const updatedAtMs = Option.match(DateTime.make(state.updatedAt), {
239 onNone: () => Number.NaN,
240 onSome: (dt) => dt.epochMilliseconds,
241 });
242 if (Number.isNaN(updatedAtMs)) {
243 return false;
244 }
245 return nowMs - updatedAtMs <= TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS;
246}
247
248export function makeAggregateState(input: {
249 readonly activeStates: ReadonlyArray<RelayAgentActivityState>;
250 readonly terminalState: RelayAgentActivityState | null;
251 readonly nowMs: number;
252}): RelayAgentActivityAggregateState | null {
253 const activeStates = input.activeStates.filter(
254 (state) => !isTerminalPhase(state) && !isExpiredAgentActivityState(state, input.nowMs),
255 );
256 if (activeStates.length === 0) {
257 if (input.terminalState !== null) {
258 return terminalAggregateState(input.terminalState);
259 }
260 // With no live work, recently finished threads keep the card showing
261 // Done/Failed content (an armed card never renders an empty state). The
262 // newly-terminal alert rules key off the previously delivered aggregate,
263 // so replays repaint this without buzzing. Once the terminal rows age
264 // out, the aggregate is null and the delivery layer ends the card.
265 const recentTerminal = input.activeStates
266 .filter((state) => isRecentTerminalState(state, input.nowMs))
267 .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
268 const newest = recentTerminal[0];
269 if (!newest) {
270 return null;
271 }
272 return sanitizeAgentActivityAggregateState({
273 title: "T3 Code",
274 subtitle: newest.phase === "failed" ? "Agent work failed" : "Agent work completed",
275 activeCount: 0,
276 updatedAt: newest.updatedAt,
277 activities: recentTerminal.slice(0, MAX_ACTIVITY_ROWS).map(aggregateRowForState),
278 });
279 }
280 // Recently finished threads ride along after the active ones (display slots
281 // permitting) so a completion is visible as Done/Failed instead of the row
282 // silently vanishing while other agents keep the activity alive.
283 const recentTerminalStates = input.activeStates
284 .filter((state) => isRecentTerminalState(state, input.nowMs))
285 .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
286 const displayedStates = [
287 ...activeStates.slice(0, MAX_ACTIVITY_ROWS),
288 ...recentTerminalStates,
289 ].slice(0, MAX_ACTIVITY_ROWS);
290 const updatedAt = [...activeStates, ...recentTerminalStates].reduce((latest, state) =>
291 state.updatedAt.localeCompare(latest.updatedAt) > 0 ? state : latest,
292 ).updatedAt;
293 return sanitizeAgentActivityAggregateState({
294 title: "T3 Code",
295 subtitle: "Agent work in progress",
296 activeCount: activeStates.length,
297 updatedAt,
298 activities: displayedStates.map(aggregateRowForState),
299 });
300}
301
302export const layer = Layer.effect(AgentActivityPublisher, make);