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
9 changes: 5 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,11 @@ SLACK_SOCKET_MODE=true
# silently dead.
#
# SCOPE IN v1: ticket-opens from Discord and GitHub, AI replies on both, and
# community follow-ups from DISCORD ONLY. A follow-up comment on a GitHub issue
# or discussion never reaches the mirror, and nothing logs that it did not — so
# a Slack thread that stops after the AI reply does not mean the reporter went
# quiet. See docs/deployment.md.
# community follow-ups from DISCORD and from GITHUB ISSUE COMMENTS. A follow-up
# comment on a GitHub DISCUSSION never reaches the mirror: the app has no
# discussion_comment webhook, and nothing logs that it did not — so a Slack
# thread that stops after the AI reply does not mean the reporter went quiet.
# See docs/deployment.md.
SLACK_MIRROR_MODE=off
# Channel ID, NOT a channel name. Slack: open channel -> click its name ->
# bottom of the details pane -> Channel ID. Looks like C09AB2CD3EF.
Expand Down
1 change: 1 addition & 0 deletions apps/github-app/src/__tests__/helpers/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export function mockQueue(): Record<string, unknown> {
JobType: {
AI_RESPONSE: 'AI_RESPONSE',
TICKET_CLASSIFY: 'TICKET_CLASSIFY',
SLACK_MIRROR: 'SLACK_MIRROR',
},
};
}
133 changes: 120 additions & 13 deletions apps/github-app/src/__tests__/issue-comment.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mockPrisma, mockQueue } from './helpers/mocks.js';

vi.mock('@copilotkit/outpost/db', () => mockPrisma());
Expand Down Expand Up @@ -26,7 +26,12 @@ vi.mock('@copilotkit/outpost/shared', async (importActual) => ({
truncate: vi.fn((str: string, _len: number) => str),
}));

