Skip to content

Commit 48fb059

Browse files
fix(relay): share notification policy and prioritize waiting agents
Extract the shared aggregation and alert helpers from the Android contribution, keeping delivery policy available to both transports. Co-authored-by: Ryan Hughes <[email protected]>
1 parent 20e2e89 commit 48fb059

6 files changed

Lines changed: 448 additions & 303 deletions

File tree

‎infra/relay/src/agentActivity/AgentActivityPublisher.ts‎

Lines changed: 6 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
import { makeAggregateState } from "./agentActivityAggregate.ts";
2+
export {
3+
makeAggregateState,
4+
TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS,
5+
} from "./agentActivityAggregate.ts";
16
import type {
2-
RelayAgentActivityAggregateState,
37
RelayAgentActivityState,
48
RelayDeliveryResult,
59
RelayPublishResponse,
@@ -8,14 +12,8 @@ import * as Context from "effect/Context";
812
import * as DateTime from "effect/DateTime";
913
import * as Effect from "effect/Effect";
1014
import * as Layer from "effect/Layer";
11-
import * as Option from "effect/Option";
1215

13-
import {
14-
isExpiredAgentActivityState,
15-
isTerminalPhase,
16-
MAX_ACTIVITY_ROWS,
17-
sanitizeAgentActivityAggregateState,
18-
} from "./agentActivityPayloads.ts";
16+
import { isTerminalPhase } from "./agentActivityPayloads.ts";
1917

2018
export { isExpiredAgentActivityState } from "./agentActivityPayloads.ts";
2119
import * as AgentActivityRows from "./AgentActivityRows.ts";
@@ -183,122 +181,4 @@ export const make = Effect.gen(function* () {
183181
});
184182
});
185183

186-
function 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-
}
205-
}
206-
207-
function 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-
};
219-
}
220-
221-
function 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-
});
229-
}
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.
234-
export const TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS = 15 * 60 * 1_000;
235-
236-
function 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;
248-
}
249-
250-
export 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-
});
302-
}
303-
304184
export const layer = Layer.effect(AgentActivityPublisher, make);

‎infra/relay/src/agentActivity/ApnsDeliveries.ts‎

Lines changed: 18 additions & 171 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import * as Schema from "effect/Schema";
2020
import {
2121
isExpiredAgentActivityState,
2222
isTerminalPhase,
23+
notificationForActivity,
2324
sanitizeAgentActivityAggregateState,
2425
sanitizeApnsNotificationPayload,
2526
} from "./agentActivityPayloads.ts";
@@ -42,6 +43,19 @@ import * as RelayConfiguration from "../Config.ts";
4243
import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
4344
import { withSpanAttributes } from "../observability.ts";
4445

46+
import {
47+
alertForAttentionTransition,
48+
alertForNewlyTerminal,
49+
alertForTerminalAggregate,
50+
newlyTerminalRows,
51+
shouldAlertForActivity,
52+
} from "./agentActivityAlerts.ts";
53+
export {
54+
alertForAttentionTransition,
55+
alertForNewlyTerminal,
56+
alertForTerminalAggregate,
57+
} from "./agentActivityAlerts.ts";
58+
4559
const MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS = 15_000;
4660
// How long a just-armed card may sit with an empty aggregate before an end is
4761
// warranted; covers the gap between arming on send and the environment's
@@ -146,148 +160,6 @@ function aggregateNeedsAttention(aggregate: RelayAgentActivityAggregateState): b
146160
);
147161
}
148162

