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
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- Per-message Slack delivery ledger. A unique messageId makes one row the
-- single durable identity of that reply; nullable claim fields let a worker
-- lease the row before posting and recover after a process exits.
CREATE TABLE "SlackMirrorDelivery" (
"id" TEXT NOT NULL,
"messageId" TEXT NOT NULL,
"deliveredAt" TIMESTAMP(3),
"claimToken" TEXT,
"claimUntil" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "SlackMirrorDelivery_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "SlackMirrorDelivery_messageId_key" ON "SlackMirrorDelivery"("messageId");

ALTER TABLE "SlackMirrorDelivery" ADD CONSTRAINT "SlackMirrorDelivery_messageId_fkey" FOREIGN KEY ("messageId") REFERENCES "Message"("id") ON DELETE CASCADE ON UPDATE CASCADE;
14 changes: 14 additions & 0 deletions packages/outpost/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ model Message {
// still PENDING, so folding them into the enum would lose the outcome.
deliveryConfirmed Boolean @default(false)
escalationRequiredReason String?
slackMirrorDelivery SlackMirrorDelivery?
attachments Json?
createdAt DateTime @default(now())

Expand All @@ -149,6 +150,19 @@ model Message {
@@index([responseState, createdAt])
}

// Per-message idempotency for posts to the external Slack mirror. This is a
// separate table because mirror delivery is independent of the source message's
// response lifecycle and must not overload responseError or attachments.
model SlackMirrorDelivery {
id String @id @default(cuid())
messageId String @unique
message Message @relation(fields: [messageId], references: [id], onDelete: Cascade)
deliveredAt DateTime?
claimToken String?
claimUntil DateTime?
createdAt DateTime @default(now())
}

enum MessageType {
USER
BOT
Expand Down
28 changes: 28 additions & 0 deletions packages/outpost/queue/src/__tests__/queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,34 @@ describe('Worker', () => {
);
});

it('respects a handler minimum retry delay longer than exponential backoff', async () => {
const jobRow = makeJobRow({ attempts: 0, maxAttempts: 5 });
mockPrisma.$queryRaw.mockResolvedValueOnce([jobRow]);
mockPrisma.$queryRaw.mockResolvedValue([]);
mockPrismaJob.updateMany.mockResolvedValue({ count: 1 });
const scheduledAt = new Date(Date.now() + 10_000);

worker.on(JobType.AI_RESPONSE, async () => ({
success: false,
error: 'external delivery lease is still active',
retryable: true,
retryAfterMs: 10_000,
}));

worker.start();
await vi.advanceTimersByTimeAsync(0);

expect(mockPrismaJob.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
status: 'PENDING',
attempts: 1,
runAt: scheduledAt,
}),
}),
);
});

