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

AgentActivityPublisher.ts

304 lines11.0 KB

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