149-
function isAttentionPhase(phase: string): boolean {
150-
return phase === "waiting_for_approval" || phase === "waiting_for_input";
151-
}
152-
153-
// Honors the same per-event notification switches the push channel uses; a
154-
// missing/corrupt preferences blob only disables nothing (matching how the
155-
// liveActivitiesEnabled check treats it), since every registration writes one.
156-
function alertAllowedForPhase(
157-
preferences: RelayAgentAwarenessPreferences | null,
158-
phase: string,
159-
): boolean {
160-
if (preferences === null) {
161-
return true;
162-
}
163-
switch (phase) {
164-
case "waiting_for_approval":
165-
return preferences.notifyOnApproval;
166-
case "waiting_for_input":
167-
return preferences.notifyOnInput;
168-
case "completed":
169-
return preferences.notifyOnCompletion;
170-
case "failed":
171-
return preferences.notifyOnFailure;
172-
default:
173-
return false;
174-
}
175-
}
176-
177-
// Alert copy for an update whose aggregate contains threads that were NOT in an
178-
// attention phase in the previously delivered aggregate. A null previous
179-
// aggregate means there is no known baseline (fresh registration, replay after
180-
// data loss) — alerting there would buzz on reconnect, not on a transition.
181-
export function alertForAttentionTransition(input: {
182-
readonly previousAggregate: RelayAgentActivityAggregateState | null;
183-
readonly nextAggregate: RelayAgentActivityAggregateState;
184-
readonly preferences: RelayAgentAwarenessPreferences | null;
185-
}): ApnsLiveActivityAlert | null {
186-
if (input.previousAggregate === null) {
187-
return null;
188-
}
189-
const previouslyAttention = new Set(
190-
input.previousAggregate.activities
191-
.filter((row) => isAttentionPhase(row.phase))
192-
.map((row) => row.threadId),
193-
);
194-
const newlyAttention = input.nextAggregate.activities.filter(
195-
(row) =>
196-
isAttentionPhase(row.phase) &&
197-
!previouslyAttention.has(row.threadId) &&
198-
alertAllowedForPhase(input.preferences, row.phase),
199-
);
200-
const first = newlyAttention[0];
201-
if (!first) {
202-
return null;
203-
}
204-
if (newlyAttention.length === 1) {
205-
return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };
206-
}
207-
return {
208-
title: `${newlyAttention.length} agents need attention`,
209-
body: newlyAttention.map((row) => row.threadTitle).join(", "),
210-
};
211-
}
212-
213-
// Alert copy for an update whose aggregate contains threads that finished
214-
// (Done/Failed) since the previously delivered aggregate — the mid-flight
215-
// completion buzz while other agents keep the activity alive. Requires the
216-
// thread to have been present and non-terminal before, so a baseline-less
217-
// replay or a row that merely fell off the display cap never rings.
218-
function newlyTerminalRows(
219-
previousAggregate: RelayAgentActivityAggregateState | null,
220-
nextAggregate: RelayAgentActivityAggregateState,
221-
): ReadonlyArray<RelayAgentActivityAggregateState["activities"][number]> {
222-
if (previousAggregate === null) {
223-
return [];
224-
}
225-
const previousPhases = new Map(
226-
previousAggregate.activities.map((row) => [row.threadId, row.phase]),
227-
);
228-
return nextAggregate.activities.filter((row) => {
229-
if (row.phase !== "completed" && row.phase !== "failed") {
230-
return false;
231-
}
232-
const previousPhase = previousPhases.get(row.threadId);
233-
return (
234-
previousPhase !== undefined && previousPhase !== "completed" && previousPhase !== "failed"
235-
);
236-
});
237-
}
238-
239-
function isFreshTerminalRow(
240-
row: RelayAgentActivityAggregateState["activities"][number],
241-
nowMs: number,
242-
): boolean {
243-
const updatedAtMs = Option.match(DateTime.make(row.updatedAt), {
244-
onNone: () => null,
245-
onSome: (dt) => dt.epochMilliseconds,
246-
});
247-
return updatedAtMs !== null && nowMs - updatedAtMs <= TERMINAL_NOTIFICATION_FRESHNESS_MS;
248-
}
249-
250-
export function alertForNewlyTerminal(input: {
251-
readonly previousAggregate: RelayAgentActivityAggregateState | null;
252-
readonly nextAggregate: RelayAgentActivityAggregateState;
253-
readonly preferences: RelayAgentAwarenessPreferences | null;
254-
readonly nowMs: number;
255-
}): ApnsLiveActivityAlert | null {
256-
const newlyTerminal = newlyTerminalRows(input.previousAggregate, input.nextAggregate).filter(
257-
(row) =>
258-
alertAllowedForPhase(input.preferences, row.phase) &&
259-
// Replays of old aggregates (server restarts, redeliveries) repaint
260-
// state without ringing; only fresh completions buzz.
261-
isFreshTerminalRow(row, input.nowMs),
262-
);
263-
const first = newlyTerminal[0];
264-
if (!first) {
265-
return null;
266-
}
267-
if (newlyTerminal.length === 1) {
268-
return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };
269-
}
270-
return {
271-
title: `${newlyTerminal.length} agents finished`,
272-
body: newlyTerminal.map((row) => row.threadTitle).join(", "),
273-
};
274-
}
275-
276-
// Alert copy for an end event carrying a terminal (Done/Failed) aggregate.
277-
export function alertForTerminalAggregate(input: {
278-
readonly aggregate: RelayAgentActivityAggregateState | null;
279-
readonly preferences: RelayAgentAwarenessPreferences | null;
280-
}): ApnsLiveActivityAlert | null {
281-
const row = input.aggregate?.activities[0];
282-
if (!row || (row.phase !== "completed" && row.phase !== "failed")) {
283-
return null;
284-
}
285-
if (!alertAllowedForPhase(input.preferences, row.phase)) {
286-
return null;
287-
}
288-
return { title: row.threadTitle, body: `${row.status}: ${row.projectTitle}` };
289-
}
290-
291163
function shouldUpdateLiveActivity(input: {
292164
readonly previousAggregate: RelayAgentActivityAggregateState | null;
293165
readonly nextAggregate: RelayAgentActivityAggregateState;
@@ -328,7 +200,6 @@ function shouldUpdateLiveActivity(input: {
328200

329201
// Completions replayed long after the fact (server restarts republish every
330202
// recently-finished thread) must not ring the device again.
331-
const TERMINAL_NOTIFICATION_FRESHNESS_MS = 2 * 60 * 1_000;
332203

333204
function notificationForAggregate(input: {
334205
readonly target: LiveActivities.TargetRow;
@@ -346,32 +217,8 @@ function notificationForAggregate(input: {
346217
if (!activity) {
347218
return null;
348219
}
349-
if (activity.phase === "completed" || activity.phase === "failed") {
350-
const updatedAtMs = Option.match(DateTime.make(activity.updatedAt), {
351-
onNone: () => null,
352-
onSome: (dt) => dt.epochMilliseconds,
353-
});
354-
if (updatedAtMs === null || input.nowMs - updatedAtMs > TERMINAL_NOTIFICATION_FRESHNESS_MS) {
355-
return null;
356-
}
357-
}
358-
const enabled =
359-
(activity.phase === "waiting_for_approval" && preferences.notifyOnApproval) ||
360-
(activity.phase === "waiting_for_input" && preferences.notifyOnInput) ||
361-
(activity.phase === "completed" && preferences.notifyOnCompletion) ||
362-
(activity.phase === "failed" && preferences.notifyOnFailure);
363-
if (!enabled) {
364-
return null;
365-
}
366-
return {
367-
title: activity.threadTitle,
368-
body: `${activity.status}: ${activity.projectTitle}`,
369-
environmentId: activity.environmentId,
370-
threadId: activity.threadId,
371-
deepLink: activity.deepLink,
372-
phase: activity.phase,
373-
updatedAt: activity.updatedAt,
374-
};
220+
if (!shouldAlertForActivity({ ...activity, preferences, nowMs: input.nowMs })) return null;
221+
return notificationForActivity(activity);
375222
}
376223

377224
// "suppressed" means a Live Activity owns this state but no update is due
@@ -584,9 +431,9 @@ interface LiveActivityDeliveryTarget {
584431
// DeviceTokenNotForTopic/BadDeviceToken, so per-device values override the
585432
// relay-wide defaults when present.
586433
function credentialsForTarget(
587-
credentials: RelayConfiguration.RelayConfiguration["Service"]["apns"],
434+
credentials: RelayConfiguration.ApnsCredentials,
588435
target: LiveActivityDeliveryTarget,
589-
): RelayConfiguration.RelayConfiguration["Service"]["apns"] {
436+
): RelayConfiguration.ApnsCredentials {
590437
return {
591438
...credentials,
592439
...(target.bundle_id ? { bundleId: target.bundle_id } : {}),

0 commit comments

Comments
 (0)