From cad68da05c05a291687ff8a160e1e399bd05a60b Mon Sep 17 00:00:00 2001 From: li4nee Date: Sat, 28 Nov 2026 19:26:52 +0545 Subject: [PATCH] feat: add agent operations Signed-off-by: li4nee --- README.md | 22 +- .../src/features/agent-operations/api.ts | 76 +++ .../components/operations-settings.tsx | 432 ++++++++++++++++++ .../components/conversation-detail.tsx | 2 + .../components/conversation-list.tsx | 5 + .../components/sla-indicator.spec.tsx | 22 + .../components/sla-indicator.tsx | 52 +++ .../features/conversations/detail.spec.tsx | 6 + .../src/features/conversations/inbox.spec.tsx | 6 + apps/admin/src/routeTree.gen.ts | 23 + .../w/$workspaceId/settings/operations.tsx | 13 + .../_app/w/$workspaceId/settings/route.tsx | 1 + apps/admin/src/strings.ts | 2 + apps/admin/src/strings/agent-operations.ts | 46 ++ apps/admin/src/strings/conversations.ts | 7 + apps/admin/src/strings/nav.ts | 1 + apps/admin/src/strings/notifications.ts | 1 + .../1794870000000-agent-operations.ts | 66 +++ .../agent-operations.controller.ts | 70 +++ .../conversations/agent-operations.job.ts | 14 + .../agent-operations.processor.ts | 13 + .../agent-operations.repository.int.spec.ts | 132 ++++++ .../agent-operations.repository.ts | 341 ++++++++++++++ .../agent-operations.schedule.ts | 20 + .../conversations/agent-operations.service.ts | 172 +++++++ .../agent-operations.sla.spec.ts | 65 +++ .../conversations/agent-operations.sla.ts | 160 +++++++ .../conversations/conversations.mapper.ts | 24 + .../conversations/conversations.module.ts | 16 +- .../entities/conversation.entity.ts | 14 +- .../handoff-notifier.listener.ts | 3 + .../modules/conversations/inbox.repository.ts | 10 + apps/api/src/modules/conversations/index.ts | 3 + .../conversations/notifications.int.spec.ts | 24 + .../notifications/notification.entity.ts | 1 + .../notifications/notification.events.ts | 5 + .../notifications/notifications.service.ts | 11 + .../workspaces/entities/membership.entity.ts | 9 + .../workspaces/entities/workspace.entity.ts | 3 + .../api/test/e2e/agent-operations.e2e.spec.ts | 109 +++++ .../src/content/docs/agent-productivity.md | 25 +- docs/spec.md | 9 +- .../plans/2026-11-28-m26-agent-operations.md | 91 ++++ packages/shared/src/agent-operations.spec.ts | 62 +++ packages/shared/src/agent-operations.ts | 230 ++++++++++ packages/shared/src/audit.ts | 4 + packages/shared/src/conversations.ts | 3 + packages/shared/src/index.ts | 17 + packages/shared/src/notifications.ts | 4 + 49 files changed, 2431 insertions(+), 16 deletions(-) create mode 100644 apps/admin/src/features/agent-operations/api.ts create mode 100644 apps/admin/src/features/agent-operations/components/operations-settings.tsx create mode 100644 apps/admin/src/features/conversations/components/sla-indicator.spec.tsx create mode 100644 apps/admin/src/features/conversations/components/sla-indicator.tsx create mode 100644 apps/admin/src/routes/_app/w/$workspaceId/settings/operations.tsx create mode 100644 apps/admin/src/strings/agent-operations.ts create mode 100644 apps/api/src/db/migrations/1794870000000-agent-operations.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.controller.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.job.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.processor.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.repository.int.spec.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.repository.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.schedule.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.service.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.sla.spec.ts create mode 100644 apps/api/src/modules/conversations/agent-operations.sla.ts create mode 100644 apps/api/test/e2e/agent-operations.e2e.spec.ts create mode 100644 docs/superpowers/plans/2026-11-28-m26-agent-operations.md create mode 100644 packages/shared/src/agent-operations.spec.ts create mode 100644 packages/shared/src/agent-operations.ts diff --git a/README.md b/README.md index d32839aa..8c95c29f 100644 --- a/README.md +++ b/README.md @@ -131,17 +131,23 @@ conversation into the team's inbox. The agent takes over and replies in the same These distinctions help set expectations when evaluating AiLoom for a support workflow: -| Area | Available today | Not included today | -| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -| Widget content | Safe Markdown, citations, handoff controls, optional email capture, feedback, CSAT, and admin-authored welcome cards/carousels, quick replies, and bounded forms | Model-generated cards, carousels, and actions inside assistant messages | -| Knowledge gaps | Ranked repeat-wording report for low/no-retrieval widget escalations, with bot/date filters, daily counts, example conversations, and links to knowledge review and corrections | Semantic topic clustering and scheduled gap digests | -| Agent operations | Shared inbox, manual assignment/release, priority, notifications, live replies, and historical first-response metrics | Rule-based auto-routing, agent availability/presence, load balancing, SLA targets, timers, and breach escalation | +| Area | Available today | Not included today | +| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| Widget content | Safe Markdown, citations, handoff controls, optional email capture, feedback, CSAT, and admin-authored welcome cards/carousels, quick replies, and bounded forms | Model-generated cards, carousels, and actions inside assistant messages | +| Knowledge gaps | Ranked repeat-wording report for low/no-retrieval widget escalations, with bot/date filters, daily counts, example conversations, and links to knowledge review and corrections | Semantic topic clustering and scheduled gap digests | +| Agent operations | Shared inbox, manual assignment/release, opt-in online/away presence, deterministic round-robin or least-loaded handoff routing, capacity limits, business-hours response/resolution SLAs, breach alerts, and historical metrics | Skills-based or AI-based routing, holidays, multi-step escalation policies, and automatic reassignment after an SLA breach | The unanswered report is specifically for widget conversations escalated because knowledge was missing or below threshold; it is not a list of every failed or unresolved conversation. The -first-human-response metric is retrospective analytics, not an active SLA policy. MCP support is an -outbound client for a configured remote server and a single selected read-only tool; AiLoom does -not expose an MCP server endpoint. +Auto-routing and SLA targets are disabled by default. Agents control their own presence; online and +away states expire after five minutes without a session heartbeat. Automatic assignment considers +only online members below the configured open-conversation limit and leaves the handoff in the +unassigned queue when no member qualifies. SLA clocks begin at human handoff, use the configured +IANA timezone and weekly business hours (an empty schedule means 24/7), and notify workspace owners +and admins after a target is missed. Policy changes apply to new handoffs. Holidays and automatic +breach reassignment are not supported. +MCP support is an outbound client for a configured remote server and a single selected read-only +tool; AiLoom does not expose an MCP server endpoint. The **Knowledge gaps** report groups eligible unanswered visitor messages per bot after lowercasing, trimming, collapsing whitespace, and removing trailing question marks. It counts each message once, diff --git a/apps/admin/src/features/agent-operations/api.ts b/apps/admin/src/features/agent-operations/api.ts new file mode 100644 index 00000000..5da72fd4 --- /dev/null +++ b/apps/admin/src/features/agent-operations/api.ts @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { z } from 'zod'; + +import { api } from '@/lib/api-client'; +import { + agentOperationsPolicySchema, + agentPresenceSchema, + agentPresenceUpdateSchema, + type AgentOperationsPolicyUpdate, + type AgentPresenceState, +} from '@app/shared'; + +const policyKey = (workspaceId: string) => ['workspaces', workspaceId, 'agent-operations'] as const; +const presenceKey = (workspaceId: string) => ['workspaces', workspaceId, 'agent-presence'] as const; + +export function useAgentOperationsPolicy(workspaceId: string, enabled: boolean) { + return useQuery({ + queryKey: policyKey(workspaceId), + queryFn: () => + api(`/v1/workspaces/${workspaceId}/agent-operations`, { + schema: agentOperationsPolicySchema, + }), + enabled, + }); +} + +export function useUpdateAgentOperationsPolicy(workspaceId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (input: AgentOperationsPolicyUpdate) => + api(`/v1/workspaces/${workspaceId}/agent-operations`, { + method: 'PUT', + body: input, + schema: agentOperationsPolicySchema, + }), + onSuccess: () => queryClient.invalidateQueries({ queryKey: policyKey(workspaceId) }), + }); +} + +export function useAgentPresence(workspaceId: string, enabled = true) { + return useQuery({ + queryKey: presenceKey(workspaceId), + queryFn: () => + api(`/v1/workspaces/${workspaceId}/agent-operations/presence`, { + schema: z.array(agentPresenceSchema), + }), + enabled, + refetchInterval: 30_000, + }); +} + +export function useSetAgentPresence(workspaceId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (state: AgentPresenceState) => + api(`/v1/workspaces/${workspaceId}/agent-operations/presence`, { + method: 'PUT', + body: agentPresenceUpdateSchema.parse({ state }), + schema: agentPresenceSchema, + }), + onSuccess: () => queryClient.invalidateQueries({ queryKey: presenceKey(workspaceId) }), + }); +} + +export function useHeartbeatAgentPresence(workspaceId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: () => + api(`/v1/workspaces/${workspaceId}/agent-operations/presence/heartbeat`, { + method: 'POST', + schema: agentPresenceSchema, + }), + onSuccess: () => queryClient.invalidateQueries({ queryKey: presenceKey(workspaceId) }), + }); +} diff --git a/apps/admin/src/features/agent-operations/components/operations-settings.tsx b/apps/admin/src/features/agent-operations/components/operations-settings.tsx new file mode 100644 index 00000000..a100ab89 --- /dev/null +++ b/apps/admin/src/features/agent-operations/components/operations-settings.tsx @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { useEffect, useState } from 'react'; + +import { FormAlert } from '@/components/form-alert'; +import { hasRole, RoleGate, useWorkspaceRole } from '@/components/role-gate'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useMe } from '@/features/auth/api'; +import { errorMessage } from '@/lib/error-message'; +import { strings } from '@/strings'; +import { + AGENT_PRESENCE_STATES, + PRIORITIES, + type AgentOperationsPolicy, + type AgentOperationsPolicyUpdate, + type AgentPresence, + type AgentPresenceState, + type Priority, +} from '@app/shared'; + +import { + useHeartbeatAgentPresence, + useAgentOperationsPolicy, + useAgentPresence, + useSetAgentPresence, + useUpdateAgentOperationsPolicy, +} from '../api'; + +type BusinessDay = keyof AgentOperationsPolicy['sla']['businessHours']; +type DayDraft = Record; + +const DAYS = [ + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday', +] as const satisfies readonly BusinessDay[]; + +function emptyDayDraft(): DayDraft { + return Object.fromEntries(DAYS.map((day) => [day, { start: '', end: '' }])) as DayDraft; +} + +function draftFromPolicy(policy: AgentOperationsPolicy): AgentOperationsPolicyUpdate { + return { + routing: { + enabled: policy.routing.enabled, + strategy: policy.routing.strategy, + maxOpenConversationsPerAgent: policy.routing.maxOpenConversationsPerAgent, + eligibleRoles: policy.routing.eligibleRoles, + }, + sla: policy.sla, + }; +} + +function daysFromPolicy(policy: AgentOperationsPolicy): DayDraft { + const days = emptyDayDraft(); + for (const day of DAYS) { + const [range] = policy.sla.businessHours[day]; + if (range !== undefined) days[day] = { start: range.start, end: range.end }; + } + return days; +} + +function policyWithHours( + policy: AgentOperationsPolicyUpdate, + dayDraft: DayDraft, +): AgentOperationsPolicyUpdate { + const businessHours = Object.fromEntries( + DAYS.map((day) => { + const { start, end } = dayDraft[day]; + return [day, start === '' && end === '' ? [] : [{ start, end }]]; + }), + ) as AgentOperationsPolicy['sla']['businessHours']; + return { ...policy, sla: { ...policy.sla, businessHours } }; +} + +function currentPresence(presence: AgentPresence[] | undefined, userId: string | undefined) { + return presence?.find((member) => member.userId === userId)?.state ?? 'offline'; +} + +export function OperationsSettings({ workspaceId }: { workspaceId: string }) { + const canAdmin = hasRole(useWorkspaceRole(), 'admin'); + const me = useMe(); + const policyQuery = useAgentOperationsPolicy(workspaceId, canAdmin); + const presenceQuery = useAgentPresence(workspaceId); + const heartbeatPresence = useHeartbeatAgentPresence(workspaceId); + const heartbeat = heartbeatPresence.mutate; + const updatePresence = useSetAgentPresence(workspaceId); + const copy = strings.agentOperations; + const mine = currentPresence(presenceQuery.data, me.data?.id); + + useEffect(() => { + if (mine === 'offline') return; + const interval = window.setInterval(() => { + heartbeat(); + }, 120_000); + return () => { + window.clearInterval(interval); + }; + }, [heartbeat, mine]); + + if (canAdmin && policyQuery.isPending) { + return

{copy.loading}

; + } + + return ( +
+
+

{copy.title}

+

{copy.intro}

+
+ +
+
+

+ {copy.presence} +

+

{copy.presenceHint}

+
+
+
+ + +
+ {updatePresence.isSuccess ?

{copy.saved}

: null} + +
+
+

{copy.teamPresence}

+ {presenceQuery.isError ? : null} +
    + {(presenceQuery.data ?? []).map((member) => ( +
  • + {member.name ?? member.email} + + {copy.presenceStates[member.state]} + +
  • + ))} + {presenceQuery.data?.length === 0 ? ( +
  • {copy.noMembers}
  • + ) : null} +
+
+
+ + {canAdmin && policyQuery.data !== undefined ? ( + + ) : canAdmin ? ( + + ) : ( +
+

{copy.readOnly}

+
+ )} +
+ ); +} + +function OperationsPolicyForm({ + workspaceId, + policy, + policyError, +}: { + workspaceId: string; + policy: AgentOperationsPolicy; + policyError: unknown; +}) { + const updatePolicy = useUpdateAgentOperationsPolicy(workspaceId); + const [draft, setDraft] = useState(() => draftFromPolicy(policy)); + const [dayDraft, setDayDraft] = useState(() => daysFromPolicy(policy)); + const copy = strings.agentOperations; + const hoursDraftInvalid = DAYS.some( + (day) => (dayDraft[day].start === '') !== (dayDraft[day].end === ''), + ); + return ( +
{ + event.preventDefault(); + if (hoursDraftInvalid) return; + updatePolicy.mutate(policyWithHours(draft, dayDraft)); + }} + > +
+
+

+ {copy.routing} +

+

{copy.routingHint}

+
+ +
+
+ + +
+
+ + { + setDraft({ + ...draft, + routing: { + ...draft.routing, + maxOpenConversationsPerAgent: Number(event.target.value), + }, + }); + }} + /> +
+
+
+ +
+
+

+ {copy.sla} +

+

{copy.slaHint}

+
+
+ + { + setDraft({ + ...draft, + sla: { ...draft.sla, timeZone: event.target.value }, + }); + }} + /> +
+
+