vi.mock('@copilotkit/outpost/shared/platforms', () => ({
// The adapter is mocked so the test never talks to GitHub, but the mirror
// helpers are the REAL ones: the gate that decides whether a comment reaches
// the Slack mirror is the thing under test, and a mocked copy of it would
// assert nothing.
vi.mock('@copilotkit/outpost/shared/platforms', async (importActual) => ({
...(await importActual<typeof import('@copilotkit/outpost/shared/platforms')>()),
GitHubPlatformAdapter: vi.fn().mockImplementation(function (this: Record<string, unknown>) {
this.parseInboundEvent = mockParseInboundEvent;
this.postSystemMessage = mockPostSystemMessage;
Expand Down Expand Up @@ -67,7 +72,9 @@ const TICKET = {
sourceId: '42',
};

function makeEvent(overrides: Record<string, unknown> = {}): EmitterWebhookEvent<'issue_comment.created'> {
function makeEvent(
overrides: Record<string, unknown> = {},
): EmitterWebhookEvent<'issue_comment.created'> {
return {
id: 'evt-1',
name: 'issue_comment',
Expand All @@ -76,21 +83,21 @@ function makeEvent(overrides: Record<string, unknown> = {}): EmitterWebhookEvent
comment: {
body: 'I still have this problem after upgrading',
id: 100,
...(overrides.comment as Record<string, unknown> ?? {}),
...((overrides.comment as Record<string, unknown>) ?? {}),
},
issue: {
number: 42,
...(overrides.issue as Record<string, unknown> ?? {}),
...((overrides.issue as Record<string, unknown>) ?? {}),
},
repository: {
full_name: 'CopilotKit/CopilotKit',
...(overrides.repository as Record<string, unknown> ?? {}),
...((overrides.repository as Record<string, unknown>) ?? {}),
},
sender: {
login: 'user123',
id: 999,
type: 'User',
...(overrides.sender as Record<string, unknown> ?? {}),
...((overrides.sender as Record<string, unknown>) ?? {}),
},
...overrides,
},
Expand All @@ -106,11 +113,17 @@ describe('handleIssueComment', () => {
plugin: 'github',
externalId: 'CopilotKit/CopilotKit#42',
ticket: TICKET,
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<infer T> ? T : never);
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<
infer T
>
? T
: never);

// Legacy fallback (should not be reached when link exists)
vi.mocked(prisma.ticket.findFirst).mockResolvedValue(
TICKET as ReturnType<typeof prisma.ticket.findFirst> extends Promise<infer T> ? T : never,
TICKET as ReturnType<typeof prisma.ticket.findFirst> extends Promise<infer T>
? T
: never,
);
vi.mocked(prisma.message.create).mockResolvedValue({
id: 'msg-1',
Expand Down Expand Up @@ -207,7 +220,11 @@ describe('handleIssueComment', () => {
plugin: 'github',
externalId: 'CopilotKit/CopilotKit#42',
ticket: resolvedTicket,
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<infer T> ? T : never);
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<
infer T
>
? T
: never);

const event = makeEvent();
await handleIssueComment(event);
Expand All @@ -231,7 +248,11 @@ describe('handleIssueComment', () => {
plugin: 'github',
externalId: 'CopilotKit/CopilotKit#42',
ticket: { ...TICKET, status },
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<infer T> ? T : never);
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<
infer T
>
? T
: never);

await handleIssueComment(makeEvent());

Expand All @@ -251,7 +272,11 @@ describe('handleIssueComment', () => {
plugin: 'github',
externalId: 'CopilotKit/CopilotKit#42',
ticket: { ...TICKET, status },
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<infer T> ? T : never);
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<
infer T
>
? T
: never);

await handleIssueComment(makeEvent());

Expand All @@ -268,7 +293,11 @@ describe('handleIssueComment', () => {
plugin: 'github',
externalId: 'CopilotKit/CopilotKit#42',
ticket: waitingTicket,
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<infer T> ? T : never);
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<
infer T
>
? T
: never);

const event = makeEvent({
sender: { login: 'teambot', id: 777, type: 'User' },
Expand All @@ -288,4 +317,82 @@ describe('handleIssueComment', () => {
expect(prisma.message.create).not.toHaveBeenCalled();
expect(createJob).not.toHaveBeenCalled();
});

// ─── The Slack ticket mirror ────────────────────────────────────────────
// A GitHub comment is a community follow-up, and the mirror is supposed to
// carry the whole life of a ticket. It used to stop at the AI reply: the
// comment reached the ticket but never the mirror, and nothing logged the
// gap — so an engineer reading the Slack thread saw a ticket with one
// answer and read it as the reporter having gone quiet.
describe('Slack mirror', () => {
const originalMode = process.env.SLACK_MIRROR_MODE;
const originalChannel = process.env.SLACK_MIRROR_CHANNEL_ID;

beforeEach(() => {
process.env.SLACK_MIRROR_MODE = 'live';
process.env.SLACK_MIRROR_CHANNEL_ID = 'C09AB2CD3EF';
});

afterEach(() => {
if (originalMode === undefined) delete process.env.SLACK_MIRROR_MODE;
else process.env.SLACK_MIRROR_MODE = originalMode;
if (originalChannel === undefined) delete process.env.SLACK_MIRROR_CHANNEL_ID;
else process.env.SLACK_MIRROR_CHANNEL_ID = originalChannel;
});

it('mirrors the comment into the ticket thread as a reply, not a new root', async () => {
await handleIssueComment(makeEvent());

expect(createJob).toHaveBeenCalledWith('SLACK_MIRROR', {
ticketId: 'ticket-1',
source: 'github',
kind: 'reply',
messageId: 'msg-1',
});
});

it('mirrors a team member comment too — the thread is the whole ticket', async () => {
await handleIssueComment(
makeEvent({ sender: { login: 'teambot', id: 777, type: 'User' } }),
);

expect(createJob).toHaveBeenCalledWith(
'SLACK_MIRROR',
expect.objectContaining({ kind: 'reply', messageId: 'msg-1' }),
);
});

it('does not enqueue a mirror job when the mirror is off', async () => {
process.env.SLACK_MIRROR_MODE = 'off';
await handleIssueComment(makeEvent());

expect(createJob).not.toHaveBeenCalled();
});

it('does not enqueue a mirror job while no channel is configured', async () => {
delete process.env.SLACK_MIRROR_CHANNEL_ID;
await handleIssueComment(makeEvent());

expect(createJob).not.toHaveBeenCalled();
});

it('does not enqueue a mirror job for a source the mirror does not cover', async () => {
vi.mocked(prisma.ticketExternalLink.findUnique).mockResolvedValue({
id: 'link-1',
ticketId: 'ticket-1',
plugin: 'github',
externalId: 'CopilotKit/CopilotKit#42',
ticket: { ...TICKET, source: 'WEB' },
} as unknown as ReturnType<typeof prisma.ticketExternalLink.findUnique> extends Promise<
infer T
>
? T
: never);

await handleIssueComment(makeEvent());

expect(prisma.message.create).toHaveBeenCalled();
expect(createJob).not.toHaveBeenCalled();
});
});
});
42 changes: 38 additions & 4 deletions apps/github-app/src/webhooks/issue-comment.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import type { EmitterWebhookEvent } from '@octokit/webhooks';
import { prisma } from '@copilotkit/outpost/db';
import { GitHubPlatformAdapter } from '@copilotkit/outpost/shared/platforms';
import { createJob, JobType } from '@copilotkit/outpost/queue';
import {
GitHubPlatformAdapter,
isMirrorableSource,
isSlackMirrorEnabled,
readSlackMirrorConfig,
toPlatformTarget,
} from '@copilotkit/outpost/shared/platforms';
import { reopensOnCustomerReply } from '@copilotkit/outpost/shared';
import { getOctokit } from '../lib/github-client.js';
import { findTicketBySourceId, isTeamMember } from '../lib/tickets.js';
Expand All @@ -14,7 +21,7 @@ export async function handleIssueComment(

console.log(
`[GitHub App] Comment on ${repository.full_name}#${issue.number} ` +
`by ${sender.login}: ${(comment.body ?? '').slice(0, 100)}`,
`by ${sender.login}: ${(comment.body ?? '').slice(0, 100)}`,
);

if (!isRepoAllowed(repository.full_name, config.allowedRepos)) {
Expand Down Expand Up @@ -51,11 +58,12 @@ export async function handleIssueComment(

// Append the comment as a Message on the ticket
const commentBody = message.content || comment.body;
await prisma.message.create({
const storedComment = await prisma.message.create({
data: {
ticketId: ticket.id,
author: `${sender.login} (${sender.id})`,
content: commentBody.length > 8000 ? commentBody.slice(0, 7997) + '...' : commentBody,
content:
commentBody.length > 8000 ? commentBody.slice(0, 7997) + '...' : commentBody,
type: 'USER',
},
});
Expand All @@ -64,6 +72,32 @@ export async function handleIssueComment(
`[GitHub App] Comment from ${sender.login} appended to ticket ${ticket.displayId}`,
);

// Mirror the follow-up under the ticket's existing Slack thread, the
// same way the shared InboundHandler mirrors a Discord reply. Without
// this, the reporter's follow-up on GitHub never reaches the mirror and
// an engineer reading the Slack thread sees a ticket with one AI answer
// and reads it as the reporter having gone quiet.
//
// The gate is the pair every other mirror producer uses: the mirror has
// to be configured, and the ticket's source has to be mirrorable. The
// mirror is an internal convenience view, so a queue hiccup here must
// never take down the comment handling for a real reporter.
if (isMirrorableSource(ticket.source) && isSlackMirrorEnabled(readSlackMirrorConfig())) {
try {
await createJob(JobType.SLACK_MIRROR, {
ticketId: ticket.id,
source: toPlatformTarget(ticket.source),
kind: 'reply',
messageId: storedComment.id,
});
} catch (error) {
console.error(
`[GitHub App] Failed to enqueue Slack mirror for ticket ${ticket.displayId}:`,
error instanceof Error ? error.message : String(error),
);
}
}

// Check if the commenter is a team member
const teamMember = await isTeamMember(sender.login);

Expand Down
2 changes: 1 addition & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Copy `.env.example` and fill in all values. Key groups:
- **Discord**: `DISCORD_TOKEN`, `DISCORD_CLIENT_ID`, `GUILD_ID`, `MONITORED_CHANNEL_IDS`
- **GitHub App**: `GITHUB_APP_ID`, `GITHUB_PRIVATE_KEY`, `GITHUB_INSTALLATION_ID`, `GITHUB_WEBHOOK_SECRET`, `GITHUB_TEAM_LOGINS` (optional)
- **Slack**: `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN`, `SLACK_SIGNING_SECRET`, `MONITORED_CHANNEL_IDS`, `TEAM_MEMBER_IDS` (optional)
- **Slack ticket mirror**: `SLACK_MIRROR_MODE` (`off` | `shadow` | `live`, default `off`), `SLACK_MIRROR_CHANNEL_ID` (channel ID, not name). **Set both on `outpost-worker` AND on every service that creates tickets** (`outpost-discord-bot`, `outpost-github-app`): the handler runs in the worker, but the producers gate on the same config via `readSlackMirrorConfig()` inside `InboundHandler`, so vars present only on the worker mean no job is ever enqueued and the mirror is silently dead. `live` also needs `SLACK_BOT_TOKEN` with `chat:write` **on the worker**. Without it the mirror does NOT simply log once and carry on: each mirror job dead-letters, one per ticket and one per reply, and that content is gone rather than retried once the token appears. Set the token before setting `live`, or leave the mode `off`. `shadow` needs no token. Any mode is inert while `SLACK_MIRROR_CHANNEL_ID` is unset. Invite the bot to the channel or posts fail `not_in_channel`, which the handler treats as permanent and does not retry. Which tickets get mirrored is decided by `isMirrorableSource()` in `packages/outpost/shared/src/platforms/slack-mirror-config.ts` (today: Discord + GitHub issues and discussions; Slack-sourced tickets are excluded because they already live in Slack). **Scope in v1: ticket-opens from Discord and GitHub, AI replies on both, and community follow-ups from Discord only.** A follow-up comment on a GitHub issue or discussion does NOT reach the mirror: `apps/github-app/src/webhooks/issue-comment.ts` appends its `Message` row directly rather than through `InboundHandler`, so it never enqueues a mirror job, and GitHub Discussions have no comment webhook at all. Nothing logs the omission, so a Slack thread that stops after the AI reply means "no Discord follow-ups", not "the reporter went quiet" — check the GitHub thread itself before concluding anything from the mirror. `SLACK_MIRROR_MODE` is intentionally independent of `SHADOW_MODE`: that flag protects community surfaces, while the mirror targets an internal channel — see the shadow-mode section for the documented exception. Keep `SLACK_MIRROR_CHANNEL_ID` out of the Slack bot's `MONITORED_CHANNEL_IDS`: the bot drops `bot_id` events today, so its own mirror posts do not become tickets, but monitoring the mirror channel would duplicate ticket context into the inbound path and leave the loop one filter change away.
- **Slack ticket mirror**: `SLACK_MIRROR_MODE` (`off` | `shadow` | `live`, default `off`), `SLACK_MIRROR_CHANNEL_ID` (channel ID, not name). **Set both on `outpost-worker` AND on every service that creates tickets** (`outpost-discord-bot`, `outpost-github-app`): the handler runs in the worker, but the producers gate on the same config via `readSlackMirrorConfig()` — inside `InboundHandler`, and in the GitHub app's issue-comment webhook — so vars present only on the worker mean no job is ever enqueued and the mirror is silently dead. `live` also needs `SLACK_BOT_TOKEN` with `chat:write` **on the worker**. Without it the mirror does NOT simply log once and carry on: each mirror job dead-letters, one per ticket and one per reply, and that content is gone rather than retried once the token appears. Set the token before setting `live`, or leave the mode `off`. `shadow` needs no token. Any mode is inert while `SLACK_MIRROR_CHANNEL_ID` is unset. Invite the bot to the channel or posts fail `not_in_channel`, which the handler treats as permanent and does not retry. Which tickets get mirrored is decided by `isMirrorableSource()` in `packages/outpost/shared/src/platforms/slack-mirror-config.ts` (today: Discord + GitHub issues and discussions; Slack-sourced tickets are excluded because they already live in Slack). **Scope in v1: ticket-opens from Discord and GitHub, AI replies on both, and community follow-ups from Discord and from GitHub issue comments.** A follow-up comment on a GitHub DISCUSSION does NOT reach the mirror: `discussion_comment` is a separate GitHub event and `apps/github-app/src/webhooks/` has no handler for it, so no mirror job is ever enqueued for one, and nothing logs the omission. A Slack thread that stops after the AI reply therefore means "no follow-ups from Discord or GitHub issues", not "the reporter went quiet" — check the GitHub thread itself before concluding anything from the mirror. `SLACK_MIRROR_MODE` is intentionally independent of `SHADOW_MODE`: that flag protects community surfaces, while the mirror targets an internal channel — see the shadow-mode section for the documented exception. Keep `SLACK_MIRROR_CHANNEL_ID` out of the Slack bot's `MONITORED_CHANNEL_IDS`: the bot drops `bot_id` events today, so its own mirror posts do not become tickets, but monitoring the mirror channel would duplicate ticket context into the inbound path and leave the loop one filter change away.
- **Teams**: `TEAMS_APP_ID`, `TEAMS_APP_PASSWORD`, `TEAMS_TENANT_ID` (optional, blank for multi-tenant), `MONITORED_CHANNEL_IDS`
- **Linear sync**: `LINEAR_API_KEY`, `LINEAR_WEBHOOK_SECRET`, `LINEAR_TEAM_ID`
- **Monitoring**: `SENTRY_DSN` (optional), `LOG_LEVEL`
Expand Down
10 changes: 9 additions & 1 deletion packages/outpost/shared/src/platforms/inbound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,16 @@ function isUniqueConstraintError(err: unknown): boolean {

/**
* Map TicketSource to PlatformTarget for job payloads.
*
* Exported so a producer that builds a job payload outside the handler — the
* GitHub app's issue-comment webhook — resolves the same target the handler
* does, rather than repeating the mapping a third time.
*
* Takes the source as a string because Prisma's generated `TicketSource` is a
* union of string literals, not this package's enum, and the two carry the
* same values.
*/
function toPlatformTarget(source: TicketSource): string {
export function toPlatformTarget(source: string): string {
switch (source) {
case TicketSource.DISCORD:
return 'discord';
Expand Down
Loading