it('retries failed jobs with backoff when attempts remain', async () => {
const jobRow = makeJobRow({ attempts: 1, maxAttempts: 5 }); // attempt will be 2
mockPrisma.$queryRaw.mockResolvedValueOnce([jobRow]);
Expand Down
225 changes: 213 additions & 12 deletions packages/outpost/queue/src/handlers/__tests__/slack-mirror.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,36 @@ const mockMessageFindUnique = vi.fn();
const mockLinkFindUnique = vi.fn();
const mockLinkCreate = vi.fn();
const mockLinkUpdate = vi.fn();
const mockDeliveryCreate = vi.fn();
const mockDeliveryFindUnique = vi.fn();
const mockDeliveryUpdateMany = vi.fn();
const mockQueryRaw = vi.fn();
const { mockSlackPostMessage, mockWebClientConstructor } = vi.hoisted(() => ({
mockSlackPostMessage: vi.fn(),
mockWebClientConstructor: vi.fn(),
}));
const deliveryRows = new Map<string, Record<string, unknown>>();

vi.mock('@slack/web-api', () => ({
WebClient: class {
chat = { postMessage: mockSlackPostMessage };

constructor(...args: unknown[]) {
mockWebClientConstructor(...args);
}
},
}));

vi.mock('@copilotkit/outpost/db', () => ({
prisma: {
$queryRaw: (...a: unknown[]) => mockQueryRaw(...a),
ticket: { findUnique: (...a: unknown[]) => mockTicketFindUnique(...a) },
message: { findUnique: (...a: unknown[]) => mockMessageFindUnique(...a) },
slackMirrorDelivery: {
create: (...a: unknown[]) => mockDeliveryCreate(...a),
findUnique: (...a: unknown[]) => mockDeliveryFindUnique(...a),
updateMany: (...a: unknown[]) => mockDeliveryUpdateMany(...a),
},
ticketExternalLink: {
findUnique: (...a: unknown[]) => mockLinkFindUnique(...a),
create: (...a: unknown[]) => mockLinkCreate(...a),
Expand Down Expand Up @@ -77,10 +102,52 @@ describe('isSlackMirrorEnabled', () => {
describe('handleSlackMirror', () => {
beforeEach(() => {
vi.clearAllMocks();
mockQueryRaw.mockResolvedValue([{ now: new Date() }]);
mockTicketFindUnique.mockResolvedValue(TICKET);
mockLinkFindUnique.mockResolvedValue(null);
mockLinkCreate.mockResolvedValue({});
mockLinkUpdate.mockResolvedValue({});
deliveryRows.clear();
mockDeliveryCreate.mockImplementation(
async ({ data }: { data: Record<string, unknown> }) => {
const messageId = String(data.messageId);
if (deliveryRows.has(messageId)) {
throw Object.assign(new Error('Unique constraint'), { code: 'P2002' });
}
const row = { ...data, deliveredAt: null };
deliveryRows.set(messageId, row);
return row;
},
);
mockDeliveryFindUnique.mockImplementation(
async ({ where }: { where: { messageId: string } }) =>
deliveryRows.get(where.messageId) ?? null,
);
mockDeliveryUpdateMany.mockImplementation(
async ({
where,
data,
}: {
where: Record<string, unknown>;
data: Record<string, unknown>;
}) => {
const row = deliveryRows.get(String(where.messageId));
if (!row || row.deliveredAt !== null) return { count: 0 };
if (typeof where.claimToken === 'string' && row.claimToken !== where.claimToken) {
return { count: 0 };
}
if (Array.isArray(where.OR)) {
const expired =
row.claimUntil == null ||
(row.claimUntil instanceof Date &&
row.claimUntil <=
(where.OR[1] as { claimUntil: { lte: Date } }).claimUntil.lte);
if (!expired) return { count: 0 };
}
Object.assign(row, data);
return { count: 1 };
},
);
});

it('posts nothing and touches no DB when the mirror is off', async () => {
Expand Down Expand Up @@ -370,7 +437,7 @@ describe('handleSlackMirror', () => {
});
});

it('a duplicate reply job opens no thread and writes no link', async () => {
it('a duplicate reply job does not post the same message twice', async () => {
mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' });
mockMessageFindUnique.mockResolvedValue({
id: 'msg-9',
Expand All @@ -380,22 +447,154 @@ describe('handleSlackMirror', () => {
});
const { poster, postMessage } = makePoster();

const first = await handleSlackMirror(
{ ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-9' },
context,
{ config: liveConfig, poster },
);
const duplicate = await handleSlackMirror(
{ ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-9' },
context,
{ config: liveConfig, poster },
);

expect(first.success).toBe(true);
expect(duplicate).toEqual({ success: true, data: { skipped: 'reply-already-mirrored' } });
expect(postMessage).toHaveBeenCalledTimes(1);
expect(postMessage.mock.calls[0][0].thread_ts).toBe('111.222');
expect(mockLinkCreate).not.toHaveBeenCalled();
expect(mockLinkUpdate).not.toHaveBeenCalled();
});

it('reuses one WebClient for successive jobs with the same token', async () => {
mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' });
mockMessageFindUnique.mockImplementation(async ({ where }: { where: { id: string } }) => ({
id: where.id,
author: 'octocat (12345)',
content: 'Still broken',
isAiGenerated: false,
}));
mockSlackPostMessage.mockResolvedValue({ ts: '222.333' });
const config = { ...liveConfig, token: 'xoxb-client-cache-test' };

for (let i = 0; i < 2; i++) {
const result = await handleSlackMirror(
{ ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-9' },
await handleSlackMirror(
{ ticketId: 'tkt-1', kind: 'reply', messageId: `msg-client-cache-${i}` },
context,
{ config: liveConfig, poster },
{ config },
);
expect(result.success).toBe(true);
}

// Two reply posts, but never a root post and never a link write.
expect(postMessage).toHaveBeenCalledTimes(2);
for (const [args] of postMessage.mock.calls) {
expect(args.thread_ts).toBe('111.222');
}
expect(mockLinkCreate).not.toHaveBeenCalled();
expect(mockLinkUpdate).not.toHaveBeenCalled();
expect(mockWebClientConstructor).toHaveBeenCalledTimes(1);
expect(mockWebClientConstructor).toHaveBeenCalledWith(
'xoxb-client-cache-test',
expect.objectContaining({
timeout: 30_000,
retryConfig: expect.any(Object),
}),
);
expect(mockSlackPostMessage).toHaveBeenCalledTimes(2);
});

it('truncates an over-limit reply without splitting an emoji', async () => {
mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' });
mockMessageFindUnique.mockResolvedValue({
id: 'msg-emoji',
author: 'octocat (12345)',
content: `${'a'.repeat(2798)}🇺🇸zz`,
isAiGenerated: false,
});
const { poster, postMessage } = makePoster();

await handleSlackMirror(
{ ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-emoji' },
context,
{ config: liveConfig, poster },
);

const text = postMessage.mock.calls[0][0].text;
expect(text).toContain('🇺🇸');
expect(text.endsWith('…')).toBe(true);
});

it('does not post a reply while another unexpired claim owns it', async () => {
const messageId = 'msg-busy';
deliveryRows.set(messageId, {
messageId,
claimToken: 'other-worker',
claimUntil: new Date(Date.now() + 60_000),
deliveredAt: null,
});
mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' });
mockMessageFindUnique.mockResolvedValue({
id: messageId,
author: 'octocat (12345)',
content: 'Still broken',
isAiGenerated: false,
});
const { poster, postMessage } = makePoster();

const result = await handleSlackMirror(
{ ticketId: 'tkt-1', kind: 'reply', messageId },
context,
{ config: liveConfig, poster },
);

expect(result).toMatchObject({ success: false, retryable: true });
expect(postMessage).not.toHaveBeenCalled();
});

it('keeps the reply claim and waits out its lease after a transient post failure', async () => {
mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' });
mockMessageFindUnique.mockResolvedValue({
id: 'msg-transient',
author: 'octocat (12345)',
content: 'Still broken',
isAiGenerated: false,
});
const postMessage = vi.fn().mockRejectedValue(new Error('socket hangup'));

const result = await handleSlackMirror(
{ ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-transient' },
context,
{ config: liveConfig, poster: { postMessage } },
);

expect(result.success).toBe(false);
expect(result.retryable).toBe(true);
expect(result.retryAfterMs).toBeGreaterThan(0);
expect(postMessage).toHaveBeenCalledTimes(1);
const row = deliveryRows.get('msg-transient');
expect(row?.claimToken).toEqual(expect.any(String));
expect(row?.claimUntil).toBeInstanceOf(Date);
});

it('releases the reply claim when Slack permanently rejects the post', async () => {
mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' });
mockMessageFindUnique.mockResolvedValue({
id: 'msg-perm',
author: 'octocat (12345)',
content: 'Still broken',
isAiGenerated: false,
});
const postMessage = vi.fn().mockRejectedValue(
Object.assign(new Error('An API error occurred'), {
data: { error: 'not_in_channel' },
}),
);

const result = await handleSlackMirror(
{ ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-perm' },
context,
{ config: liveConfig, poster: { postMessage } },
);

expect(result.success).toBe(false);
expect(result.retryable).toBe(false);
expect(result.error).toContain('not_in_channel');
const row = deliveryRows.get('msg-perm');
expect(row?.claimToken).toBeNull();
expect(row?.claimUntil).toBeNull();
});

it('fails the job when the ticket is gone', async () => {
Expand Down Expand Up @@ -543,6 +742,7 @@ describe('isMirrorableSource', () => {
describe('handleSlackMirror — permanent vs retryable', () => {
beforeEach(() => {
vi.clearAllMocks();
mockQueryRaw.mockResolvedValue([{ now: new Date() }]);
mockTicketFindUnique.mockResolvedValue(TICKET);
mockLinkFindUnique.mockResolvedValue(null);
mockLinkCreate.mockResolvedValue({});
Expand Down Expand Up @@ -610,6 +810,7 @@ describe('handleSlackMirror — permanent vs retryable', () => {
describe('handleSlackMirror — untrusted text', () => {
beforeEach(() => {
vi.clearAllMocks();
mockQueryRaw.mockResolvedValue([{ now: new Date() }]);
mockTicketFindUnique.mockResolvedValue({
...TICKET,
title: 'Crash <script> & more',
Expand Down
Loading