{copy.businessHours}

+
+ {DAYS.map((day) => ( +
+ + { + setDayDraft({ + ...dayDraft, + [day]: { ...dayDraft[day], start: event.target.value }, + }); + }} + /> + { + setDayDraft({ + ...dayDraft, + [day]: { ...dayDraft[day], end: event.target.value }, + }); + }} + /> +
+ ))} +
+

{copy.allDay}

+
+
+
+ + {copy.firstResponseMinutes} + {copy.resolutionMinutes} +
+ {PRIORITIES.map((priority) => ( +
+ {copy.priorities[priority]} + { + updateTarget(draft, setDraft, priority, 'firstResponseMinutes', value); + }} + /> + { + updateTarget(draft, setDraft, priority, 'resolutionMinutes', value); + }} + /> +
+ ))} +
+
+ + + {updatePolicy.isSuccess ?

{copy.saved}

: null} + + + + + ); +} + +function updateTarget( + policy: AgentOperationsPolicyUpdate, + setPolicy: (policy: AgentOperationsPolicyUpdate) => void, + priority: Priority, + field: 'firstResponseMinutes' | 'resolutionMinutes', + value: number | null, +) { + setPolicy({ + ...policy, + sla: { + ...policy.sla, + targets: { + ...policy.sla.targets, + [priority]: { ...policy.sla.targets[priority], [field]: value }, + }, + }, + }); +} + +function TargetInput({ + id, + label, + value, + onChange, +}: { + id: string; + label: string; + value: number | null; + onChange: (value: number | null) => void; +}) { + return ( +
+ + { + onChange(event.target.value === '' ? null : Number(event.target.value)); + }} + /> +
+ ); +} diff --git a/apps/admin/src/features/conversations/components/conversation-detail.tsx b/apps/admin/src/features/conversations/components/conversation-detail.tsx index de29f342..53ed89d9 100644 --- a/apps/admin/src/features/conversations/components/conversation-detail.tsx +++ b/apps/admin/src/features/conversations/components/conversation-detail.tsx @@ -24,6 +24,7 @@ import { ConversationQueue } from './conversation-queue'; import { InternalNotes } from './internal-notes'; import { MessageTimeline } from './message-timeline'; import { ReplyComposer } from './reply-composer'; +import { SlaIndicator } from './sla-indicator'; import { StatusBadge } from './status-badge'; export function ConversationDetail({ @@ -95,6 +96,7 @@ export function ConversationDetail({ {owner === null ? null : ( {strings.conversations.detail.assignedTo(owner.name)} )} +

{contact.email === null ? null : (

{contact.email}

diff --git a/apps/admin/src/features/conversations/components/conversation-list.tsx b/apps/admin/src/features/conversations/components/conversation-list.tsx index c1e10c0b..b7dd96b7 100644 --- a/apps/admin/src/features/conversations/components/conversation-list.tsx +++ b/apps/admin/src/features/conversations/components/conversation-list.tsx @@ -14,6 +14,7 @@ import { strings } from '@/strings'; import type { ConversationListItem } from '@app/shared'; import type { InboxFilters } from '../api'; +import { SlaIndicator } from './sla-indicator'; import { StatusBadge } from './status-badge'; function time(value: string): { label: string; exact: string } { @@ -104,6 +105,7 @@ export function ConversationList({ {conversation.assignedTo?.name ?? strings.conversations.unassigned} + @@ -159,6 +161,9 @@ function DesktopConversationTable({ {conversation.contact.email}

)} +
+ +
{conversation.botName} diff --git a/apps/admin/src/features/conversations/components/sla-indicator.spec.tsx b/apps/admin/src/features/conversations/components/sla-indicator.spec.tsx new file mode 100644 index 00000000..af6a91cd --- /dev/null +++ b/apps/admin/src/features/conversations/components/sla-indicator.spec.tsx @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import type { ConversationSla } from '@app/shared'; + +import { SlaIndicator } from './sla-indicator'; + +describe('SlaIndicator', () => { + it('identifies the resolution clock when the first response is already complete', () => { + const sla: ConversationSla = { + firstResponseDueAt: null, + resolutionDueAt: new Date(Date.now() + 5 * 60_000).toISOString(), + firstResponseBreachedAt: null, + resolutionBreachedAt: null, + }; + + render(); + + expect(screen.getByText(/^Resolution: Due in/)).toBeInTheDocument(); + }); +}); diff --git a/apps/admin/src/features/conversations/components/sla-indicator.tsx b/apps/admin/src/features/conversations/components/sla-indicator.tsx new file mode 100644 index 00000000..8c0bee03 --- /dev/null +++ b/apps/admin/src/features/conversations/components/sla-indicator.tsx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { useEffect, useState } from 'react'; + +import { Badge } from '@/components/ui/badge'; +import { strings } from '@/strings'; +import type { ConversationSla } from '@app/shared'; + +export function SlaIndicator({ sla }: { sla: ConversationSla }) { + const [now, setNow] = useState(() => Date.now()); + const responseDue = sla.firstResponseDueAt; + const resolutionDue = sla.resolutionDueAt; + + useEffect(() => { + if (responseDue === null && resolutionDue === null) return; + const interval = window.setInterval(() => { + setNow(Date.now()); + }, 30_000); + return () => { + window.clearInterval(interval); + }; + }, [responseDue, resolutionDue]); + + const responseBreached = sla.firstResponseBreachedAt !== null; + const resolutionBreached = sla.resolutionBreachedAt !== null; + if (!responseBreached && !resolutionBreached && responseDue === null && resolutionDue === null) { + return null; + } + + const activeDeadlines = [ + ...(responseDue === null ? [] : [{ kind: 'firstResponse' as const, at: responseDue }]), + ...(resolutionDue === null ? [] : [{ kind: 'resolution' as const, at: resolutionDue }]), + ].sort((left, right) => Date.parse(left.at) - Date.parse(right.at)); + const nextDeadline = activeDeadlines[0]; + const overdue = nextDeadline !== undefined && Date.parse(nextDeadline.at) <= now; + const remainingMinutes = + nextDeadline === undefined + ? 0 + : Math.max(0, Math.ceil((Date.parse(nextDeadline.at) - now) / 60_000)); + const label = responseBreached + ? `${strings.conversations.sla.firstResponse}: ${strings.conversations.sla.breached}` + : resolutionBreached + ? `${strings.conversations.sla.resolution}: ${strings.conversations.sla.breached}` + : `${ + strings.conversations.sla[nextDeadline?.kind ?? 'firstResponse'] + }: ${overdue ? strings.conversations.sla.overdue : strings.conversations.sla.dueIn(remainingMinutes)}`; + + return ( + + {label} + + ); +} diff --git a/apps/admin/src/features/conversations/detail.spec.tsx b/apps/admin/src/features/conversations/detail.spec.tsx index 7fef8813..ea4a8fdd 100644 --- a/apps/admin/src/features/conversations/detail.spec.tsx +++ b/apps/admin/src/features/conversations/detail.spec.tsx @@ -54,6 +54,12 @@ const DETAIL: Detail = { lastMessageAt: '2026-11-15T10:02:00Z', closedAt: null, metadata: {}, + sla: { + firstResponseDueAt: null, + resolutionDueAt: null, + firstResponseBreachedAt: null, + resolutionBreachedAt: null, + }, createdAt: '2026-11-15T10:00:00Z', }, contact: { diff --git a/apps/admin/src/features/conversations/inbox.spec.tsx b/apps/admin/src/features/conversations/inbox.spec.tsx index c9389e58..3080701f 100644 --- a/apps/admin/src/features/conversations/inbox.spec.tsx +++ b/apps/admin/src/features/conversations/inbox.spec.tsx @@ -49,6 +49,12 @@ const CONVERSATION: ConversationListItem = { lastMessageAt: '2026-11-15T10:00:00Z', lastMessagePreview: 'Can a person help?', unansweredByHuman: true, + sla: { + firstResponseDueAt: null, + resolutionDueAt: null, + firstResponseBreachedAt: null, + resolutionBreachedAt: null, + }, }; const routes = (): Record => ({ diff --git a/apps/admin/src/routeTree.gen.ts b/apps/admin/src/routeTree.gen.ts index dedc22a9..3978814b 100644 --- a/apps/admin/src/routeTree.gen.ts +++ b/apps/admin/src/routeTree.gen.ts @@ -43,6 +43,7 @@ import { Route as AppWWorkspaceIdSettingsIntegrationsRouteImport } from './route import { Route as AppWWorkspaceIdSettingsInvitationsRouteImport } from './routes/_app/w/$workspaceId/settings/invitations' import { Route as AppWWorkspaceIdSettingsMembersRouteImport } from './routes/_app/w/$workspaceId/settings/members' import { Route as AppWWorkspaceIdSettingsNotificationsRouteImport } from './routes/_app/w/$workspaceId/settings/notifications' +import { Route as AppWWorkspaceIdSettingsOperationsRouteImport } from './routes/_app/w/$workspaceId/settings/operations' import { Route as AppWWorkspaceIdSettingsSavedRepliesRouteImport } from './routes/_app/w/$workspaceId/settings/saved-replies' import { Route as AppWWorkspaceIdUsageIndexRouteImport } from './routes/_app/w/$workspaceId/usage/index' import { Route as AppWWorkspaceIdUsageFeedbackRouteImport } from './routes/_app/w/$workspaceId/usage/feedback' @@ -250,6 +251,12 @@ const AppWWorkspaceIdSettingsNotificationsRoute = path: '/notifications', getParentRoute: () => AppWWorkspaceIdSettingsRouteRoute, } as any) +const AppWWorkspaceIdSettingsOperationsRoute = + AppWWorkspaceIdSettingsOperationsRouteImport.update({ + id: '/operations', + path: '/operations', + getParentRoute: () => AppWWorkspaceIdSettingsRouteRoute, + } as any) const AppWWorkspaceIdSettingsSavedRepliesRoute = AppWWorkspaceIdSettingsSavedRepliesRouteImport.update({ id: '/saved-replies', @@ -402,6 +409,7 @@ export interface FileRoutesByFullPath { '/w/$workspaceId/settings/invitations': typeof AppWWorkspaceIdSettingsInvitationsRoute '/w/$workspaceId/settings/members': typeof AppWWorkspaceIdSettingsMembersRoute '/w/$workspaceId/settings/notifications': typeof AppWWorkspaceIdSettingsNotificationsRoute + '/w/$workspaceId/settings/operations': typeof AppWWorkspaceIdSettingsOperationsRoute '/w/$workspaceId/settings/saved-replies': typeof AppWWorkspaceIdSettingsSavedRepliesRoute '/w/$workspaceId/usage/feedback': typeof AppWWorkspaceIdUsageFeedbackRoute '/w/$workspaceId/usage/knowledge-gaps': typeof AppWWorkspaceIdUsageKnowledgeGapsRoute @@ -452,6 +460,7 @@ export interface FileRoutesByTo { '/w/$workspaceId/settings/invitations': typeof AppWWorkspaceIdSettingsInvitationsRoute '/w/$workspaceId/settings/members': typeof AppWWorkspaceIdSettingsMembersRoute '/w/$workspaceId/settings/notifications': typeof AppWWorkspaceIdSettingsNotificationsRoute + '/w/$workspaceId/settings/operations': typeof AppWWorkspaceIdSettingsOperationsRoute '/w/$workspaceId/settings/saved-replies': typeof AppWWorkspaceIdSettingsSavedRepliesRoute '/w/$workspaceId/usage/feedback': typeof AppWWorkspaceIdUsageFeedbackRoute '/w/$workspaceId/usage/knowledge-gaps': typeof AppWWorkspaceIdUsageKnowledgeGapsRoute @@ -509,6 +518,7 @@ export interface FileRoutesById { '/_app/w/$workspaceId/settings/invitations': typeof AppWWorkspaceIdSettingsInvitationsRoute '/_app/w/$workspaceId/settings/members': typeof AppWWorkspaceIdSettingsMembersRoute '/_app/w/$workspaceId/settings/notifications': typeof AppWWorkspaceIdSettingsNotificationsRoute + '/_app/w/$workspaceId/settings/operations': typeof AppWWorkspaceIdSettingsOperationsRoute '/_app/w/$workspaceId/settings/saved-replies': typeof AppWWorkspaceIdSettingsSavedRepliesRoute '/_app/w/$workspaceId/usage/feedback': typeof AppWWorkspaceIdUsageFeedbackRoute '/_app/w/$workspaceId/usage/knowledge-gaps': typeof AppWWorkspaceIdUsageKnowledgeGapsRoute @@ -566,6 +576,7 @@ export interface FileRouteTypes { | '/w/$workspaceId/settings/invitations' | '/w/$workspaceId/settings/members' | '/w/$workspaceId/settings/notifications' + | '/w/$workspaceId/settings/operations' | '/w/$workspaceId/settings/saved-replies' | '/w/$workspaceId/usage/feedback' | '/w/$workspaceId/usage/knowledge-gaps' @@ -616,6 +627,7 @@ export interface FileRouteTypes { | '/w/$workspaceId/settings/invitations' | '/w/$workspaceId/settings/members' | '/w/$workspaceId/settings/notifications' + | '/w/$workspaceId/settings/operations' | '/w/$workspaceId/settings/saved-replies' | '/w/$workspaceId/usage/feedback' | '/w/$workspaceId/usage/knowledge-gaps' @@ -672,6 +684,7 @@ export interface FileRouteTypes { | '/_app/w/$workspaceId/settings/invitations' | '/_app/w/$workspaceId/settings/members' | '/_app/w/$workspaceId/settings/notifications' + | '/_app/w/$workspaceId/settings/operations' | '/_app/w/$workspaceId/settings/saved-replies' | '/_app/w/$workspaceId/usage/feedback' | '/_app/w/$workspaceId/usage/knowledge-gaps' @@ -947,6 +960,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AppWWorkspaceIdSettingsNotificationsRouteImport parentRoute: typeof AppWWorkspaceIdSettingsRouteRoute } + '/_app/w/$workspaceId/settings/operations': { + id: '/_app/w/$workspaceId/settings/operations' + path: '/operations' + fullPath: '/w/$workspaceId/settings/operations' + preLoaderRoute: typeof AppWWorkspaceIdSettingsOperationsRouteImport + parentRoute: typeof AppWWorkspaceIdSettingsRouteRoute + } '/_app/w/$workspaceId/settings/saved-replies': { id: '/_app/w/$workspaceId/settings/saved-replies' path: '/saved-replies' @@ -1098,6 +1118,7 @@ interface AppWWorkspaceIdSettingsRouteRouteChildren { AppWWorkspaceIdSettingsInvitationsRoute: typeof AppWWorkspaceIdSettingsInvitationsRoute AppWWorkspaceIdSettingsMembersRoute: typeof AppWWorkspaceIdSettingsMembersRoute AppWWorkspaceIdSettingsNotificationsRoute: typeof AppWWorkspaceIdSettingsNotificationsRoute + AppWWorkspaceIdSettingsOperationsRoute: typeof AppWWorkspaceIdSettingsOperationsRoute AppWWorkspaceIdSettingsSavedRepliesRoute: typeof AppWWorkspaceIdSettingsSavedRepliesRoute AppWWorkspaceIdSettingsIndexRoute: typeof AppWWorkspaceIdSettingsIndexRoute } @@ -1115,6 +1136,8 @@ const AppWWorkspaceIdSettingsRouteRouteChildren: AppWWorkspaceIdSettingsRouteRou AppWWorkspaceIdSettingsMembersRoute: AppWWorkspaceIdSettingsMembersRoute, AppWWorkspaceIdSettingsNotificationsRoute: AppWWorkspaceIdSettingsNotificationsRoute, + AppWWorkspaceIdSettingsOperationsRoute: + AppWWorkspaceIdSettingsOperationsRoute, AppWWorkspaceIdSettingsSavedRepliesRoute: AppWWorkspaceIdSettingsSavedRepliesRoute, AppWWorkspaceIdSettingsIndexRoute: AppWWorkspaceIdSettingsIndexRoute, diff --git a/apps/admin/src/routes/_app/w/$workspaceId/settings/operations.tsx b/apps/admin/src/routes/_app/w/$workspaceId/settings/operations.tsx new file mode 100644 index 00000000..83795f87 --- /dev/null +++ b/apps/admin/src/routes/_app/w/$workspaceId/settings/operations.tsx @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { createFileRoute } from '@tanstack/react-router'; + +import { OperationsSettings } from '@/features/agent-operations/components/operations-settings'; + +export const Route = createFileRoute('/_app/w/$workspaceId/settings/operations')({ + component: OperationsPage, +}); + +function OperationsPage() { + const { workspaceId } = Route.useParams(); + return ; +} diff --git a/apps/admin/src/routes/_app/w/$workspaceId/settings/route.tsx b/apps/admin/src/routes/_app/w/$workspaceId/settings/route.tsx index 5358999e..acf0c791 100644 --- a/apps/admin/src/routes/_app/w/$workspaceId/settings/route.tsx +++ b/apps/admin/src/routes/_app/w/$workspaceId/settings/route.tsx @@ -19,6 +19,7 @@ function SettingsLayout() { ['/w/$workspaceId/settings/invitations', strings.nav.invitations, isAdmin], ['/w/$workspaceId/settings/audit-log', strings.nav.auditLog, isAdmin], ['/w/$workspaceId/settings/saved-replies', strings.nav.savedReplies, isAdmin], + ['/w/$workspaceId/settings/operations', strings.nav.agentOperations, true], ['/w/$workspaceId/settings/notifications', strings.nav.notificationPreferences, true], ] as const; diff --git a/apps/admin/src/strings.ts b/apps/admin/src/strings.ts index e874f0c9..948d9bcf 100644 --- a/apps/admin/src/strings.ts +++ b/apps/admin/src/strings.ts @@ -4,6 +4,7 @@ * one place and a later translation has a single source. */ import { account } from './strings/account'; +import { agentOperations } from './strings/agent-operations'; import { app } from './strings/app'; import { audit } from './strings/audit'; import { auth } from './strings/auth'; @@ -47,6 +48,7 @@ export const strings = { workspaces, members, account, + agentOperations, instance, audit, } as const; diff --git a/apps/admin/src/strings/agent-operations.ts b/apps/admin/src/strings/agent-operations.ts new file mode 100644 index 00000000..e665c1eb --- /dev/null +++ b/apps/admin/src/strings/agent-operations.ts @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: AGPL-3.0-only +export const agentOperations = { + title: 'Agent operations', + intro: 'Set availability, automatic handoff assignment, and response targets for your team.', + presence: 'Your availability', + presenceHint: 'Availability expires after five minutes without a refresh.', + presenceStates: { online: 'Online', away: 'Away', offline: 'Offline' }, + teamPresence: 'Team availability', + offline: 'Offline', + noMembers: 'No team members found.', + routing: 'Automatic assignment', + routingHint: 'Only online teammates below capacity receive new human handoffs.', + enableRouting: 'Automatically assign human handoffs', + strategy: 'Assignment strategy', + strategies: { round_robin: 'Round robin', least_loaded: 'Least loaded' }, + capacity: 'Open conversations per agent', + sla: 'Response and resolution targets', + slaHint: + 'Targets use the current priority at human handoff and apply to new handoffs. Empty hours mean 24/7.', + timezone: 'Business-hours timezone', + businessHours: 'Weekly business hours', + allDay: 'Leave all days empty for 24/7 coverage.', + start: 'Opens', + end: 'Closes', + priorities: { low: 'Low', normal: 'Normal', high: 'High', urgent: 'Urgent' }, + firstResponseMinutes: 'First response (minutes)', + resolutionMinutes: 'Resolution (minutes)', + disabledTarget: 'No target', + save: 'Save operations settings', + saved: 'Operations settings saved.', + readOnly: 'Only workspace admins can change routing and SLA settings.', + loading: 'Loading operations settings…', + loadFailed: 'Could not load operations settings.', + presenceFailed: 'Could not load team availability.', + saveFailed: 'Could not save operations settings.', + days: { + monday: 'Monday', + tuesday: 'Tuesday', + wednesday: 'Wednesday', + thursday: 'Thursday', + friday: 'Friday', + saturday: 'Saturday', + sunday: 'Sunday', + }, + minutes: 'min', +} as const; diff --git a/apps/admin/src/strings/conversations.ts b/apps/admin/src/strings/conversations.ts index 471d36c8..467cc319 100644 --- a/apps/admin/src/strings/conversations.ts +++ b/apps/admin/src/strings/conversations.ts @@ -38,6 +38,13 @@ export const conversations = { emptyFilters: 'No conversations match these filters.', needsHuman: 'Needs human', lastMessage: 'Last message', + sla: { + firstResponse: 'First response', + resolution: 'Resolution', + breached: 'Breached', + overdue: 'Overdue', + dueIn: (minutes: number) => `Due in ${String(minutes)} min`, + }, open: 'Open', notifications: 'Desktop notifications', notificationsHint: 'Play a sound and notify when a conversation needs a person.', diff --git a/apps/admin/src/strings/nav.ts b/apps/admin/src/strings/nav.ts index aa514a07..64a374d8 100644 --- a/apps/admin/src/strings/nav.ts +++ b/apps/admin/src/strings/nav.ts @@ -13,6 +13,7 @@ export const nav = { auditLog: 'Audit log', savedReplies: 'Saved replies', notificationPreferences: 'Notifications', + agentOperations: 'Agent operations', account: 'Account', sessions: 'Sessions', instance: 'Instance', diff --git a/apps/admin/src/strings/notifications.ts b/apps/admin/src/strings/notifications.ts index 10e3c8b1..92cd400c 100644 --- a/apps/admin/src/strings/notifications.ts +++ b/apps/admin/src/strings/notifications.ts @@ -20,5 +20,6 @@ export const notifications = { spend_alert: 'A bot reached a spend threshold', suggestion_created: 'A knowledge correction needs review', suggestion_reviewed: 'Your correction was reviewed', + sla_breached: 'A conversation missed an SLA target', }, } as const; diff --git a/apps/api/src/db/migrations/1794870000000-agent-operations.ts b/apps/api/src/db/migrations/1794870000000-agent-operations.ts new file mode 100644 index 00000000..0614df0a --- /dev/null +++ b/apps/api/src/db/migrations/1794870000000-agent-operations.ts @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AgentOperations1794870000000 implements MigrationInterface { + name = 'AgentOperations1794870000000'; + + async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TYPE "public"."notification_type" ADD VALUE 'sla_breached'`); + await queryRunner.query( + `ALTER TABLE "workspaces" ADD "agent_operations" jsonb NOT NULL DEFAULT '{}'`, + ); + await queryRunner.query( + `ALTER TABLE "memberships" ADD "presence_state" text NOT NULL DEFAULT 'offline'`, + ); + await queryRunner.query( + `ALTER TABLE "memberships" ADD CONSTRAINT "memberships_presence_state_check" CHECK ("presence_state" IN ('online', 'away', 'offline'))`, + ); + await queryRunner.query( + `ALTER TABLE "memberships" ADD "presence_expires_at" TIMESTAMP WITH TIME ZONE`, + ); + await queryRunner.query( + `ALTER TABLE "conversations" ADD "first_response_due_at" TIMESTAMP WITH TIME ZONE`, + ); + await queryRunner.query( + `ALTER TABLE "conversations" ADD "resolution_due_at" TIMESTAMP WITH TIME ZONE`, + ); + await queryRunner.query( + `ALTER TABLE "conversations" ADD "first_response_breached_at" TIMESTAMP WITH TIME ZONE`, + ); + await queryRunner.query( + `ALTER TABLE "conversations" ADD "resolution_breached_at" TIMESTAMP WITH TIME ZONE`, + ); + await queryRunner.query( + `CREATE INDEX "conversations_sla_due_idx" ON "conversations" ("first_response_due_at", "resolution_due_at") WHERE "status" IN ('needs_human', 'human') AND "closed_at" IS NULL`, + ); + await queryRunner.query( + `CREATE INDEX "memberships_presence_idx" ON "memberships" ("workspace_id", "presence_state", "presence_expires_at")`, + ); + } + + async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DELETE FROM "notifications" WHERE "type" = 'sla_breached'`); + await queryRunner.query(`DROP INDEX "memberships_presence_idx"`); + await queryRunner.query(`DROP INDEX "conversations_sla_due_idx"`); + await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN "resolution_breached_at"`); + await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN "first_response_breached_at"`); + await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN "resolution_due_at"`); + await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN "first_response_due_at"`); + await queryRunner.query( + `ALTER TABLE "memberships" DROP CONSTRAINT "memberships_presence_state_check"`, + ); + await queryRunner.query(`ALTER TABLE "memberships" DROP COLUMN "presence_expires_at"`); + await queryRunner.query(`ALTER TABLE "memberships" DROP COLUMN "presence_state"`); + await queryRunner.query(`ALTER TABLE "workspaces" DROP COLUMN "agent_operations"`); + await queryRunner.query( + `ALTER TYPE "public"."notification_type" RENAME TO "notification_type_old"`, + ); + await queryRunner.query( + `CREATE TYPE "public"."notification_type" AS ENUM('handoff_requested', 'conversation_assigned', 'visitor_replied', 'spend_alert', 'suggestion_created', 'suggestion_reviewed')`, + ); + await queryRunner.query( + `ALTER TABLE "notifications" ALTER COLUMN "type" TYPE "public"."notification_type" USING "type"::text::"public"."notification_type"`, + ); + await queryRunner.query(`DROP TYPE "public"."notification_type_old"`); + } +} diff --git a/apps/api/src/modules/conversations/agent-operations.controller.ts b/apps/api/src/modules/conversations/agent-operations.controller.ts new file mode 100644 index 00000000..31fd172b --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.controller.ts @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { Body, Controller, Get, Post, Put } from '@nestjs/common'; +import { createZodDto } from 'nestjs-zod'; + +import { + agentOperationsPolicyUpdateSchema, + agentPresenceUpdateSchema, + type AgentOperationsPolicy, + type AgentPresence, +} from '@app/shared'; + +import { AppError } from '../../common/errors'; +import type { WorkspaceId } from '../../db/ids'; +import { CurrentPrincipal, RequireRole, SessionOnly, type Principal } from '../auth'; +import { AgentOperationsService } from './agent-operations.service'; + +class AgentOperationsPolicyDto extends createZodDto(agentOperationsPolicyUpdateSchema) {} +class AgentPresenceDto extends createZodDto(agentPresenceUpdateSchema) {} + +@SessionOnly() +@Controller('v1/workspaces/:workspaceId/agent-operations') +export class AgentOperationsController { + constructor(private readonly operations: AgentOperationsService) {} + + @Get() + @RequireRole('admin') + getPolicy(@CurrentPrincipal() principal: Principal): Promise { + return this.operations.getPolicy(this.workspaceOf(principal)); + } + + @Put() + @RequireRole('admin') + updatePolicy( + @CurrentPrincipal() principal: Principal, + @Body() body: AgentOperationsPolicyDto, + ): Promise { + return this.operations.updatePolicy(this.workspaceOf(principal), principal.userId, body); + } + + @Get('presence') + @RequireRole('agent') + listPresence(@CurrentPrincipal() principal: Principal): Promise { + return this.operations.listPresence(this.workspaceOf(principal)); + } + + @Put('presence') + @RequireRole('agent') + updatePresence( + @CurrentPrincipal() principal: Principal, + @Body() body: AgentPresenceDto, + ): Promise { + return this.operations.updatePresence( + this.workspaceOf(principal), + principal.userId, + body.state, + ); + } + + @Post('presence/heartbeat') + @RequireRole('agent') + heartbeatPresence(@CurrentPrincipal() principal: Principal): Promise { + return this.operations.heartbeatPresence(this.workspaceOf(principal), principal.userId); + } + + private workspaceOf(principal: Principal): WorkspaceId { + const workspaceId = principal.workspace?.id; + if (workspaceId === undefined) throw new AppError('not_found'); + return workspaceId; + } +} diff --git a/apps/api/src/modules/conversations/agent-operations.job.ts b/apps/api/src/modules/conversations/agent-operations.job.ts new file mode 100644 index 00000000..5c773168 --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.job.ts @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { z } from 'zod'; + +import { defineJob } from '../../jobs'; + +export const REVIEW_SLA_BREACHES_JOB = defineJob({ + name: 'conversations.review_sla_breaches', + schema: z.object({}), + retryLimit: 3, + retryBackoff: true, + concurrency: 1, +}); + +export const SLA_REVIEW_SCHEDULE = '* * * * *'; diff --git a/apps/api/src/modules/conversations/agent-operations.processor.ts b/apps/api/src/modules/conversations/agent-operations.processor.ts new file mode 100644 index 00000000..9793cb1f --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.processor.ts @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { type JobHandler, JobProcessor } from '../../jobs'; +import { REVIEW_SLA_BREACHES_JOB } from './agent-operations.job'; +import { AgentOperationsService } from './agent-operations.service'; + +@JobProcessor(REVIEW_SLA_BREACHES_JOB) +export class AgentOperationsProcessor implements JobHandler> { + constructor(private readonly operations: AgentOperationsService) {} + + async handle(): Promise { + await this.operations.processSlaBreaches(); + } +} diff --git a/apps/api/src/modules/conversations/agent-operations.repository.int.spec.ts b/apps/api/src/modules/conversations/agent-operations.repository.int.spec.ts new file mode 100644 index 00000000..b92711d2 --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.repository.int.spec.ts @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import type { DataSource } from 'typeorm'; +import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { DEFAULT_AGENT_OPERATIONS_POLICY } from '@app/shared'; + +import { getTestDataSource, resetDatabase } from '../../../test/helpers/db'; +import { addMember, createUser, createWorkspace } from '../../../test/helpers/factories'; +import { asWorkspaceId } from '../../db/ids'; +import { AgentOperationsRepository } from './agent-operations.repository'; + +let ds: DataSource; +let repository: AgentOperationsRepository; + +beforeAll(async () => { + ds = await getTestDataSource(); + repository = new AgentOperationsRepository(ds); +}); + +beforeEach(async () => { + await resetDatabase(ds); +}); + +async function seedHandoffs() { + const owner = await createUser({ ds }, { email: 'ops-owner@example.com' }); + const workspace = await createWorkspace({ ds }, owner.user, 'Agent operations'); + const agents = await Promise.all([ + createUser({ ds }, { email: 'amy-agent@example.com' }), + createUser({ ds }, { email: 'ben-agent@example.com' }), + ]); + await Promise.all(agents.map(({ user }) => addMember({ ds }, workspace, user, 'agent'))); + await ds.query( + `UPDATE memberships + SET presence_state = 'online', presence_expires_at = now() + interval '5 minutes' + WHERE workspace_id = $1 AND role = 'agent'`, + [workspace.id], + ); + const credential = await ds.query<{ id: string }[]>( + `INSERT INTO provider_credentials (workspace_id, provider, label) + VALUES ($1, 'mock', 'Agent operations') RETURNING id`, + [workspace.id], + ); + const bot = await ds.query<{ id: string }[]>( + `INSERT INTO bots (workspace_id, name, public_key, chat_credential_id, chat_model, + embedding_credential_id, embedding_model, embedding_dim) + VALUES ($1, 'Support', 'pk_live_agent_operations', $2, 'mock-chat', $2, + 'mock-embed', 384) RETURNING id`, + [workspace.id, credential[0]?.id], + ); + const contact = await ds.query<{ id: string }[]>( + `INSERT INTO contacts (workspace_id) VALUES ($1) RETURNING id`, + [workspace.id], + ); + const conversations = await ds.query<{ id: string }[]>( + `INSERT INTO conversations (workspace_id, bot_id, contact_id, status, handoff_requested_at) + SELECT $1, $2, $3, 'needs_human', now() + FROM generate_series(1, 2) + RETURNING id`, + [workspace.id, bot[0]?.id, contact[0]?.id], + ); + const policy = { + ...DEFAULT_AGENT_OPERATIONS_POLICY, + routing: { + ...DEFAULT_AGENT_OPERATIONS_POLICY.routing, + enabled: true, + maxOpenConversationsPerAgent: 1, + }, + }; + await ds.query('UPDATE workspaces SET agent_operations = $2 WHERE id = $1', [ + workspace.id, + JSON.stringify(policy), + ]); + return { + workspaceId: asWorkspaceId(workspace.id), + agentIds: agents.map(({ user }) => user.id), + conversationIds: conversations.map(({ id }) => id), + }; +} + +describe('AgentOperationsRepository', () => { + it('serializes concurrent handoffs so round-robin routing respects each capacity', async () => { + const { workspaceId, agentIds, conversationIds } = await seedHandoffs(); + const now = new Date(); + const assigned = await Promise.all( + conversationIds.map((id) => repository.autoAssign(workspaceId, id, now)), + ); + + expect(assigned.every((result) => result !== null)).toBe(true); + expect(new Set(assigned.map((result) => result?.assignedUserId)).size).toBe(2); + expect(assigned.every((result) => agentIds.includes(result?.assignedUserId ?? ''))).toBe(true); + }); + + it('does not route to an online member whose presence lease has expired', async () => { + const { workspaceId, conversationIds } = await seedHandoffs(); + await ds.query( + `UPDATE memberships SET presence_expires_at = now() - interval '1 second' + WHERE workspace_id = $1 AND role = 'agent'`, + [workspaceId], + ); + + expect( + await repository.autoAssign(workspaceId, conversationIds[0] ?? '', new Date()), + ).toBeNull(); + }); + + it('marks each due SLA breach once, including both targets on one conversation', async () => { + const { workspaceId, conversationIds } = await seedHandoffs(); + const conversationId = conversationIds[0] ?? ''; + const dueAt = new Date(Date.now() - 60_000); + await ds.query( + `UPDATE conversations + SET first_response_due_at = $3, resolution_due_at = $3 + WHERE workspace_id = $1 AND id = $2`, + [workspaceId, conversationId, dueAt], + ); + + const [firstScan, secondScan] = await ds.transaction(async (manager) => { + const first = await repository.claimSlaBreaches(new Date(), manager, 100); + const second = await repository.claimSlaBreaches(new Date(), manager, 100); + return [first, second]; + }); + + expect(firstScan).toEqual( + expect.arrayContaining([ + expect.objectContaining({ conversationId, breach: 'first_response' }), + expect.objectContaining({ conversationId, breach: 'resolution' }), + ]), + ); + expect(firstScan).toHaveLength(2); + expect(secondScan).toHaveLength(0); + }); +}); diff --git a/apps/api/src/modules/conversations/agent-operations.repository.ts b/apps/api/src/modules/conversations/agent-operations.repository.ts new file mode 100644 index 00000000..31444e57 --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.repository.ts @@ -0,0 +1,341 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { Injectable } from '@nestjs/common'; +import { DataSource, IsNull } from 'typeorm'; +import type { EntityManager } from 'typeorm'; + +import { + DEFAULT_AGENT_OPERATIONS_POLICY, + agentOperationsPolicySchema, + type AgentOperationsPolicy, + type AgentPresence, + type AgentPresenceState, +} from '@app/shared'; + +import { AppError } from '../../common/errors'; +import type { WorkspaceId } from '../../db/ids'; +import { notifyWorkspace } from '../realtime'; +import { MembershipEntity, WorkspaceEntity } from '../workspaces'; +import { slaDeadlines } from './agent-operations.sla'; +import { ConversationEntity } from './entities/conversation.entity'; + +export interface AssignedConversation { + conversationId: string; + botId: string; + assignedUserId: string; + workflowVersion: number; +} + +export interface SlaBreach { + conversationId: string; + workspaceId: WorkspaceId; + breach: 'first_response' | 'resolution'; +} + +function policyOf(value: Record): AgentOperationsPolicy { + const routing = + typeof value['routing'] === 'object' && value['routing'] !== null + ? (value['routing'] as Record) + : {}; + const sla = + typeof value['sla'] === 'object' && value['sla'] !== null + ? (value['sla'] as Record) + : {}; + const hours = + typeof sla['businessHours'] === 'object' && sla['businessHours'] !== null + ? (sla['businessHours'] as Record) + : {}; + const targets = + typeof sla['targets'] === 'object' && sla['targets'] !== null + ? (sla['targets'] as Record) + : {}; + const parsed = agentOperationsPolicySchema.safeParse({ + routing: { ...DEFAULT_AGENT_OPERATIONS_POLICY.routing, ...routing }, + sla: { + ...DEFAULT_AGENT_OPERATIONS_POLICY.sla, + ...sla, + businessHours: { ...DEFAULT_AGENT_OPERATIONS_POLICY.sla.businessHours, ...hours }, + targets: { ...DEFAULT_AGENT_OPERATIONS_POLICY.sla.targets, ...targets }, + }, + }); + return parsed.success ? parsed.data : DEFAULT_AGENT_OPERATIONS_POLICY; +} + +@Injectable() +export class AgentOperationsRepository { + constructor(private readonly ds: DataSource) {} + + async policy(workspaceId: WorkspaceId): Promise { + const row = await this.ds + .getRepository(WorkspaceEntity) + .findOne({ where: { id: workspaceId } }); + if (row === null) throw new AppError('not_found'); + return policyOf(row.agentOperations); + } + + async updatePolicy( + workspaceId: WorkspaceId, + policy: Omit & { + routing: Omit; + }, + manager: EntityManager, + ): Promise { + const workspace = await manager.getRepository(WorkspaceEntity).findOne({ + where: { id: workspaceId }, + lock: { mode: 'pessimistic_write' }, + }); + if (workspace === null) throw new AppError('not_found'); + const previous = policyOf(workspace.agentOperations); + const next = agentOperationsPolicySchema.parse({ + ...policy, + routing: { ...policy.routing, lastAssignedUserId: previous.routing.lastAssignedUserId }, + }); + workspace.agentOperations = next; + await manager.getRepository(WorkspaceEntity).save(workspace); + return next; + } + + async setPresence( + workspaceId: WorkspaceId, + userId: string, + state: AgentPresenceState, + now: Date, + leaseSeconds: number, + manager: EntityManager, + ): Promise { + const expiresAt = state === 'offline' ? null : new Date(now.getTime() + leaseSeconds * 1000); + const result = await manager + .getRepository(MembershipEntity) + .update({ workspaceId, userId }, { presenceState: state, presenceExpiresAt: expiresAt }); + if ((result.affected ?? 0) === 0) throw new AppError('not_found'); + return this.presence(workspaceId, userId, now, manager); + } + + async listPresence(workspaceId: WorkspaceId, now: Date): Promise { + return this.ds.query( + `SELECT m.user_id AS "userId", u.name, u.email, m.role, + CASE WHEN m.presence_state <> 'offline' AND m.presence_expires_at > $2 + THEN m.presence_state ELSE 'offline' END AS state, + CASE WHEN m.presence_state <> 'offline' AND m.presence_expires_at > $2 + THEN m.presence_expires_at ELSE NULL END AS "expiresAt" + FROM memberships m + JOIN users u ON u.id = m.user_id + WHERE m.workspace_id = $1 + ORDER BY CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1 ELSE 2 END, + lower(u.email)`, + [workspaceId, now], + ); + } + + async heartbeatPresence( + workspaceId: WorkspaceId, + userId: string, + now: Date, + leaseSeconds: number, + manager: EntityManager, + ): Promise { + await manager.query( + `UPDATE memberships + SET presence_expires_at = $3 + WHERE workspace_id = $1 AND user_id = $2 + AND presence_state IN ('online', 'away')`, + [workspaceId, userId, new Date(now.getTime() + leaseSeconds * 1000)], + ); + return this.presence(workspaceId, userId, now, manager); + } + + async autoAssign( + workspaceId: WorkspaceId, + conversationId: string, + now: Date, + ): Promise { + return this.ds.transaction(async (manager) => { + const workspace = await manager.getRepository(WorkspaceEntity).findOne({ + where: { id: workspaceId }, + lock: { mode: 'pessimistic_write' }, + }); + if (workspace === null) return null; + const policy = policyOf(workspace.agentOperations); + if (!policy.routing.enabled) return null; + + const conversationRows = await manager.query< + { id: string; bot_id: string; status: string; assigned_user_id: string | null }[] + >( + `SELECT id, bot_id, status, assigned_user_id + FROM conversations + WHERE workspace_id = $1 AND id = $2 + FOR UPDATE`, + [workspaceId, conversationId], + ); + const conversation = conversationRows[0]; + if (conversation?.status !== 'needs_human' || conversation.assigned_user_id !== null) { + return null; + } + + const eligible = await manager.query< + { user_id: string; email: string; open_count: number }[] + >( + `SELECT m.user_id, lower(u.email) AS email, count(c.id)::int AS open_count + FROM memberships m + JOIN users u ON u.id = m.user_id + LEFT JOIN conversations c + ON c.workspace_id = m.workspace_id + AND c.assigned_user_id = m.user_id + AND c.status IN ('needs_human', 'human') + AND c.closed_at IS NULL + WHERE m.workspace_id = $1 + AND m.role = ANY($2::role[]) + AND m.presence_state = 'online' + AND m.presence_expires_at > $3 + GROUP BY m.user_id, u.email + HAVING count(c.id) < $4 + ORDER BY CASE WHEN $5 = 'least_loaded' THEN count(c.id) ELSE 0 END, + lower(u.email), m.user_id`, + [ + workspaceId, + policy.routing.eligibleRoles, + now, + policy.routing.maxOpenConversationsPerAgent, + policy.routing.strategy, + ], + ); + if (eligible.length === 0) return null; + + let selected = eligible[0]; + if (policy.routing.strategy === 'round_robin') { + const lastIndex = eligible.findIndex( + (candidate) => candidate.user_id === policy.routing.lastAssignedUserId, + ); + selected = eligible[(lastIndex + 1) % eligible.length] ?? eligible[0]; + } + if (selected === undefined) return null; + + const updated = await manager.getRepository(ConversationEntity).update( + { id: conversationId, workspaceId, assignedUserId: IsNull(), status: 'needs_human' }, + { + assignedUserId: selected.user_id, + status: 'human', + workflowVersion: () => '"workflow_version" + 1', + lastWorkflowMutationId: null, + }, + ); + if ((updated.affected ?? 0) === 0) return null; + workspace.agentOperations = { + ...policy, + routing: { ...policy.routing, lastAssignedUserId: selected.user_id }, + }; + await manager.getRepository(WorkspaceEntity).save(workspace); + const assigned = await manager.getRepository(ConversationEntity).findOne({ + where: { workspaceId, id: conversationId }, + }); + if (assigned === null) return null; + await notifyWorkspace(manager, workspaceId, { + type: 'conversation.updated', + conversationId, + botId: conversation.bot_id, + status: 'human', + }); + return { + conversationId, + botId: conversation.bot_id, + assignedUserId: selected.user_id, + workflowVersion: assigned.workflowVersion, + }; + }); + } + + async initializeSla(workspaceId: WorkspaceId, conversationId: string): Promise { + await this.ds.transaction(async (manager) => { + const conversation = await manager.getRepository(ConversationEntity).findOne({ + where: { workspaceId, id: conversationId }, + lock: { mode: 'pessimistic_write' }, + }); + if ( + conversation?.handoffRequestedAt === null || + conversation?.handoffRequestedAt === undefined || + (conversation.status !== 'needs_human' && conversation.status !== 'human') + ) { + return; + } + const policy = await manager.getRepository(WorkspaceEntity).findOne({ + where: { id: workspaceId }, + }); + if (policy === null) return; + const deadlines = slaDeadlines( + conversation.handoffRequestedAt, + conversation.priority, + policyOf(policy.agentOperations).sla, + ); + const update = { + ...(conversation.firstResponseDueAt === null && deadlines.firstResponseDueAt !== null + ? { firstResponseDueAt: deadlines.firstResponseDueAt } + : {}), + ...(conversation.resolutionDueAt === null && deadlines.resolutionDueAt !== null + ? { resolutionDueAt: deadlines.resolutionDueAt } + : {}), + }; + if (Object.keys(update).length === 0) return; + await manager + .getRepository(ConversationEntity) + .update({ id: conversationId, workspaceId }, update); + }); + } + + async claimSlaBreaches(now: Date, manager: EntityManager, limit: number): Promise { + return manager.query( + `WITH due AS ( + SELECT workspace_id, id, + (first_response_due_at <= $1 AND first_response_breached_at IS NULL + AND outcome_first_agent_reply_at IS NULL) AS response_due, + (resolution_due_at <= $1 AND resolution_breached_at IS NULL + AND closed_at IS NULL) AS resolution_due + FROM conversations + WHERE status IN ('needs_human', 'human') + AND closed_at IS NULL + AND ((first_response_due_at <= $1 AND first_response_breached_at IS NULL + AND outcome_first_agent_reply_at IS NULL) + OR (resolution_due_at <= $1 AND resolution_breached_at IS NULL)) + ORDER BY LEAST( + COALESCE(first_response_due_at, 'infinity'::timestamptz), + COALESCE(resolution_due_at, 'infinity'::timestamptz) + ) + LIMIT $2 + FOR UPDATE SKIP LOCKED + ), marked AS ( + UPDATE conversations c + SET first_response_breached_at = CASE WHEN due.response_due THEN $1 ELSE c.first_response_breached_at END, + resolution_breached_at = CASE WHEN due.resolution_due THEN $1 ELSE c.resolution_breached_at END + FROM due + WHERE c.workspace_id = due.workspace_id AND c.id = due.id + RETURNING c.workspace_id, c.id, due.response_due, due.resolution_due + ) + SELECT id AS "conversationId", workspace_id AS "workspaceId", 'first_response' AS breach + FROM marked WHERE response_due + UNION ALL + SELECT id AS "conversationId", workspace_id AS "workspaceId", 'resolution' AS breach + FROM marked WHERE resolution_due`, + [now, limit], + ); + } + + private async presence( + workspaceId: WorkspaceId, + userId: string, + now: Date, + manager: EntityManager, + ): Promise { + const rows = await manager.query( + `SELECT m.user_id AS "userId", u.name, u.email, m.role, + CASE WHEN m.presence_state <> 'offline' AND m.presence_expires_at > $3 + THEN m.presence_state ELSE 'offline' END AS state, + CASE WHEN m.presence_state <> 'offline' AND m.presence_expires_at > $3 + THEN m.presence_expires_at ELSE NULL END AS "expiresAt" + FROM memberships m + JOIN users u ON u.id = m.user_id + WHERE m.workspace_id = $1 AND m.user_id = $2`, + [workspaceId, userId, now], + ); + const row = rows[0]; + if (row === undefined) throw new AppError('not_found'); + return row; + } +} diff --git a/apps/api/src/modules/conversations/agent-operations.schedule.ts b/apps/api/src/modules/conversations/agent-operations.schedule.ts new file mode 100644 index 00000000..639ab576 --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.schedule.ts @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { Inject, Injectable, Optional, type OnApplicationBootstrap } from '@nestjs/common'; + +import { BOSS_ROLE, type BossRole, PgBossHost } from '../../jobs'; +import { REVIEW_SLA_BREACHES_JOB, SLA_REVIEW_SCHEDULE } from './agent-operations.job'; + +/** Registers minute-level breach processing in worker processes only. */ +@Injectable() +export class AgentOperationsSchedule implements OnApplicationBootstrap { + constructor( + @Optional() private readonly host?: PgBossHost, + @Optional() @Inject(BOSS_ROLE) private readonly role?: BossRole, + ) {} + + async onApplicationBootstrap(): Promise { + const host = this.host; + if (this.role !== 'worker' || host === undefined) return; + await host.boss.schedule(REVIEW_SLA_BREACHES_JOB.name, SLA_REVIEW_SCHEDULE, {}); + } +} diff --git a/apps/api/src/modules/conversations/agent-operations.service.ts b/apps/api/src/modules/conversations/agent-operations.service.ts new file mode 100644 index 00000000..36a66cd0 --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.service.ts @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { Inject, Injectable, Optional } from '@nestjs/common'; +import { DataSource } from 'typeorm'; +import type { EntityManager } from 'typeorm'; + +import { + AGENT_PRESENCE_LEASE_SECONDS, + type AgentOperationsPolicy, + type AgentOperationsPolicyUpdate, + type AgentPresence, + type AgentPresenceState, +} from '@app/shared'; + +import { Clock } from '../../common/clock'; +import { AUDIT_LOG, type AuditWriter } from '../../common/ports/audit'; +import { asUserId, type UserId, type WorkspaceId } from '../../db/ids'; +import { NotificationsService } from '../notifications'; +import { AgentOperationsRepository, type SlaBreach } from './agent-operations.repository'; + +@Injectable() +export class AgentOperationsService { + constructor( + private readonly ds: DataSource, + private readonly repository: AgentOperationsRepository, + private readonly clock: Clock, + @Inject(AUDIT_LOG) private readonly audit: AuditWriter, + @Optional() private readonly notifications?: NotificationsService, + ) {} + + getPolicy(workspaceId: WorkspaceId): Promise { + return this.repository.policy(workspaceId); + } + + async updatePolicy( + workspaceId: WorkspaceId, + actorUserId: UserId, + input: AgentOperationsPolicyUpdate, + ): Promise { + return this.ds.transaction(async (manager) => { + const policy = await this.repository.updatePolicy(workspaceId, input, manager); + await this.audit.record( + { + workspaceId, + actorUserId, + action: 'agent_operations.updated', + targetType: 'workspace', + targetId: workspaceId, + metadata: { + routingEnabled: policy.routing.enabled, + routingStrategy: policy.routing.strategy, + configuredSlaPriorities: Object.entries(policy.sla.targets) + .filter( + ([, target]) => + target.firstResponseMinutes !== null || target.resolutionMinutes !== null, + ) + .map(([priority]) => priority), + }, + }, + manager, + ); + return policy; + }); + } + + async listPresence(workspaceId: WorkspaceId): Promise { + return this.repository.listPresence(workspaceId, this.clock.now()); + } + + async updatePresence( + workspaceId: WorkspaceId, + userId: UserId, + state: AgentPresenceState, + ): Promise { + const now = this.clock.now(); + return this.ds.transaction(async (manager) => { + const presence = await this.repository.setPresence( + workspaceId, + userId, + state, + now, + AGENT_PRESENCE_LEASE_SECONDS, + manager, + ); + await this.audit.record( + { + workspaceId, + actorUserId: userId, + action: 'member.presence_changed', + targetType: 'member', + targetId: userId, + metadata: { state: presence.state }, + }, + manager, + ); + return presence; + }); + } + + async heartbeatPresence(workspaceId: WorkspaceId, userId: UserId): Promise { + return this.ds.transaction((manager) => + this.repository.heartbeatPresence( + workspaceId, + userId, + this.clock.now(), + AGENT_PRESENCE_LEASE_SECONDS, + manager, + ), + ); + } + + async routeHandoff(workspaceId: WorkspaceId, conversationId: string): Promise { + await this.repository.initializeSla(workspaceId, conversationId); + const assigned = await this.repository.autoAssign( + workspaceId, + conversationId, + this.clock.now(), + ); + if (assigned === null) return; + await this.ds.transaction(async (manager) => { + await this.audit.record( + { + workspaceId, + actorUserId: null, + action: 'conversation.auto_assigned', + targetType: 'conversation', + targetId: conversationId, + metadata: { assignedUserId: assigned.assignedUserId }, + }, + manager, + ); + await this.notifications?.notify(manager, { + type: 'conversation_assigned', + workspaceId, + conversationId, + botId: assigned.botId, + actorUserId: null, + assigneeUserId: asUserId(assigned.assignedUserId), + actorName: 'Auto-routing', + }); + }); + } + + async processSlaBreaches(): Promise { + const now = this.clock.now(); + return this.ds.transaction(async (manager) => { + const breaches = await this.repository.claimSlaBreaches(now, manager, 100); + for (const breach of breaches) await this.recordBreach(breach, manager); + return breaches.length; + }); + } + + private async recordBreach(breach: SlaBreach, manager: EntityManager): Promise { + await this.audit.record( + { + workspaceId: breach.workspaceId, + actorUserId: null, + action: 'conversation.sla_breached', + targetType: 'conversation', + targetId: breach.conversationId, + metadata: { breach: breach.breach }, + }, + manager, + ); + await this.notifications?.notify(manager, { + type: 'sla_breached', + workspaceId: breach.workspaceId, + conversationId: breach.conversationId, + breach: breach.breach, + actorUserId: null, + }); + } +} diff --git a/apps/api/src/modules/conversations/agent-operations.sla.spec.ts b/apps/api/src/modules/conversations/agent-operations.sla.spec.ts new file mode 100644 index 00000000..c273068b --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.sla.spec.ts @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_AGENT_OPERATIONS_POLICY } from '@app/shared'; + +import { addBusinessMinutes } from './agent-operations.sla'; + +describe('addBusinessMinutes', () => { + it('uses elapsed time when business hours are not configured', () => { + const deadline = addBusinessMinutes( + new Date('2026-03-02T10:00:00.000Z'), + 90, + 'UTC', + DEFAULT_AGENT_OPERATIONS_POLICY.sla.businessHours, + ); + + expect(deadline?.toISOString()).toBe('2026-03-02T11:30:00.000Z'); + }); + + it('pauses outside configured hours and resumes at the next open interval', () => { + const businessHours = { + ...DEFAULT_AGENT_OPERATIONS_POLICY.sla.businessHours, + monday: [{ start: '09:00', end: '17:00' }], + tuesday: [{ start: '09:00', end: '17:00' }], + }; + const deadline = addBusinessMinutes( + new Date('2026-03-02T16:00:00.000Z'), + 120, + 'UTC', + businessHours, + ); + + expect(deadline?.toISOString()).toBe('2026-03-03T10:00:00.000Z'); + }); + + it('counts the continuation of an overnight schedule on the next local day', () => { + const businessHours = { + ...DEFAULT_AGENT_OPERATIONS_POLICY.sla.businessHours, + monday: [{ start: '22:00', end: '02:00' }], + }; + const deadline = addBusinessMinutes( + new Date('2026-03-03T05:30:00.000Z'), + 90, + 'America/New_York', + businessHours, + ); + + expect(deadline?.toISOString()).toBe('2026-03-03T07:00:00.000Z'); + }); + + it('uses elapsed UTC minutes across a daylight-saving transition', () => { + const businessHours = { + ...DEFAULT_AGENT_OPERATIONS_POLICY.sla.businessHours, + sunday: [{ start: '00:00', end: '04:00' }], + }; + const deadline = addBusinessMinutes( + new Date('2026-03-08T05:00:00.000Z'), + 180, + 'America/New_York', + businessHours, + ); + + expect(deadline?.toISOString()).toBe('2026-03-08T08:00:00.000Z'); + }); +}); diff --git a/apps/api/src/modules/conversations/agent-operations.sla.ts b/apps/api/src/modules/conversations/agent-operations.sla.ts new file mode 100644 index 00000000..9eb7afbd --- /dev/null +++ b/apps/api/src/modules/conversations/agent-operations.sla.ts @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import type { AgentOperationsPolicy } from '@app/shared'; + +type BusinessHours = AgentOperationsPolicy['sla']['businessHours']; +type BusinessDay = keyof BusinessHours; + +interface LocalParts { + year: number; + month: number; + day: number; + hour: number; + minute: number; + weekday: BusinessDay; +} + +const WEEKDAYS: readonly BusinessDay[] = [ + 'sunday', + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', +]; +const MINUTE_MS = 60_000; +const MAX_SEARCH_DAYS = 370; + +function localParts(date: Date, timeZone: string): LocalParts { + const parts = new Intl.DateTimeFormat('en-US', { + timeZone, + weekday: 'long', + year: 'numeric', + month: 'numeric', + day: 'numeric', + hour: 'numeric', + minute: 'numeric', + hourCycle: 'h23', + }).formatToParts(date); + const values = Object.fromEntries(parts.map(({ type, value }) => [type, value])); + const weekday = values['weekday']?.toLowerCase(); + if (!WEEKDAYS.includes(weekday as BusinessDay)) throw new Error('Invalid local weekday.'); + return { + year: Number(values['year']), + month: Number(values['month']), + day: Number(values['day']), + hour: Number(values['hour']), + minute: Number(values['minute']), + weekday: weekday as BusinessDay, + }; +} + +function localTimeOnDate( + year: number, + month: number, + day: number, + time: string, + timeZone: string, +): Date { + const [hourText = '0', minuteText = '0'] = time.split(':'); + const hour = Number(hourText); + const minute = Number(minuteText); + const localEpoch = Date.UTC(year, month - 1, day, hour, minute); + let candidate = localEpoch; + for (let attempt = 0; attempt < 4; attempt += 1) { + const actual = localParts(new Date(candidate), timeZone); + const representedEpoch = Date.UTC( + actual.year, + actual.month - 1, + actual.day, + actual.hour, + actual.minute, + ); + const next = localEpoch - (representedEpoch - candidate); + if (next === candidate) break; + candidate = next; + } + return new Date(candidate); +} + +function addLocalDays(parts: LocalParts, days: number): Pick { + const date = new Date(Date.UTC(parts.year, parts.month - 1, parts.day + days)); + return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() }; +} + +function intervalWindows( + day: BusinessDay, + date: Pick, + businessHours: BusinessHours, + timeZone: string, +): { start: Date; end: Date }[] { + return businessHours[day].map(({ start, end }) => { + const endsNextDay = end < start; + const endDate = endsNextDay + ? addLocalDays({ ...date, hour: 0, minute: 0, weekday: day }, 1) + : date; + return { + start: localTimeOnDate(date.year, date.month, date.day, start, timeZone), + end: localTimeOnDate(endDate.year, endDate.month, endDate.day, end, timeZone), + }; + }); +} + +/** Returns a deadline after the requested number of business minutes; an empty schedule is 24/7. */ +export function addBusinessMinutes( + start: Date, + minutes: number | null, + timeZone: string, + businessHours: BusinessHours, +): Date | null { + if (minutes === null) return null; + if (Object.values(businessHours).every((windows) => windows.length === 0)) { + return new Date(start.getTime() + minutes * MINUTE_MS); + } + + let remainingMs = minutes * MINUTE_MS; + const startParts = localParts(start, timeZone); + let cursor = start; + + // Begin one local day earlier so an overnight interval can continue into the start day. + for (let offset = -1; offset < MAX_SEARCH_DAYS; offset += 1) { + const date = addLocalDays(startParts, offset); + const weekdayIndex = (WEEKDAYS.indexOf(startParts.weekday) + offset + 7) % 7; + const day = WEEKDAYS[weekdayIndex]; + if (day === undefined) continue; + const windows = intervalWindows(day, date, businessHours, timeZone).sort( + (left, right) => left.start.getTime() - right.start.getTime(), + ); + for (const window of windows) { + const windowStart = Math.max(cursor.getTime(), window.start.getTime()); + const availableMs = window.end.getTime() - windowStart; + if (availableMs <= 0) continue; + if (availableMs >= remainingMs) return new Date(windowStart + remainingMs); + remainingMs -= availableMs; + cursor = window.end; + } + } + throw new Error('No SLA deadline found within the configured search horizon.'); +} + +export function slaDeadlines( + start: Date, + priority: keyof AgentOperationsPolicy['sla']['targets'], + sla: AgentOperationsPolicy['sla'], +): { firstResponseDueAt: Date | null; resolutionDueAt: Date | null } { + const target = sla.targets[priority]; + return { + firstResponseDueAt: addBusinessMinutes( + start, + target.firstResponseMinutes, + sla.timeZone, + sla.businessHours, + ), + resolutionDueAt: addBusinessMinutes( + start, + target.resolutionMinutes, + sla.timeZone, + sla.businessHours, + ), + }; +} diff --git a/apps/api/src/modules/conversations/conversations.mapper.ts b/apps/api/src/modules/conversations/conversations.mapper.ts index b2abab97..6471ad49 100644 --- a/apps/api/src/modules/conversations/conversations.mapper.ts +++ b/apps/api/src/modules/conversations/conversations.mapper.ts @@ -42,6 +42,18 @@ export function toConversationListItem(row: InboxRow): ConversationListItem { lastMessageAt: iso(row.last_message_at), lastMessagePreview: row.last_message_preview ?? '', unansweredByHuman: row.unanswered_by_human, + sla: { + firstResponseDueAt: + row.first_response_breached_at !== null || row.outcome_first_agent_reply_at === null + ? (row.first_response_due_at?.toISOString() ?? null) + : null, + resolutionDueAt: + row.resolution_breached_at !== null || row.closed_at === null + ? (row.resolution_due_at?.toISOString() ?? null) + : null, + firstResponseBreachedAt: row.first_response_breached_at?.toISOString() ?? null, + resolutionBreachedAt: row.resolution_breached_at?.toISOString() ?? null, + }, }; } @@ -61,6 +73,18 @@ export function toAdminConversation(row: InboxRow): AdminConversation { closedAt: row.closed_at === null ? null : iso(row.closed_at), metadata: row.metadata, createdAt: iso(row.created_at), + sla: { + firstResponseDueAt: + row.first_response_breached_at !== null || row.outcome_first_agent_reply_at === null + ? (row.first_response_due_at?.toISOString() ?? null) + : null, + resolutionDueAt: + row.resolution_breached_at !== null || row.closed_at === null + ? (row.resolution_due_at?.toISOString() ?? null) + : null, + firstResponseBreachedAt: row.first_response_breached_at?.toISOString() ?? null, + resolutionBreachedAt: row.resolution_breached_at?.toISOString() ?? null, + }, }; } diff --git a/apps/api/src/modules/conversations/conversations.module.ts b/apps/api/src/modules/conversations/conversations.module.ts index ad9ae649..e709b454 100644 --- a/apps/api/src/modules/conversations/conversations.module.ts +++ b/apps/api/src/modules/conversations/conversations.module.ts @@ -8,6 +8,11 @@ import { UsageModule } from '../usage'; import { MembershipsRepository } from '../workspaces'; import { AgentActionsController } from './agent-actions.controller'; import { AgentActionsService } from './agent-actions.service'; +import { AgentOperationsController } from './agent-operations.controller'; +import { AgentOperationsProcessor } from './agent-operations.processor'; +import { AgentOperationsRepository } from './agent-operations.repository'; +import { AgentOperationsSchedule } from './agent-operations.schedule'; +import { AgentOperationsService } from './agent-operations.service'; import { AgentReplyEmailProcessor } from './agent-reply-email.processor'; import { ContactsRepository } from './contacts.repository'; import { ConversationsController } from './conversations.controller'; @@ -24,9 +29,18 @@ import { VisitorPresence } from './visitor-presence'; /** Conversations, their messages and the visitors they belong to (spec §9.4). */ @Module({ imports: [ActiveStreamsModule, UsageModule, AgentAssistModule], - controllers: [ConversationsController, AgentActionsController, InternalNotesController], + controllers: [ + ConversationsController, + AgentActionsController, + AgentOperationsController, + InternalNotesController, + ], providers: [ AgentActionsService, + AgentOperationsRepository, + AgentOperationsService, + AgentOperationsProcessor, + AgentOperationsSchedule, AgentReplyEmailProcessor, HandoffNotifierListener, VisitorPresence, diff --git a/apps/api/src/modules/conversations/entities/conversation.entity.ts b/apps/api/src/modules/conversations/entities/conversation.entity.ts index 0ac4f358..1266d56f 100644 --- a/apps/api/src/modules/conversations/entities/conversation.entity.ts +++ b/apps/api/src/modules/conversations/entities/conversation.entity.ts @@ -36,6 +36,7 @@ import { ContactEntity } from './contact.entity'; @Index('conversations_inbox', { synchronize: false }) @Index('conversations_inbox_priority', { synchronize: false }) @Index('conversations_inbox_priority_status', { synchronize: false }) +@Index('conversations_sla_due_idx', { synchronize: false }) @Index('conversations_outcomes_range', { synchronize: false }) @Index('conversations_contact_id', ['contactId']) @Index('conversations_bot_id', ['botId']) @@ -107,7 +108,18 @@ export class ConversationEntity extends TenantEntity { @Column({ type: 'timestamptz', nullable: true }) handoffRequestedAt!: Date | null; - /** Phase 5 SLA. */ + @Column({ type: 'timestamptz', nullable: true }) + firstResponseDueAt!: Date | null; + + @Column({ type: 'timestamptz', nullable: true }) + resolutionDueAt!: Date | null; + + @Column({ type: 'timestamptz', nullable: true }) + firstResponseBreachedAt!: Date | null; + + @Column({ type: 'timestamptz', nullable: true }) + resolutionBreachedAt!: Date | null; + @Column({ type: 'enum', enum: PRIORITIES, enumName: 'priority', default: 'normal' }) priority!: Priority; diff --git a/apps/api/src/modules/conversations/handoff-notifier.listener.ts b/apps/api/src/modules/conversations/handoff-notifier.listener.ts index ad2e2101..3b4e08af 100644 --- a/apps/api/src/modules/conversations/handoff-notifier.listener.ts +++ b/apps/api/src/modules/conversations/handoff-notifier.listener.ts @@ -6,6 +6,7 @@ import { DataSource } from 'typeorm'; import { CHAT_HANDOFF_REQUESTED, type ChatHandoffRequestedEvent } from '../../events'; import { NotificationsService } from '../notifications'; import { UsageRepository } from '../usage'; +import { AgentOperationsService } from './agent-operations.service'; import { InboxQuery } from './inbox.repository'; /** @@ -19,11 +20,13 @@ export class HandoffNotifierListener { private readonly ds: DataSource, private readonly inbox: InboxQuery, private readonly usage: UsageRepository, + @Optional() private readonly operations?: AgentOperationsService, @Optional() private readonly notifications?: NotificationsService, ) {} @OnEvent(CHAT_HANDOFF_REQUESTED) async handle(event: ChatHandoffRequestedEvent): Promise { + await this.operations?.routeHandoff(event.workspaceId, event.conversationId); const context = await this.inbox.handoffNotificationContext( event.workspaceId, event.conversationId, diff --git a/apps/api/src/modules/conversations/inbox.repository.ts b/apps/api/src/modules/conversations/inbox.repository.ts index c37a78cd..b7211bec 100644 --- a/apps/api/src/modules/conversations/inbox.repository.ts +++ b/apps/api/src/modules/conversations/inbox.repository.ts @@ -32,6 +32,11 @@ export interface InboxRow { assigned_name: string | null; handoff_reason: HandoffReason | null; handoff_requested_at: Date | null; + first_response_due_at: Date | null; + resolution_due_at: Date | null; + first_response_breached_at: Date | null; + resolution_breached_at: Date | null; + outcome_first_agent_reply_at: Date | null; last_message_at: Date; last_message_preview: string | null; unanswered_by_human: boolean; @@ -327,6 +332,11 @@ export class InboxQuery { .addSelect('COALESCE(u.name, u.email)', 'assigned_name') .addSelect('c.handoff_reason', 'handoff_reason') .addSelect('c.handoff_requested_at', 'handoff_requested_at') + .addSelect('c.first_response_due_at', 'first_response_due_at') + .addSelect('c.resolution_due_at', 'resolution_due_at') + .addSelect('c.first_response_breached_at', 'first_response_breached_at') + .addSelect('c.resolution_breached_at', 'resolution_breached_at') + .addSelect('c.outcome_first_agent_reply_at', 'outcome_first_agent_reply_at') .addSelect('c.last_message_at', 'last_message_at') .addSelect( `(SELECT left(m.content, 140) diff --git a/apps/api/src/modules/conversations/index.ts b/apps/api/src/modules/conversations/index.ts index b8778853..11477d55 100644 --- a/apps/api/src/modules/conversations/index.ts +++ b/apps/api/src/modules/conversations/index.ts @@ -1,6 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-only export { AgentActionsController } from './agent-actions.controller'; export { AgentActionsService } from './agent-actions.service'; +export { AgentOperationsController } from './agent-operations.controller'; +export { AgentOperationsRepository } from './agent-operations.repository'; +export { AgentOperationsService } from './agent-operations.service'; export { ContactsRepository } from './contacts.repository'; export { ConversationsController } from './conversations.controller'; export { ConversationsModule } from './conversations.module'; diff --git a/apps/api/src/modules/conversations/notifications.int.spec.ts b/apps/api/src/modules/conversations/notifications.int.spec.ts index de67071e..d121ca3e 100644 --- a/apps/api/src/modules/conversations/notifications.int.spec.ts +++ b/apps/api/src/modules/conversations/notifications.int.spec.ts @@ -11,6 +11,7 @@ import { loadConfig } from '../../common/config'; import { asWorkspaceId } from '../../db/ids'; import { EmailService } from '../email'; import { MemoryMailer } from '../email/memory.mailer'; +import { NotificationsService } from '../notifications'; import { AgentReplyEmailProcessor } from './agent-reply-email.processor'; import { HandoffNotifierListener } from './handoff-notifier.listener'; import { VisitorPresence } from './visitor-presence'; @@ -34,6 +35,7 @@ let listener: HandoffNotifierListener; let processor: AgentReplyEmailProcessor; let presence: VisitorPresence; let email: EmailService; +let notifications: NotificationsService; interface Seeded { workspaceId: string; @@ -96,6 +98,7 @@ beforeAll(async () => { processor = worker.get(AgentReplyEmailProcessor); presence = worker.get(VisitorPresence); email = worker.get(EmailService); + notifications = worker.get(NotificationsService); }); afterAll(async () => { @@ -108,6 +111,27 @@ beforeEach(async () => { }); describe('handoff notifications and agent reply emails', () => { + it('notifies workspace owners about a persisted SLA breach', async () => { + const seeded = await seed(ds, 'visitor@example.com'); + await ds.transaction((manager) => + notifications.notify(manager, { + type: 'sla_breached', + workspaceId: asWorkspaceId(seeded.workspaceId), + conversationId: seeded.conversationId, + breach: 'first_response', + actorUserId: null, + }), + ); + + const rows = await ds.query<{ type: string; payload: { title?: string } }[]>( + `SELECT type, payload FROM notifications WHERE workspace_id = $1`, + [seeded.workspaceId], + ); + expect(rows).toHaveLength(1); + expect(rows[0]?.type).toBe('sla_breached'); + expect(rows[0]?.payload.title).toBe('First response SLA breached'); + }); + it('emails the notification recipients with the conversation link and context', async () => { const seeded = await seed(ds, 'visitor@example.com'); await ds.query( diff --git a/apps/api/src/modules/notifications/notification.entity.ts b/apps/api/src/modules/notifications/notification.entity.ts index 21821f9b..6c5d1666 100644 --- a/apps/api/src/modules/notifications/notification.entity.ts +++ b/apps/api/src/modules/notifications/notification.entity.ts @@ -37,6 +37,7 @@ export class NotificationEntity { 'spend_alert', 'suggestion_created', 'suggestion_reviewed', + 'sla_breached', ], enumName: 'notification_type', }) diff --git a/apps/api/src/modules/notifications/notification.events.ts b/apps/api/src/modules/notifications/notification.events.ts index 3197e486..4891a201 100644 --- a/apps/api/src/modules/notifications/notification.events.ts +++ b/apps/api/src/modules/notifications/notification.events.ts @@ -57,4 +57,9 @@ export type NotificationEvent = creatorUserId: UserId | null; actorUserId: UserId; status: 'approved' | 'rejected'; + }) + | (BaseEvent & { + type: 'sla_breached'; + conversationId: string; + breach: 'first_response' | 'resolution'; }); diff --git a/apps/api/src/modules/notifications/notifications.service.ts b/apps/api/src/modules/notifications/notifications.service.ts index 9eb466be..f5f86826 100644 --- a/apps/api/src/modules/notifications/notifications.service.ts +++ b/apps/api/src/modules/notifications/notifications.service.ts @@ -190,6 +190,15 @@ export class NotificationsService { title: `Your correction was ${event.status}`, body: `An administrator ${event.status} your suggested answer.`, }; + case 'sla_breached': + return { + conversationId: event.conversationId, + title: + event.breach === 'first_response' + ? 'First response SLA breached' + : 'Resolution SLA breached', + body: 'A conversation has passed its configured service target.', + }; } } @@ -294,6 +303,8 @@ export class NotificationsService { status: event.status, }, }; + case 'sla_breached': + return null; } } diff --git a/apps/api/src/modules/workspaces/entities/membership.entity.ts b/apps/api/src/modules/workspaces/entities/membership.entity.ts index ea6ce779..903474dd 100644 --- a/apps/api/src/modules/workspaces/entities/membership.entity.ts +++ b/apps/api/src/modules/workspaces/entities/membership.entity.ts @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only import { Column, + Check, CreateDateColumn, Entity, Index, @@ -20,6 +21,8 @@ import { WorkspaceEntity } from './workspace.entity'; unique: true, where: `"role" = 'owner'`, }) +@Index('memberships_presence_idx', { synchronize: false }) +@Check('memberships_presence_state_check', `"presence_state" IN ('online', 'away', 'offline')`) export class MembershipEntity { @PrimaryColumn({ type: 'uuid' }) workspaceId!: string; @@ -33,6 +36,12 @@ export class MembershipEntity { @Column({ type: 'jsonb', default: () => "'{}'" }) notificationPreferences!: NotificationPreferences; + @Column({ type: 'text', default: 'offline' }) + presenceState!: 'online' | 'away' | 'offline'; + + @Column({ type: 'timestamptz', nullable: true }) + presenceExpiresAt!: Date | null; + @ManyToOne(() => WorkspaceEntity, { onDelete: 'CASCADE' }) @JoinColumn({ name: 'workspace_id', diff --git a/apps/api/src/modules/workspaces/entities/workspace.entity.ts b/apps/api/src/modules/workspaces/entities/workspace.entity.ts index c8132151..516e9c0f 100644 --- a/apps/api/src/modules/workspaces/entities/workspace.entity.ts +++ b/apps/api/src/modules/workspaces/entities/workspace.entity.ts @@ -16,6 +16,9 @@ export class WorkspaceEntity { @Column({ type: 'jsonb', default: () => "'{}'" }) settings!: Record; + @Column({ type: 'jsonb', default: () => "'{}'" }) + agentOperations!: Record; + @CreateDateColumn({ type: 'timestamptz' }) createdAt!: Date; diff --git a/apps/api/test/e2e/agent-operations.e2e.spec.ts b/apps/api/test/e2e/agent-operations.e2e.spec.ts new file mode 100644 index 00000000..1e9141ae --- /dev/null +++ b/apps/api/test/e2e/agent-operations.e2e.spec.ts @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { DEFAULT_AGENT_OPERATIONS_POLICY, type AgentOperationsPolicyUpdate } from '@app/shared'; + +import { createTestApp, type TestApp } from '../helpers/app'; +import { resetDatabase } from '../helpers/db'; +import { + addMember, + authed, + type AuthedClient, + createUser, + createWorkspace, + loginAs, +} from '../helpers/factories'; + +let t: TestApp; +let owner: AuthedClient; +let agent: AuthedClient; +let otherOwner: AuthedClient; +let workspaceId: string; +let ownerId: string; +let agentId: string; +let emailSequence = 0; + +beforeAll(async () => { + t = await createTestApp(); + await t.app.listen(0); +}); + +afterAll(async () => { + await t.close(); +}); + +beforeEach(async () => { + await resetDatabase(t.ds); + emailSequence += 1; + const ownerAccount = await createUser( + { ds: t.ds }, + { email: `operations-owner-${String(emailSequence)}@example.com` }, + ); + const workspace = await createWorkspace(t, ownerAccount.user, 'Agent operations'); + workspaceId = workspace.id; + ownerId = ownerAccount.user.id; + owner = authed(t, await loginAs(t, ownerAccount.user, ownerAccount.password)); + + const agentAccount = await createUser( + { ds: t.ds }, + { email: `operations-agent-${String(emailSequence)}@example.com` }, + ); + agentId = agentAccount.user.id; + await addMember(t, workspace, agentAccount.user, 'agent'); + agent = authed(t, await loginAs(t, agentAccount.user, agentAccount.password)); + + const otherAccount = await createUser( + { ds: t.ds }, + { email: `operations-other-${String(emailSequence)}@example.com` }, + ); + await createWorkspace(t, otherAccount.user, 'Other workspace'); + otherOwner = authed(t, await loginAs(t, otherAccount.user, otherAccount.password)); +}); + +describe('agent operations endpoints', () => { + it('keeps routing disabled by default and restricts policy changes to admins', async () => { + const path = `/api/v1/workspaces/${workspaceId}/agent-operations`; + const initial = await owner.get(path).expect(200); + expect(initial.body).toMatchObject({ routing: { enabled: false } }); + + const update: AgentOperationsPolicyUpdate = { + routing: { + enabled: true, + strategy: 'round_robin', + maxOpenConversationsPerAgent: 5, + eligibleRoles: ['agent', 'admin', 'owner'], + }, + sla: DEFAULT_AGENT_OPERATIONS_POLICY.sla, + }; + await owner.put(path).send(update).expect(200); + await agent.put(path).send(update).expect(403); + + const forbiddenWorkspace = await otherOwner.get(path); + expect([403, 404]).toContain(forbiddenWorkspace.status); + }); + + it('lets members update only their own presence and keeps it workspace scoped', async () => { + const path = `/api/v1/workspaces/${workspaceId}/agent-operations/presence`; + await owner.put(path).send({ state: 'online' }).expect(200); + await agent.put(path).send({ state: 'online' }).expect(200); + + const roster = await owner.get(path).expect(200); + expect(roster.body).toEqual( + expect.arrayContaining([ + expect.objectContaining({ userId: agentId, state: 'online' }), + expect.objectContaining({ userId: ownerId, state: 'online' }), + ]), + ); + await agent.put(path).send({ state: 'offline', userId: ownerId }).expect(200); + const updatedRoster = await owner.get(path).expect(200); + expect(updatedRoster.body).toEqual( + expect.arrayContaining([ + expect.objectContaining({ userId: agentId, state: 'offline' }), + expect.objectContaining({ userId: ownerId, state: 'online' }), + ]), + ); + + const forbiddenWorkspace = await otherOwner.get(path); + expect([403, 404]).toContain(forbiddenWorkspace.status); + }); +}); diff --git a/apps/docs/src/content/docs/agent-productivity.md b/apps/docs/src/content/docs/agent-productivity.md index a5cabf7d..3dd7676a 100644 --- a/apps/docs/src/content/docs/agent-productivity.md +++ b/apps/docs/src/content/docs/agent-productivity.md @@ -1,6 +1,6 @@ --- title: Agent productivity -description: Inbox routing, customer context, internal notes, saved replies, and reviewed AI assistance. +description: Agent presence, automatic handoff routing, service targets, customer context, and reviewed AI assistance. --- # Agent productivity @@ -19,6 +19,27 @@ Owners and admins can route conversations to workspace members. Agents can assig they are permitted to handle. A stale concurrent update returns a conflict; reload the conversation and choose again. Assignment and priority changes are audited and invalidate other workspace inboxes. +## Availability, automatic routing, and service targets + +Agents set their own presence to **Online**, **Away**, or **Offline** under **Settings → Agent +operations**. Online and away presence expires after five minutes unless the open admin session +refreshes its lease. Only online members are eligible for automatic assignment. Owners and admins +can see the workspace roster but cannot change another member's presence. + +Owners and admins can enable workspace handoff routing and choose round-robin or least-loaded +selection, with a maximum number of open assigned conversations per agent. A handoff stays +unassigned when no online member is below capacity. Existing conversations are not reassigned when +the setting changes, and manual assignment remains available. + +Service targets are configured separately for first response and resolution at each priority. +The current priority and targets are captured when a new conversation is handed to a person; the +response clock stops at the first agent +reply, and the resolution clock stops when the conversation closes. Business hours use the configured +IANA timezone and repeat weekly. Leave every day empty for a 24/7 schedule. Breaches are checked by +the background worker about once a minute, appear on the conversation, and notify workspace owners +and admins. The system does not apply holiday calendars, pause rules, escalation tiers, or automatic +reassignment. + ## Customer context The sidebar shows the contact's email and external ID, first and last seen times, bounded attributes, @@ -74,7 +95,7 @@ transcripts. ## Notifications The bell in the workspace header lists handoffs, assignments, visitor replies to assigned work, -spend alerts, and knowledge-correction updates. Select an item to open the related conversation, +SLA breaches, spend alerts, and knowledge-correction updates. Select an item to open the related conversation, suggestion queue, or usage page; use **Mark all read** to clear the unread count. New notifications arrive over the workspace's live event stream, and each member sees only their own items. diff --git a/docs/spec.md b/docs/spec.md index 138eaec2..d16ea9ac 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -1007,14 +1007,14 @@ No LLM call is made when escalating on retrieval signals (saves cost, avoids hal 1. Visitor requests a human (button, or "Yes" on a handoff offer). 2. If the contact has no email, the widget shows an optional email field ("so we can reply if you leave"). -3. Conversation → `needs_human`, `handoff_reason`, `handoff_requested_at` set. AI stops responding in this conversation. The widget shows the bot's `handoff_message` (expected reply time, set by the operator), so a visitor at 3 a.m. knows what to expect. Business hours are Phase 5. +3. Conversation → `needs_human`, `handoff_reason`, `handoff_requested_at` set. AI stops responding in this conversation. The widget shows the bot's `handoff_message` (expected reply time, set by the operator), so a visitor at 3 a.m. knows what to expect. Optional business-time response and resolution targets are available since Milestone 26. 4. Notification email to the workspace's notification addresses (default: owners and admins), with a link to the conversation. 5. Admin dashboard shows a **"Needs human" list** with count badge. Agents with the admin open also get a **browser notification and sound** (Notification API, opt-in per browser, driven by the existing workspace SSE channel). 6. An agent opens the conversation and clicks **Take over** → status `human`, `assigned_user_id` set. Agent replies are delivered to the widget in real time (section 18). 7. Agent can **Hand back to AI** (status `ai`) or **Close** (status `closed`). 8. If the visitor left and has an email, agent replies are also emailed (with a link back into the conversation, Phase 2) — Phase 1 sends a plain-text copy. -Milestone 9 adds manual assignment, priority filters, internal notes, saved replies, contact context, and reviewed AI assistance. Automated routing, presence, typing indicators, and unread synchronization remain later Phase 2 work. +Milestone 9 added manual assignment, priority filters, internal notes, saved replies, contact context, and reviewed AI assistance. Milestone 26 added opt-in presence, deterministic handoff routing, and configurable business-time SLAs. Typing indicators and unread synchronization remain later work. --- @@ -1609,7 +1609,8 @@ The `v0.1.0` release ships only when all are true: ### Phase 2: Humans in the loop - **Milestone 9 — agent productivity:** manual assignment/unassignment, typed priority controls and filters, contact identity/attributes/history with existing CRM links, workspace saved replies, private internal notes, asynchronous handoff summaries, and on-demand grounded reply suggestions. AI assistance defaults off for existing bots, has separate owner/admin controls and a kill switch, is rate/idempotency protected, and passes deterministic safety plus documented live-model quality gates. AI output is always reviewed and manually sent; internal notes are excluded from every external channel and default AI context. -- **Later inbox:** round-robin/skills-based routing, agent presence, typing indicators, unread synchronization, and WebSockets only where those bidirectional features require them. +- **Milestone 26 — agent operations:** self-managed presence with expiring leases, opt-in round-robin/least-loaded handoff routing with capacity limits, and worker-scanned business-time response/resolution SLAs. Skills-based routing, holidays, escalation tiers, and automatic reassignment remain out of scope. +- **Later inbox:** typing indicators, unread synchronization, and WebSockets only where those bidirectional features require them. - **Later contacts:** tags, merge/deduplication, richer profile editing, and data-quality workflows. Signed widget `identify()` and external attributes shipped in Milestone 8. - **Knowledge freshness:** scheduled recrawl per source, `document_versions` history with diff view, unreachable-page detection, "stale for N days" report, manual content editor (creates a new version). - **Duplicate detection:** skip chunks with identical `content_hash` within a bot. @@ -1645,7 +1646,7 @@ The `v0.1.0` release ships only when all are true: - Shared rate-limit store; horizontally scaled API and worker documented and tested. - OpenTelemetry tracing, Prometheus metrics, example Grafana dashboards. -- SLA: priorities, response-time targets, business hours and holidays, unassigned alerts, escalation rules. +- SLA follow-ups: holiday calendars, pause conditions, unassigned alerts, and configurable escalation rules (basic response/resolution targets and weekly business hours shipped in Milestone 26). - Full audit log UI and export; GDPR tooling (contact data export and erasure); per-workspace retention policies. - SSO via OIDC; enforced 2FA (TOTP) option for workspaces. - S3-compatible storage (MinIO, AWS S3, R2). diff --git a/docs/superpowers/plans/2026-11-28-m26-agent-operations.md b/docs/superpowers/plans/2026-11-28-m26-agent-operations.md new file mode 100644 index 00000000..33fc9683 --- /dev/null +++ b/docs/superpowers/plans/2026-11-28-m26-agent-operations.md @@ -0,0 +1,91 @@ +# M26: Agent operations + +## Outcome + +Help support teams get human conversations to the right available agent and see when a response +or resolution is at risk. Policies are explicit, deterministic, workspace-scoped, and visible to +admins; the AI never assigns agents or changes SLA policy. + +## Existing behavior + +- Agents can manually assign or release conversations, set priority, take over, reply, and close. +- Handoff notifications and live workspace invalidation already exist. +- First-response and resolution times are historical analytics only. +- Workspace members have owner/admin/agent roles, but no presence state or capacity. + +## Scope + +1. Add agent presence states `online`, `away`, and `offline`, controlled by each member, with a + short server-enforced lease so abandoned sessions become offline. Presence is workspace-scoped; + admins can inspect it, but cannot silently set an agent's availability. +2. Add workspace routing policy with enable/disable, `round_robin` or `least_loaded` selection, + maximum open assigned conversations per agent, and an explicit fallback to the unassigned + queue. Only online members below capacity are eligible. Route human handoffs after their + database transaction commits; manual assignment always takes precedence. Selection and cursor + updates must be safe under concurrent handoffs. +3. Add admin-configured response and resolution targets per priority, plus an IANA timezone and + weekly business-hours schedule. An empty schedule means always-on. Count elapsed business time; + holidays are out of scope. Response timing begins at human handoff, response ends on the first + agent reply, and resolution ends when the conversation closes. +4. Add a worker-owned periodic SLA processor. Persist breach timestamps to make notifications and + audit events idempotent. Breaches notify the configured workspace admins/owners and leave the + conversation visible in the inbox; they do not automatically close or reassign it. +5. Add an Operations settings page for admins, a presence control and SLA indicators in the inbox, + role-checked APIs, audit events, shared schemas, migrations, and documentation. +6. Keep the existing manual inbox workflow as the default: auto-routing disabled, all agents + offline until they opt in, and no SLA targets until an admin configures them. + +## Out of scope + +- Skills-based or AI-based assignment, routing expressions/scripts, cross-workspace assignment, + assignment of away/offline members, and automatic SLA reassignment. +- Holiday calendars, custom pause conditions, multiple escalation tiers, on-call schedules, + external paging integrations, and WebSocket presence. The current SSE/polling model is enough. +- Guaranteed zero-overrun at concurrent boundaries; SLA processing is at-least-once and + idempotent, with minute-level precision. + +## Implementation sequence + +1. Define strict shared contracts for presence, routing policy, business hours, SLA targets, and + their API DTOs. Add coverage for bounds, timezones, invalid schedules, and defaults. +2. Add persistence and reversible migration for agent presence leases, workspace policies, and + per-conversation breach markers. Keep all data workspace-scoped and add indexes for due SLA + scans. +3. Implement self-presence APIs, admin policy read/write APIs, and audit trails. Reject setting + policies unless the caller is an owner/admin; agents can update only their own presence. +4. Implement deterministic handoff routing with eligibility, capacity counts, and the round-robin + cursor serialized by a workspace row lock. Leave the handoff unassigned when no agent qualifies. +5. Implement business-time deadline calculation, a worker-only minute schedule, idempotent breach + recording, and notifications. Do not run recurring work from API-only processes. +6. Add admin controls and inbox visibility with pending/loading/empty/error states, keyboard + access, mobile layout, and truthful copy for presence leases and SLA timing. +7. Update README and docs. Run shared/API/admin tests, migration check, integration/E2E/browser + tests, lint, typecheck, build, and CI. Record any infrastructure-only validation limits. + +## Acceptance criteria + +- Existing workspaces preserve manual assignment; routing and SLA features are inactive by default. +- Presence updates cannot target another user's ID and expire server-side after the documented + lease. A user outside the workspace cannot read or modify presence. +- Only eligible online members under capacity receive an automatic handoff; round-robin is fair + across successful assignments, least-loaded ties are deterministic, and simultaneous handoffs + cannot exceed a member's configured capacity. +- Admins can configure bounded targets and valid weekly schedules. Agents cannot change policies. +- Business-time calculation covers DST transitions and overnight schedule boundaries. Unconfigured + target values stay inactive; an empty weekly schedule means 24/7. +- Each response/resolution breach is persisted once and creates at most one alert/audit event. + Human reply and close stop their respective timers, and late processing still reports correct + breach state. +- README and docs describe defaults, routing eligibility, lease expiration, SLA clock semantics, + and exclusions accurately. +- Required CI checks pass and PR #49 is merged. + +## Progress + +- [x] Branch `feat/m26-agent-operations` from current `main`. +- [x] Shared contracts, tests, persistence and migration. +- [x] Presence and policy APIs with role and tenant-isolation tests. +- [x] Deterministic routing and concurrent capacity tests. +- [x] Business-time SLA calculation, worker, notifications, and idempotency tests. +- [x] Admin settings and inbox UX. +- [ ] Documentation, full validation, PR #49, and merge. diff --git a/packages/shared/src/agent-operations.spec.ts b/packages/shared/src/agent-operations.spec.ts new file mode 100644 index 00000000..77f2a544 --- /dev/null +++ b/packages/shared/src/agent-operations.spec.ts @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: MIT +import { describe, expect, it } from 'vitest'; + +import { + DEFAULT_AGENT_OPERATIONS_POLICY, + agentOperationsPolicySchema, + agentOperationsPolicyUpdateSchema, +} from './agent-operations.js'; + +describe('agent operations policy', () => { + it('provides conservative defaults with routing and SLA targets disabled', () => { + expect(agentOperationsPolicySchema.safeParse(DEFAULT_AGENT_OPERATIONS_POLICY).success).toBe( + true, + ); + expect(DEFAULT_AGENT_OPERATIONS_POLICY.routing.enabled).toBe(false); + expect( + Object.values(DEFAULT_AGENT_OPERATIONS_POLICY.sla.targets).every( + (target) => target.firstResponseMinutes === null && target.resolutionMinutes === null, + ), + ).toBe(true); + }); + + it('rejects invalid timezones, overlapping overnight windows, and model-added fields', () => { + const invalidTimezone = structuredClone(DEFAULT_AGENT_OPERATIONS_POLICY); + invalidTimezone.sla.timeZone = 'not/a-timezone'; + expect(agentOperationsPolicySchema.safeParse(invalidTimezone).success).toBe(false); + + const overlappingHours = structuredClone(DEFAULT_AGENT_OPERATIONS_POLICY); + overlappingHours.sla.businessHours.monday = [{ start: '22:00', end: '02:00' }]; + overlappingHours.sla.businessHours.tuesday = [{ start: '01:00', end: '03:00' }]; + expect(agentOperationsPolicySchema.safeParse(overlappingHours).success).toBe(false); + expect( + agentOperationsPolicyUpdateSchema.safeParse({ + routing: { + enabled: false, + strategy: 'round_robin', + maxOpenConversationsPerAgent: 10, + eligibleRoles: ['agent', 'admin', 'owner'], + }, + sla: overlappingHours.sla, + }).success, + ).toBe(false); + + const unknownAction = { + ...DEFAULT_AGENT_OPERATIONS_POLICY, + routeAction: 'delete_customer', + }; + expect(agentOperationsPolicySchema.safeParse(unknownAction).success).toBe(false); + }); + + it('keeps the internal round-robin cursor out of admin updates', () => { + const { enabled, strategy, maxOpenConversationsPerAgent, eligibleRoles } = + DEFAULT_AGENT_OPERATIONS_POLICY.routing; + const routing = { enabled, strategy, maxOpenConversationsPerAgent, eligibleRoles }; + expect( + agentOperationsPolicyUpdateSchema.safeParse({ + ...DEFAULT_AGENT_OPERATIONS_POLICY, + routing, + }).success, + ).toBe(true); + }); +}); diff --git a/packages/shared/src/agent-operations.ts b/packages/shared/src/agent-operations.ts new file mode 100644 index 00000000..8c7f4876 --- /dev/null +++ b/packages/shared/src/agent-operations.ts @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MIT +import { z } from 'zod'; + +import { PRIORITIES, ROLES } from './enums.js'; + +export const AGENT_PRESENCE_STATES = ['online', 'away', 'offline'] as const; +export const AGENT_PRESENCE_LEASE_SECONDS = 300; + +const minuteOfDaySchema = z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/); +const timeZoneSchema = z + .string() + .trim() + .min(1) + .max(64) + .refine((value) => { + try { + new Intl.DateTimeFormat('en', { timeZone: value }); + return true; + } catch { + return false; + } + }, 'Choose a valid IANA timezone.'); + +const businessWindowSchema = z + .object({ start: minuteOfDaySchema, end: minuteOfDaySchema }) + .strict(); + +export const agentPresenceUpdateSchema = z.object({ + state: z.enum(AGENT_PRESENCE_STATES), +}); + +export const agentPresenceSchema = z.object({ + userId: z.uuid(), + name: z.string().nullable(), + email: z.email(), + role: z.enum(ROLES), + state: z.enum(AGENT_PRESENCE_STATES), + expiresAt: z.iso.datetime().nullable(), +}); + +export const weeklyBusinessHoursSchema = z + .object({ + monday: z.array(businessWindowSchema).max(1), + tuesday: z.array(businessWindowSchema).max(1), + wednesday: z.array(businessWindowSchema).max(1), + thursday: z.array(businessWindowSchema).max(1), + friday: z.array(businessWindowSchema).max(1), + saturday: z.array(businessWindowSchema).max(1), + sunday: z.array(businessWindowSchema).max(1), + }) + .strict(); + +const businessHoursDays = [ + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday', +] as const; + +export const agentOperationsPolicySchema = z + .object({ + routing: z + .object({ + enabled: z.boolean(), + strategy: z.enum(['round_robin', 'least_loaded']), + maxOpenConversationsPerAgent: z.number().int().min(1).max(100), + eligibleRoles: z.array(z.enum(ROLES)).min(1).max(3), + lastAssignedUserId: z.uuid().nullable(), + }) + .strict() + .refine((routing) => new Set(routing.eligibleRoles).size === routing.eligibleRoles.length), + sla: z + .object({ + timeZone: timeZoneSchema, + businessHours: weeklyBusinessHoursSchema, + targets: z + .record( + z.enum(PRIORITIES), + z + .object({ + firstResponseMinutes: z.number().int().min(1).max(43_200).nullable(), + resolutionMinutes: z.number().int().min(1).max(43_200).nullable(), + }) + .strict(), + ) + .refine((targets) => PRIORITIES.every((priority) => priority in targets)), + }) + .strict(), + }) + .strict() + .superRefine(({ sla }, context) => { + const intervals = businessHoursDays.flatMap((day, dayIndex) => + sla.businessHours[day].map(({ start, end }, rangeIndex) => { + const startMinute = Number(start.slice(0, 2)) * 60 + Number(start.slice(3)); + let endMinute = Number(end.slice(0, 2)) * 60 + Number(end.slice(3)); + if (startMinute === endMinute) { + context.addIssue({ + code: 'custom', + path: ['sla', 'businessHours', day, rangeIndex], + message: 'Start and end must differ.', + }); + endMinute += 24 * 60; + } else if (endMinute < startMinute) { + endMinute += 24 * 60; + } + return { start: dayIndex * 24 * 60 + startMinute, end: dayIndex * 24 * 60 + endMinute }; + }), + ); + const weekMinutes = 7 * 24 * 60; + for (const [index, interval] of intervals.entries()) { + for (const other of intervals.slice(index + 1)) { + const overlaps = [-weekMinutes, 0, weekMinutes].some((offset) => { + const otherStart = other.start + offset; + const otherEnd = other.end + offset; + return interval.start < otherEnd && otherStart < interval.end; + }); + if (overlaps) { + context.addIssue({ + code: 'custom', + path: ['sla', 'businessHours'], + message: 'Business-hour ranges may not overlap.', + }); + } + } + } + }); + +const noBusinessHours = { + monday: [], + tuesday: [], + wednesday: [], + thursday: [], + friday: [], + saturday: [], + sunday: [], +} satisfies z.infer; + +export const DEFAULT_AGENT_OPERATIONS_POLICY: z.infer = { + routing: { + enabled: false, + strategy: 'round_robin', + maxOpenConversationsPerAgent: 10, + eligibleRoles: ['agent', 'admin', 'owner'], + lastAssignedUserId: null, + }, + sla: { + timeZone: 'UTC', + businessHours: noBusinessHours, + targets: { + low: { firstResponseMinutes: null, resolutionMinutes: null }, + normal: { firstResponseMinutes: null, resolutionMinutes: null }, + high: { firstResponseMinutes: null, resolutionMinutes: null }, + urgent: { firstResponseMinutes: null, resolutionMinutes: null }, + }, + }, +}; + +export const agentOperationsPolicyUpdateSchema = z + .object({ + routing: z + .object({ + enabled: z.boolean(), + strategy: z.enum(['round_robin', 'least_loaded']), + maxOpenConversationsPerAgent: z.number().int().min(1).max(100), + eligibleRoles: z + .array(z.enum(ROLES)) + .min(1) + .max(3) + .refine((roles) => new Set(roles).size === roles.length), + }) + .strict(), + sla: agentOperationsPolicySchema.shape.sla, + }) + .strict() + .superRefine(({ sla }, context) => { + const intervals = businessHoursDays.flatMap((day, dayIndex) => + sla.businessHours[day].map(({ start, end }, rangeIndex) => { + const startMinute = Number(start.slice(0, 2)) * 60 + Number(start.slice(3)); + let endMinute = Number(end.slice(0, 2)) * 60 + Number(end.slice(3)); + if (startMinute === endMinute) { + context.addIssue({ + code: 'custom', + path: ['sla', 'businessHours', day, rangeIndex], + message: 'Start and end must differ.', + }); + endMinute += 24 * 60; + } else if (endMinute < startMinute) { + endMinute += 24 * 60; + } + return { start: dayIndex * 24 * 60 + startMinute, end: dayIndex * 24 * 60 + endMinute }; + }), + ); + const weekMinutes = 7 * 24 * 60; + for (const [index, interval] of intervals.entries()) { + for (const other of intervals.slice(index + 1)) { + const overlaps = [-weekMinutes, 0, weekMinutes].some((offset) => { + const otherStart = other.start + offset; + const otherEnd = other.end + offset; + return interval.start < otherEnd && otherStart < interval.end; + }); + if (overlaps) { + context.addIssue({ + code: 'custom', + path: ['sla', 'businessHours'], + message: 'Business-hour ranges may not overlap.', + }); + } + } + } + }); + +export const agentOperationsResponseSchema = z.object({ + policy: agentOperationsPolicySchema, +}); + +export const conversationSlaSchema = z.object({ + firstResponseDueAt: z.iso.datetime().nullable(), + resolutionDueAt: z.iso.datetime().nullable(), + firstResponseBreachedAt: z.iso.datetime().nullable(), + resolutionBreachedAt: z.iso.datetime().nullable(), +}); + +export type AgentPresenceState = (typeof AGENT_PRESENCE_STATES)[number]; +export type AgentPresence = z.infer; +export type AgentOperationsPolicy = z.infer; +export type AgentOperationsPolicyUpdate = z.infer; +export type ConversationSla = z.infer; diff --git a/packages/shared/src/audit.ts b/packages/shared/src/audit.ts index 2c9341f1..4a1a8398 100644 --- a/packages/shared/src/audit.ts +++ b/packages/shared/src/audit.ts @@ -45,7 +45,11 @@ export const AUDIT_ACTIONS = [ 'webhook.deleted', 'webhook.replayed', 'conversation.assignment_changed', + 'conversation.auto_assigned', 'conversation.priority_changed', + 'conversation.sla_breached', + 'agent_operations.updated', + 'member.presence_changed', 'saved_reply.created', 'saved_reply.updated', 'saved_reply.archived', diff --git a/packages/shared/src/conversations.ts b/packages/shared/src/conversations.ts index 23afe6bb..5c6d615c 100644 --- a/packages/shared/src/conversations.ts +++ b/packages/shared/src/conversations.ts @@ -2,6 +2,7 @@ import { z } from 'zod'; import { conversationAiArtifactSchema, suggestedReplyArtifactSchema } from './agent-assist.js'; +import { conversationSlaSchema } from './agent-operations.js'; import { citationSchema } from './citations.js'; import { CONVERSATION_STATUSES, MESSAGE_ROLES, MESSAGE_STATUSES, PRIORITIES } from './enums.js'; import { pageQuerySchema } from './pagination.js'; @@ -99,6 +100,7 @@ export const conversationListItemSchema = z.object({ lastMessageAt: z.string(), lastMessagePreview: z.string(), unansweredByHuman: z.boolean(), + sla: conversationSlaSchema, }); /** Badge counts for the inbox navigation. `mine` excludes closed conversations. */ @@ -142,6 +144,7 @@ export const adminConversationSchema = z.object({ closedAt: z.string().nullable(), metadata: z.record(z.string(), z.unknown()), createdAt: z.string(), + sla: conversationSlaSchema, }); /** `GET …/conversations/:conversationId`: every message, oldest first. */ diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 6ab3949a..421b8c29 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -36,6 +36,23 @@ export { type TraceOrigin, } from './enums.js'; export { AUDIT_ACTIONS, auditEntrySchema, type AuditAction, type AuditEntryDto } from './audit.js'; +export { + AGENT_PRESENCE_LEASE_SECONDS, + AGENT_PRESENCE_STATES, + DEFAULT_AGENT_OPERATIONS_POLICY, + agentOperationsPolicySchema, + agentOperationsPolicyUpdateSchema, + agentOperationsResponseSchema, + agentPresenceSchema, + agentPresenceUpdateSchema, + conversationSlaSchema, + weeklyBusinessHoursSchema, + type AgentOperationsPolicy, + type AgentOperationsPolicyUpdate, + type AgentPresence, + type AgentPresenceState, + type ConversationSla, +} from './agent-operations.js'; export { EVAL_CASE_ORIGINS, EVAL_RUN_STATUSES, diff --git a/packages/shared/src/notifications.ts b/packages/shared/src/notifications.ts index f788e219..46b84be5 100644 --- a/packages/shared/src/notifications.ts +++ b/packages/shared/src/notifications.ts @@ -10,6 +10,7 @@ export const NOTIFICATION_TYPES = [ 'spend_alert', 'suggestion_created', 'suggestion_reviewed', + 'sla_breached', ] as const; export type NotificationType = (typeof NOTIFICATION_TYPES)[number]; @@ -72,6 +73,7 @@ export const DEFAULT_NOTIFICATION_PREFERENCES: Record< spend_alert: { email: true, inApp: true }, suggestion_created: { email: false, inApp: true }, suggestion_reviewed: { email: false, inApp: true }, + sla_breached: { email: true, inApp: true }, }, admin: { handoff_requested: { email: true, inApp: true }, @@ -80,6 +82,7 @@ export const DEFAULT_NOTIFICATION_PREFERENCES: Record< spend_alert: { email: true, inApp: true }, suggestion_created: { email: false, inApp: true }, suggestion_reviewed: { email: false, inApp: true }, + sla_breached: { email: true, inApp: true }, }, agent: { handoff_requested: { email: false, inApp: true }, @@ -88,6 +91,7 @@ export const DEFAULT_NOTIFICATION_PREFERENCES: Record< spend_alert: { email: false, inApp: true }, suggestion_created: { email: false, inApp: false }, suggestion_reviewed: { email: false, inApp: true }, + sla_breached: { email: false, inApp: false }, }, };