Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/api/src/harness/alerts-route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {expect, mock, test} from 'bun:test';
import {Ok} from 'ts-results-es';

import type {MemberAlertRow} from '@proxy/db/alerts';

import {fakeStore} from './fake-store';

const viewer = {orgId: 'org-1', userId: 'user-1', name: 'Northwind', role: 'member'};
mock.module('../utils/user-org', () => ({requireViewer: mock(async () => Ok(viewer))}));

const {alertRoutes} = await import('./alerts-route');

const now = new Date('2026-11-04T10:00:00Z');
const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const};
const slack = {teamId: 'T0001', channel: 'D0001', rootTs: '1761040800.000100'};

const alert: MemberAlertRow = {
id: 'alert-1',
orgId: 'org-1',
userId: 'user-1',
chatId: 'chat-1',
threadId: 'thread-1',
setInThreadId: 'thread-1',
title: 'Offsite deposit',
brief: 'Remind them to pay it.',
at: now,
nextAt: now,
every: null,
timeZone: null,
collectionId: null,
connectionIds: [],
terms: [],
split: null,
lastMatchedAt: null,
createdAt: now,
persona: {id: 'persona-1', name: 'Travel', look, color: 'teal', harness: 'proxy', chatModel: 'claude', ownerUserId: null, createdById: null, createdAt: now},
thread: {id: 'thread-1', title: 'Plan the offsite in Lisbon', slack},
setIn: {id: 'thread-1', title: 'Plan the offsite in Lisbon', slack},
};

test('an alert of a thread that lives in Slack links to that thread there; one of a thread in Chat has no link but its page', async () => {
const store = fakeStore();
store.listMemberAlerts.mockResolvedValue(Ok([alert, {...alert, id: 'alert-2', thread: null, threadId: null, setIn: {id: 'thread-2', title: 'Pricing review with Dana', slack: null}}]));
store.listConnectionsByIds.mockResolvedValue(Ok([]));

const {alerts} = (await alertRoutes(store).handleListAlertsRoute({params: {}, user: {userId: 'user-1'}} as never)).unwrap();

const url = 'https://app.slack.com/client/T0001/D0001/thread/D0001-1761040800.000100';
expect(alerts.map(({id, thread, setIn}) => [id, thread, setIn])).toEqual([
['alert-1', {id: 'thread-1', title: 'Plan the offsite in Lisbon', slackUrl: url}, {id: 'thread-1', title: 'Plan the offsite in Lisbon', slackUrl: url}],
['alert-2', null, {id: 'thread-2', title: 'Pricing review with Dana', slackUrl: null}],
]);
});
17 changes: 13 additions & 4 deletions packages/api/src/harness/alerts-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import type {z} from 'zod';

import {type ApiError, ApiErr, Do} from '@proxy/utils';
import {toAvatarColor} from '@proxy/utils/harness';
import type {MemberAlertRow} from '@proxy/db/alerts';
import type {MemberAlertRow, ThreadRef} from '@proxy/db/alerts';
import type {ConnectionRow} from '@proxy/db/connection';
import type {Alert, alertListSchema} from '@proxy/contracts/alerts';

import type {AuthenticatedRequest} from '../server/middleware/require-auth';
import {slackThreadUrl} from '../slack/thread-link';
import {requireViewer} from '../utils/user-org';
import {DEFAULT_TIME_ZONE, everyText} from './alert-repeat';
import {collectionName, connectionName} from './alerts';
Expand All @@ -28,15 +29,23 @@ function nextAt(alert: MemberAlertRow): Date | null {
return alert.every === null ? alert.at : (alert.nextAt ?? alert.at);
}

// A thread of the alert's, linked to Slack where it lives there, since the app doesn't show it.
function toThread(thread: ThreadRef | null): Alert['thread'] {
if (thread === null) {
return null;
}
return {id: thread.id, title: thread.title, slackUrl: thread.slack === null ? null : slackThreadUrl(thread.slack)};
}

function toAlert(alert: MemberAlertRow, connections: Map<string, ConnectionRow>): Alert {
return {
id: alert.id,
title: alert.title,
brief: alert.brief,
persona: {id: alert.persona.id, name: alert.persona.name, look: alert.persona.look, color: toAvatarColor(alert.persona.color)},
opens: alert.threadId === null ? 'new_thread' : 'this_thread',
thread: alert.thread,
setIn: alert.setIn,
thread: toThread(alert.thread),
setIn: toThread(alert.setIn),
at: nextAt(alert)?.toISOString() ?? null,
every: alert.every === null ? null : everyText(alert.every, alert.timeZone ?? DEFAULT_TIME_ZONE),
split: alert.split,
Expand All @@ -51,7 +60,7 @@ function toAlert(alert: MemberAlertRow, connections: Map<string, ConnectionRow>)
};
}

