fix(relay): share notification policy and prioritize waiting agents (#10848)

Co-authored-by: Ryan Hughes <[email protected]>
This commit is contained in:
Julius MarmingeandRyan Hughes authored and GitHub committed 2026-09-08 16:39:48 -07:00
1 parent 20e2e899ec
commit fdf34c4018
6 files changed
+448 -303

No files matched your search

@@ -1,5 +1,9 @@
import { makeAggregateState } from "./agentActivityAggregate.ts";
export {
makeAggregateState,
TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS,
} from "./agentActivityAggregate.ts";
import type {
RelayAgentActivityAggregateState,
RelayAgentActivityState,
RelayDeliveryResult,
RelayPublishResponse,
@@ -8,14 +12,8 @@ import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import {
isExpiredAgentActivityState,
isTerminalPhase,
MAX_ACTIVITY_ROWS,
sanitizeAgentActivityAggregateState,
} from "./agentActivityPayloads.ts";
import { isTerminalPhase } from "./agentActivityPayloads.ts";
export { isExpiredAgentActivityState } from "./agentActivityPayloads.ts";
import * as AgentActivityRows from "./AgentActivityRows.ts";
@@ -183,122 +181,4 @@ export const make = Effect.gen(function* () {
});
});
function statusForPhase(phase: RelayAgentActivityState["phase"]): string {
switch (phase) {
case "waiting_for_approval":
return "Approval";
case "waiting_for_input":
return "Input";
case "completed":
return "Done";
case "failed":
return "Failed";
case "starting":
// Matches the web sidebar's pill wording (Sidebar.logic.ts) so the same
// thread reads the same across surfaces.
return "Connecting";
case "running":
return "Working";
case "stale":
return "Waiting";
}
}
function aggregateRowForState(state: RelayAgentActivityState) {
return {
environmentId: state.environmentId,
threadId: state.threadId,
projectTitle: state.projectTitle,
threadTitle: state.threadTitle,
modelTitle: state.modelTitle,
phase: state.phase,
status: statusForPhase(state.phase),
updatedAt: state.updatedAt,
deepLink: state.deepLink,
};
}
function terminalAggregateState(state: RelayAgentActivityState): RelayAgentActivityAggregateState {
return sanitizeAgentActivityAggregateState({
title: "T3 Code",
subtitle: state.phase === "failed" ? "Agent work failed" : "Agent work completed",
activeCount: 0,
updatedAt: state.updatedAt,
activities: [aggregateRowForState(state)],
});
}
// How long a finished thread keeps its Done/Failed row in the aggregate while
// other agents are still active. Long enough to be seen on the lock screen,
// short enough that the activity list stays about live work.
export const TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS = 15 * 60 * 1_000;
function isRecentTerminalState(state: RelayAgentActivityState, nowMs: number): boolean {
if (!isTerminalPhase(state)) {
return false;
}
const updatedAtMs = Option.match(DateTime.make(state.updatedAt), {
onNone: () => Number.NaN,
onSome: (dt) => dt.epochMilliseconds,
});
if (Number.isNaN(updatedAtMs)) {
return false;
}
return nowMs - updatedAtMs <= TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS;
}
export function makeAggregateState(input: {
readonly activeStates: ReadonlyArray<RelayAgentActivityState>;
readonly terminalState: RelayAgentActivityState | null;
readonly nowMs: number;
}): RelayAgentActivityAggregateState | null {
const activeStates = input.activeStates.filter(
(state) => !isTerminalPhase(state) && !isExpiredAgentActivityState(state, input.nowMs),
);
if (activeStates.length === 0) {
if (input.terminalState !== null) {
return terminalAggregateState(input.terminalState);
}
// With no live work, recently finished threads keep the card showing
// Done/Failed content (an armed card never renders an empty state). The
// newly-terminal alert rules key off the previously delivered aggregate,
// so replays repaint this without buzzing. Once the terminal rows age
// out, the aggregate is null and the delivery layer ends the card.
const recentTerminal = input.activeStates
.filter((state) => isRecentTerminalState(state, input.nowMs))
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
const newest = recentTerminal[0];
if (!newest) {
return null;
}
return sanitizeAgentActivityAggregateState({
title: "T3 Code",
subtitle: newest.phase === "failed" ? "Agent work failed" : "Agent work completed",
activeCount: 0,
updatedAt: newest.updatedAt,
activities: recentTerminal.slice(0, MAX_ACTIVITY_ROWS).map(aggregateRowForState),
});
}
// Recently finished threads ride along after the active ones (display slots
// permitting) so a completion is visible as Done/Failed instead of the row
// silently vanishing while other agents keep the activity alive.
const recentTerminalStates = input.activeStates
.filter((state) => isRecentTerminalState(state, input.nowMs))
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
const displayedStates = [
...activeStates.slice(0, MAX_ACTIVITY_ROWS),
...recentTerminalStates,
].slice(0, MAX_ACTIVITY_ROWS);
const updatedAt = [...activeStates, ...recentTerminalStates].reduce((latest, state) =>
state.updatedAt.localeCompare(latest.updatedAt) > 0 ? state : latest,
).updatedAt;
return sanitizeAgentActivityAggregateState({
title: "T3 Code",
subtitle: "Agent work in progress",
activeCount: activeStates.length,
updatedAt,
activities: displayedStates.map(aggregateRowForState),
});
}
export const layer = Layer.effect(AgentActivityPublisher, make);
+18 -171
View File
@@ -20,6 +20,7 @@ import * as Schema from "effect/Schema";
import {
isExpiredAgentActivityState,
isTerminalPhase,
notificationForActivity,
sanitizeAgentActivityAggregateState,
sanitizeApnsNotificationPayload,
} from "./agentActivityPayloads.ts";
@@ -42,6 +43,19 @@ import * as RelayConfiguration from "../Config.ts";
import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
import { withSpanAttributes } from "../observability.ts";
import {
alertForAttentionTransition,
alertForNewlyTerminal,
alertForTerminalAggregate,
newlyTerminalRows,
shouldAlertForActivity,
} from "./agentActivityAlerts.ts";
export {
alertForAttentionTransition,
alertForNewlyTerminal,
alertForTerminalAggregate,
} from "./agentActivityAlerts.ts";
const MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS = 15_000;
// How long a just-armed card may sit with an empty aggregate before an end is
// warranted; covers the gap between arming on send and the environment's
@@ -146,148 +160,6 @@ function aggregateNeedsAttention(aggregate: RelayAgentActivityAggregateState): b
);
}
function isAttentionPhase(phase: string): boolean {
return phase === "waiting_for_approval" || phase === "waiting_for_input";
}
// Honors the same per-event notification switches the push channel uses; a
// missing/corrupt preferences blob only disables nothing (matching how the
// liveActivitiesEnabled check treats it), since every registration writes one.
function alertAllowedForPhase(
preferences: RelayAgentAwarenessPreferences | null,
phase: string,
): boolean {
if (preferences === null) {
return true;
}
switch (phase) {
case "waiting_for_approval":
return preferences.notifyOnApproval;
case "waiting_for_input":
return preferences.notifyOnInput;
case "completed":
return preferences.notifyOnCompletion;
case "failed":
return preferences.notifyOnFailure;
default:
return false;
}
}
// Alert copy for an update whose aggregate contains threads that were NOT in an
// attention phase in the previously delivered aggregate. A null previous
// aggregate means there is no known baseline (fresh registration, replay after
// data loss) — alerting there would buzz on reconnect, not on a transition.
export function alertForAttentionTransition(input: {
readonly previousAggregate: RelayAgentActivityAggregateState | null;
readonly nextAggregate: RelayAgentActivityAggregateState;
readonly preferences: RelayAgentAwarenessPreferences | null;
}): ApnsLiveActivityAlert | null {
if (input.previousAggregate === null) {
return null;
}
const previouslyAttention = new Set(
input.previousAggregate.activities
.filter((row) => isAttentionPhase(row.phase))
.map((row) => row.threadId),
);
const newlyAttention = input.nextAggregate.activities.filter(
(row) =>
isAttentionPhase(row.phase) &&
!previouslyAttention.has(row.threadId) &&
alertAllowedForPhase(input.preferences, row.phase),
);
const first = newlyAttention[0];
if (!first) {
return null;
}
if (newlyAttention.length === 1) {
return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };
}
return {
title: `${newlyAttention.length} agents need attention`,
body: newlyAttention.map((row) => row.threadTitle).join(", "),
};
}
// Alert copy for an update whose aggregate contains threads that finished
// (Done/Failed) since the previously delivered aggregate — the mid-flight
// completion buzz while other agents keep the activity alive. Requires the
// thread to have been present and non-terminal before, so a baseline-less
// replay or a row that merely fell off the display cap never rings.
function newlyTerminalRows(
previousAggregate: RelayAgentActivityAggregateState | null,
nextAggregate: RelayAgentActivityAggregateState,
): ReadonlyArray<RelayAgentActivityAggregateState["activities"][number]> {
if (previousAggregate === null) {
return [];
}
const previousPhases = new Map(
previousAggregate.activities.map((row) => [row.threadId, row.phase]),
);
return nextAggregate.activities.filter((row) => {
if (row.phase !== "completed" && row.phase !== "failed") {
return false;
}
const previousPhase = previousPhases.get(row.threadId);
return (
previousPhase !== undefined && previousPhase !== "completed" && previousPhase !== "failed"
);
});
}
function isFreshTerminalRow(
row: RelayAgentActivityAggregateState["activities"][number],
nowMs: number,
): boolean {
const updatedAtMs = Option.match(DateTime.make(row.updatedAt), {
onNone: () => null,
onSome: (dt) => dt.epochMilliseconds,
});
return updatedAtMs !== null && nowMs - updatedAtMs <= TERMINAL_NOTIFICATION_FRESHNESS_MS;
}
export function alertForNewlyTerminal(input: {
readonly previousAggregate: RelayAgentActivityAggregateState | null;
readonly nextAggregate: RelayAgentActivityAggregateState;
readonly preferences: RelayAgentAwarenessPreferences | null;
readonly nowMs: number;
}): ApnsLiveActivityAlert | null {
const newlyTerminal = newlyTerminalRows(input.previousAggregate, input.nextAggregate).filter(
(row) =>
alertAllowedForPhase(input.preferences, row.phase) &&
// Replays of old aggregates (server restarts, redeliveries) repaint
// state without ringing; only fresh completions buzz.
isFreshTerminalRow(row, input.nowMs),
);
const first = newlyTerminal[0];
if (!first) {
return null;
}
if (newlyTerminal.length === 1) {
return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };
}
return {
title: `${newlyTerminal.length} agents finished`,
body: newlyTerminal.map((row) => row.threadTitle).join(", "),
};
}
// Alert copy for an end event carrying a terminal (Done/Failed) aggregate.
export function alertForTerminalAggregate(input: {
readonly aggregate: RelayAgentActivityAggregateState | null;
readonly preferences: RelayAgentAwarenessPreferences | null;
}): ApnsLiveActivityAlert | null {
const row = input.aggregate?.activities[0];
if (!row || (row.phase !== "completed" && row.phase !== "failed")) {
return null;
}
if (!alertAllowedForPhase(input.preferences, row.phase)) {
return null;
}
return { title: row.threadTitle, body: `${row.status}: ${row.projectTitle}` };
}
function shouldUpdateLiveActivity(input: {
readonly previousAggregate: RelayAgentActivityAggregateState | null;
readonly nextAggregate: RelayAgentActivityAggregateState;
@@ -328,7 +200,6 @@ function shouldUpdateLiveActivity(input: {
// Completions replayed long after the fact (server restarts republish every
// recently-finished thread) must not ring the device again.
const TERMINAL_NOTIFICATION_FRESHNESS_MS = 2 * 60 * 1_000;
function notificationForAggregate(input: {
readonly target: LiveActivities.TargetRow;
@@ -346,32 +217,8 @@ function notificationForAggregate(input: {
if (!activity) {
return null;
}
if (activity.phase === "completed" || activity.phase === "failed") {
const updatedAtMs = Option.match(DateTime.make(activity.updatedAt), {
onNone: () => null,
onSome: (dt) => dt.epochMilliseconds,
});
if (updatedAtMs === null || input.nowMs - updatedAtMs > TERMINAL_NOTIFICATION_FRESHNESS_MS) {
return null;
}
}
const enabled =
(activity.phase === "waiting_for_approval" && preferences.notifyOnApproval) ||
(activity.phase === "waiting_for_input" && preferences.notifyOnInput) ||
(activity.phase === "completed" && preferences.notifyOnCompletion) ||
(activity.phase === "failed" && preferences.notifyOnFailure);
if (!enabled) {
return null;
}
return {
title: activity.threadTitle,
body: `${activity.status}: ${activity.projectTitle}`,
environmentId: activity.environmentId,
threadId: activity.threadId,
deepLink: activity.deepLink,
phase: activity.phase,
updatedAt: activity.updatedAt,
};
if (!shouldAlertForActivity({ ...activity, preferences, nowMs: input.nowMs })) return null;
return notificationForActivity(activity);
}
// "suppressed" means a Live Activity owns this state but no update is due
@@ -584,9 +431,9 @@ interface LiveActivityDeliveryTarget {
// DeviceTokenNotForTopic/BadDeviceToken, so per-device values override the
// relay-wide defaults when present.
function credentialsForTarget(
credentials: RelayConfiguration.RelayConfiguration["Service"]["apns"],
credentials: RelayConfiguration.ApnsCredentials,
target: LiveActivityDeliveryTarget,
): RelayConfiguration.RelayConfiguration["Service"]["apns"] {
): RelayConfiguration.ApnsCredentials {
return {
...credentials,
...(target.bundle_id ? { bundleId: target.bundle_id } : {}),
@@ -0,0 +1,139 @@
import type {
RelayAgentActivityAggregateState,
RelayAgentActivityState,
} from "@t3tools/contracts/relay";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
import {
isExpiredAgentActivityState,
isTerminalPhase,
MAX_ACTIVITY_ROWS,
sanitizeAgentActivityAggregateState,
} from "./agentActivityPayloads.ts";
export function statusForPhase(phase: RelayAgentActivityState["phase"]): string {
switch (phase) {
case "waiting_for_approval":
return "Approval";
case "waiting_for_input":
return "Input";
case "completed":
return "Done";
case "failed":
return "Failed";
case "starting":
// Matches the web sidebar's pill wording (Sidebar.logic.ts) so the same
// thread reads the same across surfaces.
return "Connecting";
case "running":
return "Working";
case "stale":
return "Waiting";
}
}
function aggregateRowForState(state: RelayAgentActivityState) {
return {
environmentId: state.environmentId,
threadId: state.threadId,
projectTitle: state.projectTitle,
threadTitle: state.threadTitle,
modelTitle: state.modelTitle,
phase: state.phase,
status: statusForPhase(state.phase),
updatedAt: state.updatedAt,
deepLink: state.deepLink,
};
}
function terminalAggregateState(state: RelayAgentActivityState): RelayAgentActivityAggregateState {
return sanitizeAgentActivityAggregateState({
title: "T3 Code",
subtitle: state.phase === "failed" ? "Agent work failed" : "Agent work completed",
activeCount: 0,
updatedAt: state.updatedAt,
activities: [aggregateRowForState(state)],
});
}
// How long a finished thread keeps its Done/Failed row in the aggregate while
// other agents are still active. Long enough to be seen on the lock screen,
// short enough that the activity list stays about live work.
export const TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS = 15 * 60 * 1_000;
function isRecentTerminalState(state: RelayAgentActivityState, nowMs: number): boolean {
if (!isTerminalPhase(state)) {
return false;
}
const updatedAtMs = Option.match(DateTime.make(state.updatedAt), {
onNone: () => Number.NaN,
onSome: (dt) => dt.epochMilliseconds,
});
if (Number.isNaN(updatedAtMs)) {
return false;
}
return nowMs - updatedAtMs <= TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS;
}
export function makeAggregateState(input: {
readonly activeStates: ReadonlyArray<RelayAgentActivityState>;
readonly terminalState: RelayAgentActivityState | null;
readonly nowMs: number;
}): RelayAgentActivityAggregateState | null {
const activeStates = input.activeStates.filter(
(state) => !isTerminalPhase(state) && !isExpiredAgentActivityState(state, input.nowMs),
);
if (activeStates.length === 0) {
if (input.terminalState !== null) {
return terminalAggregateState(input.terminalState);
}
// With no live work, recently finished threads keep the card showing
// Done/Failed content (an armed card never renders an empty state). The
// newly-terminal alert rules key off the previously delivered aggregate,
// so replays repaint this without buzzing. Once the terminal rows age
// out, the aggregate is null and the delivery layer ends the card.
const recentTerminal = input.activeStates
.filter((state) => isRecentTerminalState(state, input.nowMs))
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
const newest = recentTerminal[0];
if (!newest) {
return null;
}
return sanitizeAgentActivityAggregateState({
title: "T3 Code",
subtitle: newest.phase === "failed" ? "Agent work failed" : "Agent work completed",
activeCount: 0,
updatedAt: newest.updatedAt,
activities: recentTerminal.slice(0, MAX_ACTIVITY_ROWS).map(aggregateRowForState),
});
}
// Recently finished threads ride along after the active ones (display slots
// permitting) so a completion is visible as Done/Failed instead of the row
// silently vanishing while other agents keep the activity alive.
const recentTerminalStates = input.activeStates
.filter((state) => isRecentTerminalState(state, input.nowMs))
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
const displayedStates = [
...activeStates
.toSorted((a, b) => activityPhasePriority(a.phase) - activityPhasePriority(b.phase))
.slice(0, MAX_ACTIVITY_ROWS),
...recentTerminalStates,
].slice(0, MAX_ACTIVITY_ROWS);
const updatedAt = [...activeStates, ...recentTerminalStates].reduce((latest, state) =>
state.updatedAt.localeCompare(latest.updatedAt) > 0 ? state : latest,
).updatedAt;
return sanitizeAgentActivityAggregateState({
title: "T3 Code",
subtitle: "Agent work in progress",
activeCount: activeStates.length,
updatedAt,
activities: displayedStates.map(aggregateRowForState),
});
}
export function activityPhasePriority(phase: RelayAgentActivityState["phase"]): number {
if (phase === "waiting_for_approval" || phase === "waiting_for_input") return 0;
if (phase === "failed") return 1;
if (phase === "starting" || phase === "running") return 2;
return 3;
}
@@ -0,0 +1,152 @@
import type {
RelayAgentActivityAggregateRow,
RelayAgentActivityAggregateState,
RelayAgentAwarenessPreferences,
} from "@t3tools/contracts/relay";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
export interface AgentActivityAlert {
readonly title: string;
readonly body: string;
}
export const TERMINAL_NOTIFICATION_FRESHNESS_MS = 2 * 60 * 1_000;
export function isFreshTerminalNotification(updatedAt: string, nowMs: number): boolean {
const timestamp = Option.getOrNull(DateTime.make(updatedAt));
return (
timestamp !== null && nowMs - timestamp.epochMilliseconds <= TERMINAL_NOTIFICATION_FRESHNESS_MS
);
}
type TransitionInput = {
readonly previousAggregate: RelayAgentActivityAggregateState | null;
readonly nextAggregate: RelayAgentActivityAggregateState;
readonly preferences: RelayAgentAwarenessPreferences | null;
};
function rowKey(row: RelayAgentActivityAggregateRow): string {
return JSON.stringify([row.environmentId, row.threadId]);
}
function isAttentionPhase(phase: string): boolean {
return phase === "waiting_for_approval" || phase === "waiting_for_input";
}
export function alertAllowedForPhase(
preferences: RelayAgentAwarenessPreferences | null,
phase: string,
): boolean {
if (preferences === null) return true;
switch (phase) {
case "waiting_for_approval":
return preferences.notifyOnApproval;
case "waiting_for_input":
return preferences.notifyOnInput;
case "completed":
return preferences.notifyOnCompletion;
case "failed":
return preferences.notifyOnFailure;
default:
return false;
}
}
// A missing baseline is a replay, not a transition that should buzz the phone.
export function attentionTransitionRows(input: TransitionInput) {
if (input.previousAggregate === null) return [];
const previouslyAttention = new Set(
input.previousAggregate.activities.filter((row) => isAttentionPhase(row.phase)).map(rowKey),
);
return input.nextAggregate.activities.filter(
(row) =>
isAttentionPhase(row.phase) &&
!previouslyAttention.has(rowKey(row)) &&
alertAllowedForPhase(input.preferences, row.phase),
);
}
// Reconciliation uses only observed transitions. Event-driven delivery can
// include fresh completions whose running update never reached the device.
export function newlyTerminalRows(
previousAggregate: RelayAgentActivityAggregateState | null,
nextAggregate: RelayAgentActivityAggregateState,
includeUnobserved = false,
): ReadonlyArray<RelayAgentActivityAggregateRow> {
if (previousAggregate === null) return [];
const previousPhases = new Map(
previousAggregate.activities.map((row) => [rowKey(row), row.phase]),
);
return nextAggregate.activities.filter((row) => {
if (row.phase !== "completed" && row.phase !== "failed") return false;
const previousPhase = previousPhases.get(rowKey(row));
return (
(includeUnobserved || previousPhase !== undefined) &&
previousPhase !== "completed" &&
previousPhase !== "failed"
);
});
}
export function terminalTransitionRows(
input: TransitionInput & { readonly nowMs: number; readonly includeUnobserved?: boolean },
) {
return newlyTerminalRows(
input.previousAggregate,
input.nextAggregate,
input.includeUnobserved,
).filter((row) => {
return (
alertAllowedForPhase(input.preferences, row.phase) &&
isFreshTerminalNotification(row.updatedAt, input.nowMs)
);
});
}
export function alertForActivityRows(
rows: ReadonlyArray<RelayAgentActivityAggregateRow>,
): AgentActivityAlert | null {
const first = rows[0];
if (!first) return null;
if (rows.length === 1) {
return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };
}
return {
title: `${rows.length} agents ${isAttentionPhase(first.phase) ? "need attention" : "finished"}`,
body: rows.map((row) => row.threadTitle).join(", "),
};
}
export function alertForAttentionTransition(input: TransitionInput): AgentActivityAlert | null {
return alertForActivityRows(attentionTransitionRows(input));
}
export function alertForNewlyTerminal(
input: TransitionInput & { readonly nowMs: number; readonly includeUnobserved?: boolean },
): AgentActivityAlert | null {
return alertForActivityRows(terminalTransitionRows(input));
}
export function alertForTerminalAggregate(input: {
readonly aggregate: RelayAgentActivityAggregateState | null;
readonly preferences: RelayAgentAwarenessPreferences | null;
}): AgentActivityAlert | null {
const row = input.aggregate?.activities[0];
if (!row || (row.phase !== "completed" && row.phase !== "failed")) return null;
return alertAllowedForPhase(input.preferences, row.phase) ? alertForActivityRows([row]) : null;
}
export function shouldAlertForActivity(input: {
readonly phase: RelayAgentActivityAggregateRow["phase"];
readonly updatedAt: string;
readonly preferences: RelayAgentAwarenessPreferences | null;
readonly nowMs: number;
}): boolean {
return (
input.preferences?.notificationsEnabled === true &&
alertAllowedForPhase(input.preferences, input.phase) &&
((input.phase !== "completed" && input.phase !== "failed") ||
isFreshTerminalNotification(input.updatedAt, input.nowMs))
);
}
@@ -22,22 +22,29 @@ export function isTerminalPhase(state: RelayAgentActivityState): boolean {
const RUNNING_AGENT_ACTIVITY_ROW_TTL_MS = 2 * 60 * 60 * 1_000;
const WAITING_AGENT_ACTIVITY_ROW_TTL_MS = 24 * 60 * 60 * 1_000;
export function isExpiredAgentActivityState(
state: RelayAgentActivityState,
nowMs: number,
): boolean {
export function agentActivityExpiresAt(
state: Pick<RelayAgentActivityState, "phase" | "updatedAt">,
): number {
const updatedAtMs = Option.match(DateTime.make(state.updatedAt), {
onNone: () => Number.NaN,
onSome: (dt) => dt.epochMilliseconds,
});
if (Number.isNaN(updatedAtMs)) {
return true;
return Number.NaN;
}
const ttlMs =
state.phase === "running" || state.phase === "starting"
? RUNNING_AGENT_ACTIVITY_ROW_TTL_MS
: WAITING_AGENT_ACTIVITY_ROW_TTL_MS;
return nowMs - updatedAtMs > ttlMs;
return updatedAtMs + ttlMs;
}
export function isExpiredAgentActivityState(
state: RelayAgentActivityState,
nowMs: number,
): boolean {
const expiresAt = agentActivityExpiresAt(state);
return !Number.isFinite(expiresAt) || nowMs > expiresAt;
}
const MAX_SUMMARY_TEXT_LENGTH = 120;
@@ -99,3 +106,18 @@ export function sanitizeApnsNotificationPayload(
deepLink: sanitizeDeepLink(notification.deepLink),
};
}
export function notificationForActivity(
row: RelayAgentActivityAggregateRow,
): ApnsNotificationPayload {
const activity = sanitizeAgentActivityAggregateRow(row);
return sanitizeApnsNotificationPayload({
title: activity.threadTitle,
body: `${activity.status}: ${activity.projectTitle}`,
environmentId: activity.environmentId,
threadId: activity.threadId,
deepLink: activity.deepLink,
phase: activity.phase,
updatedAt: activity.updatedAt,
});
}
@@ -0,0 +1,105 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
import { makeAggregateState } from "./agentActivityAggregate.ts";
import {
attentionTransitionRows,
terminalTransitionRows,
shouldAlertForActivity,
} from "./agentActivityAlerts.ts";
const state: RelayAgentActivityState = {
environmentId: EnvironmentId.make("env"),
threadId: ThreadId.make("thread"),
projectTitle: "Project",
threadTitle: "Thread",
modelTitle: "Model",
headline: "Working",
phase: "running",
updatedAt: "1970-01-01T00:00:00.000Z",
deepLink: "/threads/env/thread",
};
const preferences = {
notificationsEnabled: true,
liveActivitiesEnabled: true,
notifyOnApproval: true,
notifyOnInput: true,
notifyOnCompletion: true,
notifyOnFailure: true,
};
const aggregate = (states: RelayAgentActivityState[]) =>
makeAggregateState({ activeStates: states, terminalState: null, nowMs: 0 })!;
describe("shared agent activity policy", () => {
it.each(["waiting_for_approval", "waiting_for_input"] as const)(
"keeps an older %s ahead of five running rows",
(phase) => {
const running = Array.from({ length: 5 }, (_, i) => ({
...state,
threadId: ThreadId.make(`running-${i}`),
}));
const waiting = { ...state, phase, updatedAt: "1969-12-31T23:59:00.000Z" };
const next = aggregate([...running, waiting]);
expect(next.activities[0]?.threadId).toBe(state.threadId);
expect(next.activeCount).toBe(6);
expect(next.activities).toHaveLength(5);
expect(
attentionTransitionRows({
previousAggregate: aggregate(running),
nextAggregate: next,
preferences,
}),
).toMatchObject([{ threadId: state.threadId }]);
},
);
it("allows fresh unobserved completions for events, but not reconciliation or repeats", () => {
const previousAggregate = aggregate([
{ ...state, threadId: ThreadId.make("old"), phase: "completed" },
]);
const nextAggregate = aggregate([{ ...state, phase: "completed" }]);
const input = { previousAggregate, nextAggregate, preferences, nowMs: 0 };
expect(terminalTransitionRows(input)).toEqual([]);
expect(terminalTransitionRows({ ...input, includeUnobserved: true })).toHaveLength(1);
expect(
terminalTransitionRows({
...input,
includeUnobserved: true,
previousAggregate: nextAggregate,
}),
).toEqual([]);
expect(terminalTransitionRows({ ...input, includeUnobserved: true, nowMs: 180_000 })).toEqual(
[],
);
});
it("distinguishes equal thread IDs across environments", () => {
const waiting = { ...state, phase: "waiting_for_input" as const };
const other = { ...waiting, environmentId: EnvironmentId.make("other") };
expect(
attentionTransitionRows({
previousAggregate: aggregate([waiting]),
nextAggregate: aggregate([waiting, other]),
preferences,
}),
).toMatchObject([{ environmentId: other.environmentId }]);
});
it("checks current permission, event preferences, and freshness together", () => {
const input = { ...state, phase: "completed" as const, preferences, nowMs: 0 };
expect(shouldAlertForActivity(input)).toBe(true);
expect(
shouldAlertForActivity({
...input,
preferences: { ...preferences, notificationsEnabled: false },
}),
).toBe(false);
expect(
shouldAlertForActivity({
...input,
preferences: { ...preferences, notifyOnCompletion: false },
}),
).toBe(false);
expect(shouldAlertForActivity({ ...input, nowMs: 180_000 })).toBe(false);
});
});