diff --git a/.env.example b/.env.example index 030a0700..50b8f172 100644 --- a/.env.example +++ b/.env.example @@ -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. diff --git a/apps/github-app/src/__tests__/helpers/mocks.ts b/apps/github-app/src/__tests__/helpers/mocks.ts index c6c6f0df..b48e1272 100644 --- a/apps/github-app/src/__tests__/helpers/mocks.ts +++ b/apps/github-app/src/__tests__/helpers/mocks.ts @@ -37,6 +37,7 @@ export function mockQueue(): Record { JobType: { AI_RESPONSE: 'AI_RESPONSE', TICKET_CLASSIFY: 'TICKET_CLASSIFY', + SLACK_MIRROR: 'SLACK_MIRROR', }, }; } diff --git a/apps/github-app/src/__tests__/issue-comment.test.ts b/apps/github-app/src/__tests__/issue-comment.test.ts index 99bdb6e7..1b5b5ef3 100644 --- a/apps/github-app/src/__tests__/issue-comment.test.ts +++ b/apps/github-app/src/__tests__/issue-comment.test.ts @@ -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()); @@ -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()), GitHubPlatformAdapter: vi.fn().mockImplementation(function (this: Record) { this.parseInboundEvent = mockParseInboundEvent; this.postSystemMessage = mockPostSystemMessage; @@ -67,7 +72,9 @@ const TICKET = { sourceId: '42', }; -function makeEvent(overrides: Record = {}): EmitterWebhookEvent<'issue_comment.created'> { +function makeEvent( + overrides: Record = {}, +): EmitterWebhookEvent<'issue_comment.created'> { return { id: 'evt-1', name: 'issue_comment', @@ -76,21 +83,21 @@ function makeEvent(overrides: Record = {}): EmitterWebhookEvent comment: { body: 'I still have this problem after upgrading', id: 100, - ...(overrides.comment as Record ?? {}), + ...((overrides.comment as Record) ?? {}), }, issue: { number: 42, - ...(overrides.issue as Record ?? {}), + ...((overrides.issue as Record) ?? {}), }, repository: { full_name: 'CopilotKit/CopilotKit', - ...(overrides.repository as Record ?? {}), + ...((overrides.repository as Record) ?? {}), }, sender: { login: 'user123', id: 999, type: 'User', - ...(overrides.sender as Record ?? {}), + ...((overrides.sender as Record) ?? {}), }, ...overrides, }, @@ -106,11 +113,17 @@ describe('handleIssueComment', () => { plugin: 'github', externalId: 'CopilotKit/CopilotKit#42', ticket: TICKET, - } as unknown as ReturnType extends Promise ? T : never); + } as unknown as ReturnType extends Promise< + infer T + > + ? T + : never); // Legacy fallback (should not be reached when link exists) vi.mocked(prisma.ticket.findFirst).mockResolvedValue( - TICKET as ReturnType extends Promise ? T : never, + TICKET as ReturnType extends Promise + ? T + : never, ); vi.mocked(prisma.message.create).mockResolvedValue({ id: 'msg-1', @@ -207,7 +220,11 @@ describe('handleIssueComment', () => { plugin: 'github', externalId: 'CopilotKit/CopilotKit#42', ticket: resolvedTicket, - } as unknown as ReturnType extends Promise ? T : never); + } as unknown as ReturnType extends Promise< + infer T + > + ? T + : never); const event = makeEvent(); await handleIssueComment(event); @@ -231,7 +248,11 @@ describe('handleIssueComment', () => { plugin: 'github', externalId: 'CopilotKit/CopilotKit#42', ticket: { ...TICKET, status }, - } as unknown as ReturnType extends Promise ? T : never); + } as unknown as ReturnType extends Promise< + infer T + > + ? T + : never); await handleIssueComment(makeEvent()); @@ -251,7 +272,11 @@ describe('handleIssueComment', () => { plugin: 'github', externalId: 'CopilotKit/CopilotKit#42', ticket: { ...TICKET, status }, - } as unknown as ReturnType extends Promise ? T : never); + } as unknown as ReturnType extends Promise< + infer T + > + ? T + : never); await handleIssueComment(makeEvent()); @@ -268,7 +293,11 @@ describe('handleIssueComment', () => { plugin: 'github', externalId: 'CopilotKit/CopilotKit#42', ticket: waitingTicket, - } as unknown as ReturnType extends Promise ? T : never); + } as unknown as ReturnType extends Promise< + infer T + > + ? T + : never); const event = makeEvent({ sender: { login: 'teambot', id: 777, type: 'User' }, @@ -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 extends Promise< + infer T + > + ? T + : never); + + await handleIssueComment(makeEvent()); + + expect(prisma.message.create).toHaveBeenCalled(); + expect(createJob).not.toHaveBeenCalled(); + }); + }); }); diff --git a/apps/github-app/src/webhooks/issue-comment.ts b/apps/github-app/src/webhooks/issue-comment.ts index 607c54a0..572782f2 100644 --- a/apps/github-app/src/webhooks/issue-comment.ts +++ b/apps/github-app/src/webhooks/issue-comment.ts @@ -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'; @@ -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)) { @@ -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', }, }); @@ -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); diff --git a/docs/deployment.md b/docs/deployment.md index 4dedd2d5..256441d0 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -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` diff --git a/packages/outpost/shared/src/platforms/inbound.ts b/packages/outpost/shared/src/platforms/inbound.ts index 2cd45a89..32d7d229 100644 --- a/packages/outpost/shared/src/platforms/inbound.ts +++ b/packages/outpost/shared/src/platforms/inbound.ts @@ -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'; diff --git a/packages/outpost/shared/src/platforms/index.ts b/packages/outpost/shared/src/platforms/index.ts index 6c542818..e3e84427 100644 --- a/packages/outpost/shared/src/platforms/index.ts +++ b/packages/outpost/shared/src/platforms/index.ts @@ -32,7 +32,7 @@ export { getAdapter, hasAdapter, clearAdapterCache, SUPPORTED_PLATFORMS } from ' export { buildTicketSourceId } from './source-id.js'; // Inbound handler -export { InboundHandler } from './inbound.js'; +export { InboundHandler, toPlatformTarget } from './inbound.js'; export type { InboundHandlerConfig, CreateJobFn, HandleOptions } from './inbound.js'; export type { PrismaLike as InboundPrismaLike } from './inbound.js';