/** `GET /api/orgs/:org/alerts`: the viewer's alerts in the organization, newest first, each with the persona it was set with and the connections it watches. */
/** `GET /api/orgs/:org/alerts`: the viewer's alerts in the organization, newest first, each with the persona it was set with, its threads, linked to Slack where they live there, and the connections it watches. */
function handleListAlertsRoute(store: AlertsStore, request: AuthenticatedRequest): Promise<Result<z.infer<typeof alertListSchema>, ApiError>> {
return Do(async ($) => {
const viewer = $(await requireViewer(request));
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/harness/alerts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,18 +153,18 @@ describe('the words', () => {
});

test('a thread’s agent is told of every alert of the person’s, with the thread it comes to, or that it opens new ones and where it was set', () => {
const mine: MemberAlertRow = {...watch, persona, thread: {id: 'thread-1', title: 'Watch the bank'}, setIn: {id: 'thread-1', title: 'Watch the bank'}};
const mine: MemberAlertRow = {...watch, persona, thread: {id: 'thread-1', title: 'Watch the bank', slack: null}, setIn: {id: 'thread-1', title: 'Watch the bank', slack: null}};
const morning: MemberAlertRow = {
...timed,
id: 'alert-2',
threadId: 'thread-2',
setInThreadId: 'thread-2',
title: 'Morning check',
persona,
thread: {id: 'thread-2', title: 'Check the review every morning'},
setIn: {id: 'thread-2', title: 'Check the review every morning'},
thread: {id: 'thread-2', title: 'Check the review every morning', slack: null},
setIn: {id: 'thread-2', title: 'Check the review every morning', slack: null},
};
const own: MemberAlertRow = {...watch, id: 'alert-3', threadId: null, split: 'per_record', persona, thread: null, setIn: {id: 'thread-1', title: 'Watch the bank'}};
const own: MemberAlertRow = {...watch, id: 'alert-3', threadId: null, split: 'per_record', persona, thread: null, setIn: {id: 'thread-1', title: 'Watch the bank', slack: null}};

expect(alertsParagraph([], 'thread-1')).toBe('No alerts.');
expect(alertsParagraph([mine, morning, own], 'thread-1')).toBe(
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/harness/fake-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export function fakeStore(): FakeStore {
replyInThread: mock<HarnessStore['replyInThread']>(),
listChatThreads: mock<HarnessStore['listChatThreads']>(),
getChatThread: mock<HarnessStore['getChatThread']>(),
getShownThread: mock<HarnessStore['getShownThread']>(),
hasChatThread: mock<HarnessStore['hasChatThread']>(),
setThreadModel: mock<HarnessStore['setThreadModel']>(),
writeThreadStanding: mock<HarnessStore['writeThreadStanding']>(),
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/harness/inference.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ describe('runInference', () => {
createdById: null,
createdAt: now,
},
thread: {id: 'thread-1', title: 'Find the invoices'},
setIn: {id: 'thread-1', title: 'Find the invoices'},
thread: {id: 'thread-1', title: 'Find the invoices', slack: null},
setIn: {id: 'thread-1', title: 'Find the invoices', slack: null},
};
// One of the person's set in another thread is told of too.
store.listMemberAlerts.mockResolvedValue(
Expand All @@ -164,8 +164,8 @@ describe('runInference', () => {
threadId: 'thread-2',
setInThreadId: 'thread-2',
title: 'Morning check',
thread: {id: 'thread-2', title: 'Check the review every morning'},
setIn: {id: 'thread-2', title: 'Check the review every morning'},
thread: {id: 'thread-2', title: 'Check the review every morning', slack: null},
setIn: {id: 'thread-2', title: 'Check the review every morning', slack: null},
},
]),
);
Expand Down
22 changes: 22 additions & 0 deletions packages/api/src/harness/member-chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type {Result} from 'ts-results-es';

import {type ApiError, Do} from '@proxy/utils';
import type {ThreadRow} from '@proxy/db/harness';

import {getBuiltInAgent} from './built-in-agent';
import type {HarnessStore} from './store';

/**
* The member's chat with the persona, begun the first time, through the organization's built-in
* login: as the page begins it (route.ts), and as a message from Slack does (slack/messages.ts).
*/
export function ensureChat(store: Pick<HarnessStore, 'getMemberChat' | 'ensureMemberChat'>, member: {orgId: string; userId: string}, persona: {id: string}): Promise<Result<ThreadRow, ApiError>> {
return Do(async ($) => {
const existing = $(await store.getMemberChat(persona.id, member.userId));
if (existing) {
return existing;
}
const login = $(await getBuiltInAgent(member.orgId));
return $(await store.ensureMemberChat({orgId: member.orgId, agentId: login.id, personaId: persona.id, userId: member.userId}));
});
}
Loading
Loading