Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
slack: improve command (#2820)
Thibault Le Ouay022708b8f91e
diff --git a/apps/dashboard/src/components/forms/incident/form.tsx b/apps/dashboard/src/components/forms/incident/form.tsxindex 568318bea..308931634 100644--- a/apps/dashboard/src/components/forms/incident/form.tsx+++ b/apps/dashboard/src/components/forms/incident/form.tsx@@ -303,7 +303,7 @@ export function FormDeclareIncident({/></FormControl><FormLabel className="font-normal">- Open a Slack channel and invite the team+ Open a Slack channel and try to add you to it</FormLabel></FormItem>)}diff --git a/apps/server/scripts/slack-manifest-dev.ts b/apps/server/scripts/slack-manifest-dev.tsindex 89b336ec9..b1a6f0da1 100644--- a/apps/server/scripts/slack-manifest-dev.ts+++ b/apps/server/scripts/slack-manifest-dev.ts@@ -17,7 +17,14 @@ if (!redirectUri) {);Deno.exit(1);}-const devOrigin = new URL(redirectUri).origin;+const redirectUrl = new URL(redirectUri);+if (redirectUrl.pathname !== "/slack/oauth/callback") {+ console.error(+ `SLACK_REDIRECT_URI must have the exact path /slack/oauth/callback — got ${redirectUri}`,+ );+ Deno.exit(1);+}+const devOrigin = redirectUrl.origin;const dev = structuredClone(manifest);dev.display_information.name = DEV_NAME;diff --git a/apps/server/slack-manifest.json b/apps/server/slack-manifest.jsonindex 26a4e4a71..b0ebe94fe 100644--- a/apps/server/slack-manifest.json+++ b/apps/server/slack-manifest.json@@ -1,9 +1,9 @@{"display_information": {"name": "openstatus",- "description": "The incident communication agent for your status pages.",+ "description": "Run incidents and keep your status page up to date, without leaving Slack.","background_color": "#000000",- "long_description": "openstatus is an agent for incident communication. Open it from the Slack top bar, or mention @openstatus in any channel, and it turns the conversation into status page updates — no context switching required.\n\n How it works:\n :one: Open openstatus in the agent pane and describe the issue, or mention @openstatus in an incident channel or thread\n :two: The agent reads the conversation, queries your status pages, and drafts a status update\n :three: Review the proposed action and click Approve, Approve & Notify, or Cancel\n\n What you can do:\n :white_check_mark: Create status reports from natural conversation\n :white_check_mark: Post progress updates as incidents evolve\n :white_check_mark: Resolve incidents when the issue is fixed\n :white_check_mark: Schedule maintenance windows in plain language\n :white_check_mark: Notify your status page subscribers with one click\n\n The agent understands context — tag it in an ongoing thread and it will synthesize the discussion into a clear, public-facing status update. It infers incident status automatically: \"we found the root cause\" becomes Identified, \"it's fixed\" becomes Resolved.\n\n AI disclaimer: openstatus uses large language models (LLMs) to summarize conversations, draft status updates, and infer incident status. AI-generated content may sometimes be inaccurate, incomplete, or misleading. Always review every draft before approving it — nothing is posted to your status page until you explicitly confirm. Only the person who triggered the action can approve it, and you can edit or cancel any draft."+ "long_description": "openstatus runs your incidents and status page from Slack. Declare an incident and it opens a dedicated channel for it. Mention @openstatus in that channel or any thread, or open it from the Slack top bar, and it turns the conversation into status page updates. Nothing is published until you approve it.\n\nIncidents\n:rotating_light: Declare an incident from the Declare incident shortcut, a message's ⋯ menu, or /openstatus incident declare\n:hash: openstatus opens a dedicated channel and adds you to it\n:memo: Add notes to the timeline, mark the incident mitigated or resolved, and draft the postmortem\n\nStatus page updates\n:speech_balloon: Mention @openstatus in a thread and it drafts a status report from the discussion\n:white_check_mark: Click Approve to publish it, or Approve & Notify to also notify your subscribers\n:arrows_counterclockwise: Say \"we found the cause\" or \"it's fixed\" and it moves the report to Identified or Resolved\n:calendar: Schedule maintenance windows in plain language\n\nStatus page subscriptions\n:bell: /openstatus subscribe <status-page-url> posts a status page's updates in a channel\n\nAI disclaimer\nopenstatus uses large language models (LLMs) to summarize conversations, draft status updates, and infer incident status. AI-generated content may be inaccurate or incomplete, so review every draft before approving it. Nothing is posted to your status page until you confirm, only the person who triggered the action can approve it, and you can cancel any draft."},"features": {"agent_view": {@@ -36,12 +36,26 @@"display_name": "openstatus","always_online": true},+ "shortcuts": [+ {+ "name": "Declare incident",+ "type": "global",+ "callback_id": "declare_incident",+ "description": "Declare an incident in openstatus"+ },+ {+ "name": "Declare incident",+ "type": "message",+ "callback_id": "declare_incident_from_message",+ "description": "Declare an incident from this message"+ }+ ],"slash_commands": [{"command": "/openstatus","url": "https://api.openstatus.dev/slack/commands",- "description": "Incidents and status page subscriptions from Slack",- "usage_hint": "incident declare | incident note | incident list | subscribe | help",+ "description": "Run incidents and manage status page subscriptions",+ "usage_hint": "incident declare | incident list | subscribe <status-page-url> | help","should_escape": false}]diff --git a/apps/server/src/libs/test/doubles/slack-web-api.mock.ts b/apps/server/src/libs/test/doubles/slack-web-api.mock.tsindex 05ea11c85..01a73fc12 100644--- a/apps/server/src/libs/test/doubles/slack-web-api.mock.ts+++ b/apps/server/src/libs/test/doubles/slack-web-api.mock.ts@@ -115,5 +115,9 @@ export class WebClient {s.calls.push({ method: "views.publish", args });return Promise.resolve({ ok: true });},+ open: (args: Record<string, unknown>) => {+ s.calls.push({ method: "views.open", args });+ return Promise.resolve({ ok: true });+ },};}diff --git a/apps/server/src/routes/slack/commands.test.ts b/apps/server/src/routes/slack/commands.test.tsindex f77d11526..4735c844c 100644--- a/apps/server/src/routes/slack/commands.test.ts+++ b/apps/server/src/routes/slack/commands.test.ts@@ -34,12 +34,14 @@ function post(text: string,user: string,channelId = "C1",+ extra: Record<string, string> = {},) {const body = new URLSearchParams({text,team_id: "T_KNOWN",user_id: user,channel_id: channelId,+ ...extra,}).toString();const timestamp = Math.floor(Date.now() / 1000);const sig = crypto@@ -72,6 +74,35 @@ describe("handleSlackCommand (members only)", () => {: Promise.resolve(null);});+ test("`incident declare` without a title opens the form", async () => {+ slackTestState.usersInfoImpl = () =>+ Promise.resolve({+ ok: true,+ user: { profile: { email: "[email protected]" } },+ });+ const res = await post(app, "incident declare", "U_OWNER", "C_HERE", {+ trigger_id: "trig-cmd",+ });+ expect(res.status).toBe(200);+ const open = slackTestState.calls.find((c) => c.method === "views.open");+ expect(open?.args.trigger_id).toBe("trig-cmd");+ const view = open?.args.view as Record<string, unknown>;+ expect(view.callback_id).toBe("declare_incident");+ expect(view.private_metadata).toBe(JSON.stringify({ channelId: "C_HERE" }));+ });++ test("`incident declare` in an unconnected workspace says so", async () => {+ const res = await post(app, "incident declare", "U_OWNER", "C_HERE", {+ trigger_id: "trig-cmd",+ team_id: "T_UNKNOWN",+ });+ const json = (await res.json()) as { text: string };+ expect(json.text).toContain("isn't connected");+ expect(slackTestState.calls.some((c) => c.method === "views.open")).toBe(+ false,+ );+ });+test("help needs no link", async () => {const res = await post(app, "help", `U_${crypto.randomUUID()}`);const json = (await res.json()) as { text: string };diff --git a/apps/server/src/routes/slack/commands.ts b/apps/server/src/routes/slack/commands.tsindex ea67c2fdc..012bea8b9 100644--- a/apps/server/src/routes/slack/commands.ts+++ b/apps/server/src/routes/slack/commands.ts@@ -17,6 +17,7 @@ import {} from "./blocks";import type { SlackConfig, SlackEnv } from "./config";import { runIncidentCommand } from "./incident-commands";+import { openDeclareIncidentModal } from "./incident-modal";import {linkAccountUrl,planRequiredMessage,@@ -35,16 +36,18 @@ const slashCommandSchema = z.object({channel_id: z.string(),channel_name: z.string().optional(),response_url: z.string().optional(),+ trigger_id: z.string().optional(),});type SlashCommand = z.infer<typeof slashCommandSchema>;const HELP = ["*openstatus*",+ "• `/openstatus incident declare` — declare an incident (opens a form)",+ "• `/openstatus incident help` — run incidents: notes, status, postmortem","• `/openstatus subscribe <status-page-url>` — subscribe this channel to a status page","• `/openstatus unsubscribe <status-page-url>` — unsubscribe","• `/openstatus subscriptions` — show this channel's subscriptions",- "• `/openstatus incident help` — declare and run incidents",].join("\n");type CommandReply = { text: string; blocks?: Block[] };@@ -92,6 +95,42 @@ export function handleSlackCommand(c: Context<SlackEnv>) {const command = parsed.data;const sub = subcommand(command);+ const triggerId = command.trigger_id;+ if (triggerId && opensDeclareModal(command)) {+ // `trigger_id` stays valid for 3s after the user's action whether or not+ // we have acked, so ack now and open the form in the background.+ const open = () =>+ openDeclareIncidentModal({+ teamId: command.team_id,+ slackUserId: command.user_id,+ triggerId,+ channelId: command.channel_id,+ config,+ }).then(+ (notice): CommandReply | undefined =>+ notice ? { text: notice } : undefined,+ (error) => {+ logger.error("slack declare modal open failed", { error });+ return { text: ":x: Could not open the form. Please try again." };+ },+ );+ const responseUrl = command.response_url;+ if (!responseUrl) {+ return open().then((reply) =>+ reply ? ephemeral(c, reply) : c.body(null, 200),+ );+ }+ runInBackground(+ "command declare modal",+ async () => {+ const reply = await open();+ if (reply) await respondLater(responseUrl, reply);+ },+ { teamId: command.team_id, channelId: command.channel_id },+ );+ return c.body(null, 200);+ }+// `help` — and anything unrecognised, which falls through to it — needs no// I/O, so it is answered in the ack itself.if (@@ -141,6 +180,16 @@ function subcommand(command: SlashCommand): string {return (tokens[0] ?? "help").toLowerCase();}+/** `/openstatus incident declare` with no title opens the form instead. */+function opensDeclareModal(command: SlashCommand): boolean {+ const words = command.text.trim().split(/\s+/).filter(Boolean);+ return (+ words.length === 2 &&+ words[0].toLowerCase() === "incident" &&+ words[1].toLowerCase() === "declare"+ );+}+function argument(command: SlashCommand): string | undefined {return command.text.trim().split(/\s+/).filter(Boolean)[1];}diff --git a/apps/server/src/routes/slack/handler.ts b/apps/server/src/routes/slack/handler.tsindex 307609171..0e989cea7 100644--- a/apps/server/src/routes/slack/handler.ts+++ b/apps/server/src/routes/slack/handler.ts@@ -35,7 +35,7 @@ import type { SlackConfig, SlackEnv } from "./config";import { makeRefResolvers } from "./confirmation-card";import { draftKey, findByThread, replace, store } from "./confirmation-store";import type { PendingPayload } from "./confirmation-store";-import { publishHomeView, publishLinkAccountView } from "./home";+import { homeIncidents, publishHomeView, publishLinkAccountView } from "./home";import { handleChannelGone, handlePinReaction } from "./incident-events";import {getComponentNames,@@ -433,6 +433,13 @@ async function processEvent(body: SlackEvent, config: SlackConfig) {reconnectUrl: needsReconnect? `${config.dashboardUrl}/settings/integrations`: undefined,+ openIncidents: await homeIncidents({+ workspace: resolved.workspace,+ actor,+ }).catch((error) => {+ logger.warn("slack home incidents failed", { error, teamId });+ return undefined;+ }),});} else {const url = await linkAccountUrl(config, {diff --git a/apps/server/src/routes/slack/home.test.ts b/apps/server/src/routes/slack/home.test.tsnew file mode 100644index 000000000..0450a2e01--- /dev/null+++ b/apps/server/src/routes/slack/home.test.ts@@ -0,0 +1,42 @@+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import { buildHomeBlocks, OPEN_DECLARE_INCIDENT_ACTION } from "./home";++describe("buildHomeBlocks", () => {+ test("hides incidents when the feature is off", () => {+ const text = JSON.stringify(buildHomeBlocks());+ expect(text).not.toContain(OPEN_DECLARE_INCIDENT_ACTION);+ expect(text).not.toContain("incident declare");+ });++ test("lists open incidents with the declare button", () => {+ const text = JSON.stringify(+ buildHomeBlocks({+ openIncidents: [+ {+ id: 7,+ title: "API <down>",+ severity: "critical",+ status: "open",+ url: "https://app.test/incidents/7",+ slackChannelId: "C_INC",+ },+ ],+ }),+ );+ expect(text).toContain(OPEN_DECLARE_INCIDENT_ACTION);+ expect(text).toContain("<https://app.test/incidents/7|API <down>>");+ expect(text).toContain("<#C_INC>");+ expect(text).toContain(+ "API <down>>* · Critical · Open · #7 · <#C_INC>",+ );+ expect(text).toContain("/openstatus incident declare");+ });++ test("says so when nothing is open", () => {+ expect(JSON.stringify(buildHomeBlocks({ openIncidents: [] }))).toContain(+ "No open incidents",+ );+ });+});diff --git a/apps/server/src/routes/slack/home.ts b/apps/server/src/routes/slack/home.tsindex 3fc7008e4..be7fa2f86 100644--- a/apps/server/src/routes/slack/home.ts+++ b/apps/server/src/routes/slack/home.ts@@ -1,12 +1,106 @@+import { isFeatureEnabled, type ServiceContext } from "@openstatus/services";+import { escapeMrkdwn, listIncidents } from "@openstatus/services/incident";import type { WebClient } from "@slack/web-api";import type { KnownBlock } from "@slack/web-api";import { buildLinkAccountBlocks } from "./blocks";+import { getIncidentDashboardUrl } from "./page-urls";export const DOCS_URL = "https://www.openstatus.dev/docs";+export const OPEN_DECLARE_INCIDENT_ACTION = "open_declare_incident";++export type HomeIncident = {+ id: number;+ title: string;+ severity: string;+ status: string;+ url: string;+ slackChannelId: string | null;+};++const SEVERITY_EMOJI: Record<string, string> = {+ critical: ":red_circle:",+ major: ":large_orange_circle:",+ minor: ":large_yellow_circle:",+};++function capitalize(value: string): string {+ return value.charAt(0).toUpperCase() + value.slice(1);+}++function incidentLine(i: HomeIncident): KnownBlock {+ const text = [+ `${SEVERITY_EMOJI[i.severity] ?? "•"} *<${i.url}|${escapeMrkdwn(i.title)}>*`,+ capitalize(i.severity),+ capitalize(i.status),+ `#${i.id}`,+ ...(i.slackChannelId ? [`<#${i.slackChannelId}>`] : []),+ ].join(" · ");+ return { type: "section", text: { type: "mrkdwn", text } };+}++function incidentBlocks(openIncidents: HomeIncident[]): KnownBlock[] {+ const heading =+ openIncidents.length === 0+ ? "*Open incidents*"+ : `*Open incidents (${openIncidents.length})*`;+ return [+ {+ type: "section",+ text: { type: "mrkdwn", text: heading },+ accessory: {+ type: "button",+ text: { type: "plain_text", text: "Declare incident", emoji: true },+ style: "danger",+ action_id: OPEN_DECLARE_INCIDENT_ACTION,+ },+ },+ ...(openIncidents.length === 0+ ? [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: ":white_check_mark: No open incidents. All quiet.",+ },+ } satisfies KnownBlock,+ ]+ : openIncidents.map(incidentLine)),+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: "Declaring an incident opens a dedicated channel and adds you to it. You can also use the *Declare incident* shortcut: type `/` in any message box, or pick it from a message's *⋯* menu to start from that message.",+ },+ ],+ },+ { type: "divider" },+ ];+}++/** `undefined` hides the incidents section: the feature is off here. */+export async function homeIncidents(+ ctx: ServiceContext,+): Promise<HomeIncident[] | undefined> {+ if (!isFeatureEnabled(ctx.workspace, "incident-management")) return;+ const rows = await listIncidents({+ ctx,+ input: { status: ["open", "mitigated"], limit: 10 },+ });+ return rows.map((row) => ({+ id: row.id,+ title: row.title,+ severity: row.severity,+ status: row.status,+ url: getIncidentDashboardUrl(row.id),+ slackChannelId: row.slackChannelId,+ }));+}+export function buildHomeBlocks(- opts: { reconnectUrl?: string } = {},+ opts: { reconnectUrl?: string; openIncidents?: HomeIncident[] } = {},): KnownBlock[] {const reconnect: KnownBlock[] = opts.reconnectUrl? [@@ -20,32 +114,78 @@ export function buildHomeBlocks({ type: "divider" },]: [];- return [- ...reconnect,+ const incidents = opts.openIncidents;+ const commandBlocks: KnownBlock[] = [{- type: "header",- text: { type: "plain_text", text: "openstatus", emoji: true },+ type: "section",+ text: { type: "mrkdwn", text: "*Slash commands*" },},+ ...(incidents+ ? [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: [+ "*Incidents*",+ "`/openstatus incident declare` Open the declare form",+ "`/openstatus incident list` List open incidents",+ "`/openstatus incident note <text>` Add a note to the timeline",+ "`/openstatus incident mitigate` · `resolve` · `cancel` · `reopen` Change its status",+ "`/openstatus incident postmortem` Draft the postmortem",+ ].join("\n"),+ },+ } satisfies KnownBlock,+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: "Run these in the incident's channel, or add its number from anywhere, e.g. `/openstatus incident resolve #12`.",+ },+ ],+ } satisfies KnownBlock,+ ]+ : []),{type: "section",text: {type: "mrkdwn",- text: "Your incident communication agent. Open *openstatus* from the Slack top bar to chat with it, or mention *@openstatus* in any channel or thread — it drafts status updates from the conversation, and nothing is published until you approve it.",+ text: [+ "*Status page subscriptions*",+ "`/openstatus subscribe <status-page-url>` Post that page's updates in this channel",+ "`/openstatus unsubscribe <status-page-url>` Stop posting them",+ "`/openstatus subscriptions` List this channel's subscriptions",+ ].join("\n"),},},- { type: "divider" },+ ];+ return [+ ...reconnect,{type: "section",text: {type: "mrkdwn",- text: '*Create & update incidents*\nDescribe the issue in the agent pane, or mention `@openstatus` in any channel or thread. It reads the thread, drafts a report, and you click *Approve*, *Approve & Notify*, or *Cancel*. Say _"we found the cause"_ or _"it\'s fixed"_ and it moves the incident to Identified or Resolved.',+ text: incidents+ ? "*Run incidents and keep your status page up to date, without leaving Slack.*"+ : "*Keep your status page up to date, without leaving Slack.*",},},+ { type: "divider" },+ ...(incidents ? incidentBlocks(incidents) : []),+ {+ type: "section",+ text: { type: "mrkdwn", text: "*Update your status page*" },+ },{type: "section",text: {type: "mrkdwn",- text: "*Slash commands*\n• `/openstatus subscribe <status-page-url>` — subscribe this channel to a status page\n• `/openstatus unsubscribe <status-page-url>` — unsubscribe this channel\n• `/openstatus subscriptions` — list this channel's subscriptions\n• `/openstatus help` — show these commands",+ text: [+ "*1.* Mention *@openstatus* in a channel or thread, or open it from the Slack top bar, and describe what's happening.",+ "*2.* It reads the conversation and drafts a status report.",+ "*3.* Click *Approve* to publish it, or *Approve & Notify* to also notify your subscribers.",+ ].join("\n"),},},{@@ -53,7 +193,18 @@ export function buildHomeBlocks(elements: [{type: "mrkdwn",- text: `<${DOCS_URL}|Documentation> · Updates from subscribed status pages appear as threaded messages in the channel.`,+ text: 'Keep replying in the same thread: _"we found the cause"_ moves the report to Identified, _"it\'s fixed"_ to Resolved.',+ },+ ],+ },+ { type: "divider" },+ ...commandBlocks,+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `\`/openstatus help\` lists every command · <${DOCS_URL}|Documentation>`,},],},@@ -63,7 +214,7 @@ export function buildHomeBlocks(export async function publishHomeView(slack: WebClient,userId: string,- opts: { reconnectUrl?: string } = {},+ opts: { reconnectUrl?: string; openIncidents?: HomeIncident[] } = {},): Promise<void> {await slack.views.publish({user_id: userId,diff --git a/apps/server/src/routes/slack/incident-commands.ts b/apps/server/src/routes/slack/incident-commands.tsindex 9559d468c..67b6a3d9b 100644--- a/apps/server/src/routes/slack/incident-commands.ts+++ b/apps/server/src/routes/slack/incident-commands.ts@@ -27,6 +27,7 @@ const logger = getLogger(["api-server", "slack", "incident-commands"]);export const INCIDENT_HELP = ["*Incidents*",+ "• `/openstatus incident declare` — open the declare form (or the *Declare incident* shortcut)","• `/openstatus incident declare <title> [--sev critical|major|minor]` — declare an incident (approval card)","• `/openstatus incident note <text>` — add to the timeline (in an incident channel)","• `/openstatus incident mitigate|resolve|cancel|reopen [#id] [note]` — change its status (approval card)",diff --git a/apps/server/src/routes/slack/incident-modal.ts b/apps/server/src/routes/slack/incident-modal.tsnew file mode 100644index 000000000..729921533--- /dev/null+++ b/apps/server/src/routes/slack/incident-modal.ts@@ -0,0 +1,403 @@+import { getLogger } from "@logtape/logtape";+import {+ isFeatureEnabled,+ type ServiceContext,+ ServiceError,+} from "@openstatus/services";+import { escapeMrkdwn } from "@openstatus/services/incident";+import { type ModalView, WebClient } from "@slack/web-api";+import { z } from "zod";++import { runInBackground } from "./background";+import {+ type Block,+ buildLinkAccountBlocks,+ LINK_ACCOUNT_TEXT,+} from "./blocks";+import type { SlackConfig } from "./config";+import { onIncidentDeclared } from "./incident-slack";+import { getIncidentDashboardUrl } from "./page-urls";+import { executeRegistryAction, getRegistryTool } from "./registry-runner";+import {+ linkAccountUrl,+ planRequiredMessage,+ requireSlackMember,+ type SlackActor,+ slackAgentAllowed,+} from "./require-slack-member";+import { resolveSlackMember } from "./resolve-slack-user";+import { resolveWorkspace, type SlackWorkspace } from "./workspace-resolver";++const logger = getLogger(["api-server", "slack", "incident-modal"]);++const NOT_CONNECTED =+ "openstatus isn't connected to this Slack workspace. Connect it from the openstatus dashboard.";++/** Callback id of the global shortcut, the message shortcut and the modal. */+export const DECLARE_INCIDENT_CALLBACK = "declare_incident";+export const DECLARE_INCIDENT_FROM_MESSAGE_CALLBACK =+ "declare_incident_from_message";++const TITLE_MAX = 256;+// Slack rejects the whole view if a plain_text_input's max_length exceeds 3000.+const SUMMARY_MAX = 3000;+const SEVERITIES = [+ { value: "critical", label: "Critical — major outage or data loss" },+ { value: "major", label: "Major — significant degradation" },+ { value: "minor", label: "Minor — limited impact" },+] as const;++type View = ModalView;++type Prefill = { title?: string; summary?: string };++const privateMetadata = z.object({ channelId: z.string().optional() });++function originChannel(metadata: string | undefined): string | undefined {+ try {+ return privateMetadata.safeParse(JSON.parse(metadata || "{}")).data+ ?.channelId;+ } catch {+ return undefined;+ }+}++function option(value: string, label: string) {+ return { text: { type: "plain_text" as const, text: label }, value };+}++export function buildDeclareIncidentModal(args: {+ slackUserId: string;+ channelId?: string;+ prefill?: Prefill;+}): View {+ const { prefill = {} } = args;+ const major = SEVERITIES[1];+ return {+ type: "modal",+ callback_id: DECLARE_INCIDENT_CALLBACK,+ private_metadata: JSON.stringify({ channelId: args.channelId }),+ title: { type: "plain_text", text: "Declare an incident" },+ submit: { type: "plain_text", text: "Declare" },+ close: { type: "plain_text", text: "Cancel" },+ blocks: [+ {+ type: "input",+ block_id: "title",+ label: { type: "plain_text", text: "Title" },+ element: {+ type: "plain_text_input",+ action_id: "value",+ max_length: TITLE_MAX,+ placeholder: { type: "plain_text", text: "API returning 500s" },+ ...(prefill.title+ ? { initial_value: prefill.title.slice(0, TITLE_MAX) }+ : {}),+ },+ },+ {+ type: "input",+ block_id: "severity",+ label: { type: "plain_text", text: "Severity" },+ element: {+ type: "static_select",+ action_id: "value",+ options: SEVERITIES.map((s) => option(s.value, s.label)),+ initial_option: option(major.value, major.label),+ },+ },+ {+ type: "input",+ block_id: "summary",+ optional: true,+ label: { type: "plain_text", text: "Summary" },+ element: {+ type: "plain_text_input",+ action_id: "value",+ multiline: true,+ max_length: SUMMARY_MAX,+ placeholder: { type: "plain_text", text: "What is happening?" },+ ...(prefill.summary+ ? { initial_value: prefill.summary.slice(0, SUMMARY_MAX) }+ : {}),+ },+ },+ {+ type: "input",+ block_id: "commander",+ optional: true,+ label: { type: "plain_text", text: "Commander" },+ hint: {+ type: "plain_text",+ text: "Leads the response. Defaults to you.",+ },+ element: {+ type: "users_select",+ action_id: "value",+ initial_user: args.slackUserId,+ },+ },+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: "Internal only: nothing is published to your status page.",+ },+ ],+ },+ ],+ };+}++function noticeModal(text: string, blocks?: Block[]): View {+ return {+ type: "modal",+ title: { type: "plain_text", text: "Declare an incident" },+ close: { type: "plain_text", text: "Close" },+ blocks: blocks ?? [{ type: "section", text: { type: "mrkdwn", text } }],+ };+}++type Gate =+ | { ok: true; resolved: SlackWorkspace; actor: SlackActor }+ | { ok: false; view: View; botToken?: string };++/** Everything the modal needs before it can declare; a notice view otherwise. */+async function gate(+ teamId: string,+ slackUserId: string,+ config: SlackConfig,+): Promise<Gate> {+ const resolved = await resolveWorkspace(teamId);+ if (!resolved) {+ return {+ ok: false,+ view: noticeModal(NOT_CONNECTED),+ };+ }+ if (!slackAgentAllowed(resolved.workspace)) {+ return {+ ok: false,+ view: noticeModal(planRequiredMessage(config).text),+ botToken: resolved.botToken,+ };+ }+ if (!isFeatureEnabled(resolved.workspace, "incident-management")) {+ return {+ ok: false,+ view: noticeModal(+ "Incident management isn't available for this workspace yet.",+ ),+ botToken: resolved.botToken,+ };+ }+ const actor = await requireSlackMember({+ workspace: resolved.workspace,+ teamId,+ slackUserId,+ slack: new WebClient(resolved.botToken),+ });+ if (!actor) {+ const url = await linkAccountUrl(config, {+ workspaceId: resolved.workspace.id,+ teamId,+ slackUserId,+ });+ return {+ ok: false,+ view: noticeModal(LINK_ACCOUNT_TEXT, buildLinkAccountBlocks(url)),+ botToken: resolved.botToken,+ };+ }+ return { ok: true, resolved, actor };+}++/**+ * `trigger_id` expires 3s after the user's action. Returns the message to show+ * instead when there is no bot token to open even a notice with.+ */+export async function openDeclareIncidentModal(args: {+ teamId: string;+ slackUserId: string;+ triggerId: string;+ channelId?: string;+ prefill?: Prefill;+ config: SlackConfig;+}): Promise<string | undefined> {+ const { teamId, slackUserId, triggerId, config } = args;+ const checked = await gate(teamId, slackUserId, config);+ if (!checked.ok) {+ if (!checked.botToken) return NOT_CONNECTED;+ await new WebClient(checked.botToken).views.open({+ trigger_id: triggerId,+ view: checked.view,+ });+ return;+ }+ await new WebClient(checked.resolved.botToken).views.open({+ trigger_id: triggerId,+ view: buildDeclareIncidentModal({+ slackUserId,+ channelId: args.channelId,+ prefill: args.prefill,+ }),+ });+}++type StateValues = Record<+ string,+ Record<+ string,+ {+ value?: string | null;+ selected_option?: { value: string } | null;+ selected_user?: string | null;+ }+ >+>;++export type DeclareSubmission = {+ title: string;+ severity: "critical" | "major" | "minor";+ summary?: string;+ commanderSlackUserId?: string;+};++export function parseDeclareSubmission(+ values: StateValues,+): DeclareSubmission | { error: Record<string, string> } {+ const title = values.title?.value?.value?.trim() ?? "";+ if (!title) return { error: { title: "Give the incident a title." } };+ const severity = SEVERITIES.find(+ (s) => s.value === values.severity?.value?.selected_option?.value,+ )?.value;+ if (!severity) return { error: { severity: "Pick a severity." } };+ const summary = values.summary?.value?.value?.trim();+ const commander = values.commander?.value?.selected_user;+ return {+ title,+ severity,+ ...(summary ? { summary } : {}),+ ...(commander ? { commanderSlackUserId: commander } : {}),+ };+}++export type ViewSubmissionPayload = {+ type: "view_submission";+ team?: { id: string };+ user: { id: string; team_id?: string };+ view: {+ callback_id: string;+ private_metadata?: string;+ state: { values: StateValues };+ };+};++export type ViewSubmissionResponse =+ | { response_action: "errors"; errors: Record<string, string> }+ | { response_action: "update"; view: View }+ | null;++/**+ * Declares the incident inside Slack's 3s submission window, so validation+ * errors land on the form; the channel and notifications follow in background.+ */+export async function submitDeclareIncident(+ payload: ViewSubmissionPayload,+ config: SlackConfig,+): Promise<ViewSubmissionResponse> {+ const teamId = payload.team?.id ?? payload.user.team_id;+ if (!teamId) {+ return {+ response_action: "update",+ view: noticeModal("Could not read this request."),+ };+ }+ const slackUserId = payload.user.id;++ const parsed = parseDeclareSubmission(payload.view.state.values);+ if ("error" in parsed) {+ return { response_action: "errors", errors: parsed.error };+ }++ const checked = await gate(teamId, slackUserId, config);+ if (!checked.ok) return { response_action: "update", view: checked.view };+ const { resolved, actor } = checked;+ const slack = new WebClient(resolved.botToken);++ let commanderId = actor.userId;+ if (+ parsed.commanderSlackUserId &&+ parsed.commanderSlackUserId !== slackUserId+ ) {+ const mapped = await resolveSlackMember({+ workspace: resolved.workspace,+ teamId,+ slackUserId: parsed.commanderSlackUserId,+ slack,+ });+ if (mapped === null) {+ return {+ response_action: "errors",+ errors: {+ commander:+ "This person isn't a member of the openstatus workspace, or hasn't linked their account.",+ },+ };+ }+ commanderId = mapped;+ }++ const tool = getRegistryTool("declare_incident");+ if (!tool) throw new Error('slack: "declare_incident" tool missing');+ const ctx: ServiceContext = { workspace: resolved.workspace, actor };+ let incidentId: number;+ try {+ const { output } = await executeRegistryAction({+ tool,+ ctx,+ draftInput: {+ title: parsed.title,+ severity: parsed.severity,+ summary: parsed.summary,+ commanderId,+ },+ flags: {},+ });+ incidentId = (output as { id: number }).id;+ } catch (error) {+ if (error instanceof ServiceError) {+ return { response_action: "errors", errors: { title: error.message } };+ }+ logger.error("slack declare modal failed", { error, teamId });+ return {+ response_action: "errors",+ errors: { title: "Something went wrong. Please try again." },+ };+ }++ const origin = originChannel(payload.view.private_metadata);++ runInBackground(+ "incident-modal-declared",+ async () => {+ const channel = await onIncidentDeclared(ctx, incidentId, config);+ const where =+ channel.status === "bound" || channel.status === "unbound"+ ? ` Join <#${channel.channelId}>.`+ : "";+ const text = `:rotating_light: Declared *${escapeMrkdwn(parsed.title)}* (${parsed.severity}).${where} <${getIncidentDashboardUrl(incidentId)}|Open in openstatus>`;+ if (origin) {+ await slack.chat+ .postEphemeral({ channel: origin, user: slackUserId, text })+ .catch(() => slack.chat.postMessage({ channel: slackUserId, text }));+ return;+ }+ await slack.chat.postMessage({ channel: slackUserId, text });+ },+ { teamId, incidentId },+ );++ return null;+}diff --git a/apps/server/src/routes/slack/incident-slack.ts b/apps/server/src/routes/slack/incident-slack.tsindex 62d1b6006..e220979f3 100644--- a/apps/server/src/routes/slack/incident-slack.ts+++ b/apps/server/src/routes/slack/incident-slack.ts@@ -7,6 +7,7 @@ import {displayName,escapeMrkdwn,getIncident,+ type OpenChannelResult,openIncidentSlackChannel,type SlackClientFactory,} from "@openstatus/services/incident";@@ -93,17 +94,7 @@ export async function afterIncidentTool(args: {const note = incidentInput.safeParse(args.input).data?.note;try {if (toolName === "declare_incident") {- trackSlackIncident(ctx, "declare");- await notifyCommander(ctx, incidentId, config).catch((error) =>- logger.warn("incident commander email failed", { error, incidentId }),- );- const result = await openIncidentSlackChannel({- ctx,- incidentId,- clientFor: slackClientFor,- dashboardUrl: config.dashboardUrl,- });- logger.info("slack incident channel", { incidentId, ...result });+ await onIncidentDeclared(ctx, incidentId, config);return;}if (toolName === "update_incident") {@@ -150,6 +141,26 @@ export async function afterIncidentTool(args: {}}+/** Commander email and the incident channel, after any Slack declare. */+export async function onIncidentDeclared(+ ctx: ServiceContext,+ incidentId: number,+ config: SlackConfig,+): Promise<OpenChannelResult> {+ trackSlackIncident(ctx, "declare");+ await notifyCommander(ctx, incidentId, config).catch((error) =>+ logger.warn("incident commander email failed", { error, incidentId }),+ );+ const result = await openIncidentSlackChannel({+ ctx,+ incidentId,+ clientFor: slackClientFor,+ dashboardUrl: config.dashboardUrl,+ });+ logger.info("slack incident channel", { incidentId, ...result });+ return result;+}+/** A linked status report still open gets a resolve card; never automatic. */async function offerStatusReportResolve(args: {ctx: ServiceContext;diff --git a/apps/server/src/routes/slack/interactions.test.ts b/apps/server/src/routes/slack/interactions.test.tsindex 5432639c0..024890276 100644--- a/apps/server/src/routes/slack/interactions.test.ts+++ b/apps/server/src/routes/slack/interactions.test.ts@@ -629,3 +629,155 @@ describe("link this channel button", () => {}});});++describe("declare incident modal", () => {+ const app = createTestApp();++ beforeEach(() => {+ configureSlackDoubles();+ redisStore.clear();+ });++ function submission(values: Record<string, unknown>, metadata = "{}") {+ return {+ type: "view_submission",+ team: { id: "T_KNOWN" },+ user: { id: "U_OWNER" },+ view: {+ callback_id: "declare_incident",+ private_metadata: metadata,+ state: { values },+ },+ };+ }++ test("the global shortcut opens the form", async () => {+ const res = await signAndPost(app, {+ type: "shortcut",+ callback_id: "declare_incident",+ trigger_id: "trig-1",+ team: { id: "T_KNOWN" },+ user: { id: "U_OWNER" },+ });+ expect(res.status).toBe(200);+ const open = slackTestState.calls.find((c) => c.method === "views.open");+ expect(open).toBeDefined();+ expect(open?.args.trigger_id).toBe("trig-1");+ const view = open?.args.view as Record<string, unknown>;+ expect(view.callback_id).toBe("declare_incident");+ expect(JSON.stringify(view.blocks)).toContain('"initial_user":"U_OWNER"');+ });++ test("the message shortcut prefills the summary", async () => {+ await signAndPost(app, {+ type: "message_action",+ callback_id: "declare_incident_from_message",+ trigger_id: "trig-2",+ team: { id: "T_KNOWN" },+ user: { id: "U_OWNER" },+ channel: { id: "C_ORIGIN" },+ message: { text: "checkout is throwing 500s" },+ });+ const open = slackTestState.calls.find((c) => c.method === "views.open");+ expect(open).toBeDefined();+ const view = open?.args.view as Record<string, unknown>;+ expect(view.private_metadata).toBe(+ JSON.stringify({ channelId: "C_ORIGIN" }),+ );+ expect(JSON.stringify(view.blocks)).toContain("checkout is throwing 500s");+ });++ test("an unlinked user gets the link card instead of the form", async () => {+ slackTestState.usersInfoImpl = () =>+ Promise.resolve({ ok: true, user: { profile: {} } });+ await signAndPost(app, {+ type: "shortcut",+ callback_id: "declare_incident",+ trigger_id: "trig-3",+ team: { id: "T_KNOWN" },+ user: { id: "U_STRANGER" },+ });+ const open = slackTestState.calls.find((c) => c.method === "views.open");+ expect(open).toBeDefined();+ const view = open?.args.view as Record<string, unknown>;+ expect(view.callback_id).toBeUndefined();+ expect(JSON.stringify(view.blocks)).toContain("Link account");+ });++ test("the home tab button opens the form", async () => {+ await signAndPost(app, {+ type: "block_actions",+ trigger_id: "trig-home",+ team: { id: "T_KNOWN" },+ user: { id: "U_OWNER" },+ actions: [{ action_id: "open_declare_incident" }],+ });+ const open = slackTestState.calls.find((c) => c.method === "views.open");+ expect(open).toBeDefined();+ expect(open?.args.trigger_id).toBe("trig-home");+ const view = open?.args.view as { callback_id?: string };+ expect(view.callback_id).toBe("declare_incident");+ });++ test("a blank title is rejected on the form", async () => {+ const res = await signAndPost(+ app,+ submission({+ title: { value: { value: " " } },+ severity: { value: { selected_option: { value: "major" } } },+ }),+ );+ expect(await res.json()).toEqual({+ response_action: "errors",+ errors: { title: "Give the incident a title." },+ });+ });++ test("submitting declares the incident and closes the form", async () => {+ const title = `Modal ${crypto.randomUUID()}`;+ const res = await signAndPost(+ app,+ submission(+ {+ title: { value: { value: title } },+ severity: { value: { selected_option: { value: "critical" } } },+ summary: { value: { value: "Checkout is down" } },+ commander: { value: { selected_user: "U_OWNER" } },+ },+ JSON.stringify({ channelId: "C_ORIGIN" }),+ ),+ );+ expect(res.status).toBe(200);+ expect(await res.text()).toBe("");+ const row = await db+ .select()+ .from(incident)+ .where(eq(incident.title, title))+ .get();+ try {+ expect(row?.severity).toBe("critical");+ expect(row?.summary).toBe("Checkout is down");+ expect(row?.workspaceId).toBe(1);+ const ephemeral = slackTestState.calls.find(+ (c) => c.method === "postEphemeral",+ );+ expect(ephemeral?.args.channel).toBe("C_ORIGIN");+ expect(String(ephemeral?.args.text)).toContain(title);+ } finally {+ if (row) {+ await db+ .delete(auditLog)+ .where(+ and(+ eq(auditLog.entityType, "incident"),+ eq(auditLog.entityId, String(row.id)),+ ),+ );+ await db+ .delete(incidentEvent)+ .where(eq(incidentEvent.incidentId, row.id));+ await db.delete(incident).where(eq(incident.id, row.id));+ }+ }+ });+});diff --git a/apps/server/src/routes/slack/interactions.ts b/apps/server/src/routes/slack/interactions.tsindex b5f29e20b..dae249a4c 100644--- a/apps/server/src/routes/slack/interactions.ts+++ b/apps/server/src/routes/slack/interactions.ts@@ -13,6 +13,15 @@ import {import type { SlackConfig, SlackEnv } from "./config";import { consume, get } from "./confirmation-store";import type { PendingAction } from "./confirmation-store";+import { OPEN_DECLARE_INCIDENT_ACTION } from "./home";+import {+ DECLARE_INCIDENT_CALLBACK,+ DECLARE_INCIDENT_FROM_MESSAGE_CALLBACK,+ openDeclareIncidentModal,+ submitDeclareIncident,+ type ViewSubmissionPayload,+ type ViewSubmissionResponse,+} from "./incident-modal";import {afterIncidentTool,bindChannelFromButton,@@ -60,10 +69,77 @@ async function processIncidentBind(payload: SlackInteractionPayload) {});}-export function handleSlackInteraction(c: Context<SlackEnv>) {- const payload = c.get("slackBody") as SlackInteractionPayload;+interface SlackShortcutPayload {+ type: "shortcut" | "message_action" | "block_actions";+ callback_id: string;+ trigger_id: string;+ user?: { id: string; team_id?: string };+ team?: { id: string };+ channel?: { id: string };+ message?: { text?: string };+}++async function handleShortcut(+ c: Context<SlackEnv>,+ payload: SlackShortcutPayload,+) {+ const teamId = payload.team?.id ?? payload.user?.team_id;+ if (+ !teamId ||+ !payload.user?.id ||+ (payload.callback_id !== DECLARE_INCIDENT_CALLBACK &&+ payload.callback_id !== DECLARE_INCIDENT_FROM_MESSAGE_CALLBACK)+ ) {+ return c.body(null, 200);+ }+ // Awaited, not backgrounded: `trigger_id` dies with the 3s ack window.+ await openDeclareIncidentModal({+ teamId,+ slackUserId: payload.user.id,+ triggerId: payload.trigger_id,+ channelId: payload.channel?.id,+ prefill:+ payload.type === "message_action" && payload.message?.text+ ? { summary: payload.message.text }+ : undefined,+ config: c.get("slackConfig"),+ }).catch((error) =>+ logger.error("slack declare modal open failed", { error, teamId }),+ );+ return c.body(null, 200);+}++export async function handleSlackInteraction(c: Context<SlackEnv>) {+ const body = c.get("slackBody") as { type?: string };const config = c.get("slackConfig");+ if (body.type === "shortcut" || body.type === "message_action") {+ return handleShortcut(c, body as SlackShortcutPayload);+ }+ if (body.type === "view_submission") {+ const submission = body as ViewSubmissionPayload;+ if (submission.view?.callback_id !== DECLARE_INCIDENT_CALLBACK) {+ return c.body(null, 200);+ }+ const response = await submitDeclareIncident(submission, config).catch(+ (error): ViewSubmissionResponse => {+ logger.error("slack declare modal submit failed", { error });+ return {+ response_action: "errors",+ errors: { title: "Something went wrong. Please try again." },+ };+ },+ );+ return response ? c.json(response) : c.body(null, 200);+ }++ const payload = body as SlackInteractionPayload;+ if (payload.actions?.[0]?.action_id === OPEN_DECLARE_INCIDENT_ACTION) {+ return handleShortcut(c, {+ ...(body as SlackShortcutPayload),+ callback_id: DECLARE_INCIDENT_CALLBACK,+ });+ }if (payload.type !== "block_actions" || !payload.actions?.length) {return c.json({ ok: true });}diff --git a/apps/server/src/routes/slack/system-prompt.test.ts b/apps/server/src/routes/slack/system-prompt.test.tsindex 246836a54..fb3f29d59 100644--- a/apps/server/src/routes/slack/system-prompt.test.ts+++ b/apps/server/src/routes/slack/system-prompt.test.ts@@ -54,6 +54,12 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("call list_notifications FIRST");});+ test("asks for short, direct replies", () => {+ const prompt = buildSystemPrompt("Acme Corp");+ expect(prompt).toContain("REPLY STYLE");+ expect(prompt).toContain("Lead with the answer");+ });+test("tells the model not to show internal ids", () => {expect(buildSystemPrompt("Acme Corp")).toContain("NEVER show internal ids");});diff --git a/apps/server/src/routes/slack/system-prompt.ts b/apps/server/src/routes/slack/system-prompt.tsindex b8b51c97a..4c2583ea4 100644--- a/apps/server/src/routes/slack/system-prompt.ts+++ b/apps/server/src/routes/slack/system-prompt.ts@@ -25,13 +25,20 @@ export function buildSystemPrompt(// move the timestamp to the first user message so the rest of the// system prompt can cache.const now = new Date().toISOString();- return `You are the OpenStatus assistant for workspace "${workspaceName}".+ return `You are the openstatus assistant for workspace "${workspaceName}".The current date and time is: ${now} (UTC).You help teams through Slack with three kinds of work:- Incident communication: create and manage status reports and maintenance windows on their status pages.- SRE / on-call questions ("what's broken right now?", "is the checkout monitor healthy?") answered from monitors, response logs, notification channels, private locations, and audit logs.- Product / how-to questions about openstatus itself, answered from the official docs.+REPLY STYLE — this is Slack, not a document. Be brief and direct.+- Lead with the answer or the outcome. The first sentence must be useful on its own.+- Default to 1-3 short sentences. Use a bullet list only for several items (monitors, reports, regions), one line each. No headings, no tables.+- No filler: don't restate the request, don't narrate tool calls ("Let me check…", "I'll look that up"), no "Great question", no closing offers ("Let me know if…", "Anything else?").+- After a write call, one short line pointing at the card (e.g. "Draft ready 👇"). Don't repeat what the card already shows, and don't explain how approval works unless asked.+- Include only the details that answer the question. Skip caveats and background nobody asked for.+HOW APPROVAL WORKS HERE — read this before any write tool:Calling a write tool (create_status_report, add_status_report_update, update_status_report, resolve_status_report, create_maintenance) does NOT execute it. It renders an approval card in Slack with Approve/Cancel buttons, and nothing is created, published, or notified until the user clicks Approve. The card IS how you ask.- Call the tool as soon as you have the ids it needs. That is the ONLY way the user gets a card.@@ -96,11 +103,11 @@ Guidelines:"we found the root cause" -> identified"we're watching it" -> monitoring"it's fixed" -> resolved-- Draft professional status page updates. Don't repeat the user verbatim.+- Draft professional status page updates: short and factual — what's affected, the impact, and what happens next, in 1-3 sentences. Don't repeat the user verbatim, and don't speculate about causes.- When tagged in a channel thread, synthesize the full thread into a status report draft.- In a direct conversation (the agent pane), the user is talking to you directly — answer their request; there is no channel discussion to summarize.- Status progression: investigating -> identified -> monitoring -> resolved-- Be concise. Use Slack mrkdwn formatting (*bold*, _italic_).+- Use Slack mrkdwn formatting (*bold*, _italic_) sparingly.- NEVER show internal ids (page, component, report, maintenance, monitor ids) in your replies — they mean nothing to the reader. Refer to things by name; when two share a name, tell them apart by slug, URL, or another visible detail. Ids are only for tool calls.- Every mutation goes through a tool call — see "HOW APPROVAL WORKS HERE" above. A drafted change you did not call a tool for is a change the user cannot approve.@@ -113,7 +120,7 @@ Monitor diagnostics:Docs and product questions:- For questions about how openstatus works (features, configuration, CLI, API, plans), call search_docs BEFORE answering — never answer product questions from memory.- Search with keyword queries. If the first search misses, retry once with different terms or type: "guides". "When did X ship?" -> type: "changelog".-- Read the best 1-2 hits with get_doc_page, ground your answer in that content, and ALWAYS cite the page URL(s) as links.+- Read the best 1-2 hits with get_doc_page, ground your answer in that content, and ALWAYS cite the page URL(s) as links. Answer in a sentence or two plus the link; don't paste the docs back.- Pricing, plan fit, comparisons with other tools, use cases, customer stories, blog posts -> search_content, then get_content_page on the best hits.- If nothing relevant is found, say so plainly instead of guessing.- Don't use search_docs or search_content for workspace data — the list/get tools are the source of truth there.diff --git a/packages/services/src/incident/__tests__/slack-flow.test.ts b/packages/services/src/incident/__tests__/slack-flow.test.tsindex f23ec042e..2ab5f30b5 100644--- a/packages/services/src/incident/__tests__/slack-flow.test.ts+++ b/packages/services/src/incident/__tests__/slack-flow.test.ts@@ -1,4 +1,5 @@-import { integration } from "@openstatus/db/src/schema";+import { db, eq } from "@openstatus/db";+import { integration, user } from "@openstatus/db/src/schema";import {addUserToWorkspace,createUser,@@ -86,12 +87,19 @@ function fakeSlack(let workspace: Workspace;let ownerId: number;+let ownerEmail: string;let memberEmail: string;beforeAll(async () => {const fixture = await createWorkspaceFixture("team");workspace = fixture.workspace;ownerId = fixture.userId;+ const owner = await db+ .select({ email: user.email })+ .from(user)+ .where(eq(user.id, ownerId))+ .get();+ ownerEmail = owner?.email as string;const member = await createUser();memberEmail = member.email as string;await addUserToWorkspace(member.id, workspace.id, "member");@@ -134,7 +142,7 @@ describe("incidentChannelName", () => {});describe("openIncidentSlackChannel", () => {- test("creates, links members by email, invites, pins and binds", async () => {+ test("creates, invites only the declarer, pins and binds", async () => {await withTestTransaction(async (tx) => {await connectSlack(tx, "T_FLOW", SLACK_BOT_SCOPES.join(","));const ctx = ctxFor(tx);@@ -145,7 +153,7 @@ describe("openIncidentSlackChannel", () => {const name = incidentChannelName(inc);const { client, calls } = fakeSlack({takenNames: [name],- emails: { [memberEmail]: "U_MEMBER" },+ emails: { [ownerEmail]: "U_OWNER", [memberEmail]: "U_MEMBER" },});const result = await openIncidentSlackChannel({@@ -158,8 +166,8 @@ describe("openIncidentSlackChannel", () => {expect(result).toEqual({ status: "bound", channelId: "C_NEW" });const creates = calls.filter((c) => c.method === "create");expect(creates.map((c) => c.args.name)).toEqual([name, `${name}-2`]);- const invite = calls.find((c) => c.method === "invite");- expect(String(invite?.args.users)).toContain("U_MEMBER");+ const invites = calls.filter((c) => c.method === "invite");+ expect(invites.map((c) => c.args.users)).toEqual(["U_OWNER"]);expect(calls.some((c) => c.method === "pins.add")).toBe(true);const bound = await getIncident({ ctx, input: { id: inc.id } });@@ -170,6 +178,39 @@ describe("openIncidentSlackChannel", () => {});});+ test("declared from Slack, invites the clicking user without a lookup", async () => {+ await withTestTransaction(async (tx) => {+ await connectSlack(tx, "T_SLACK", SLACK_BOT_SCOPES.join(","));+ const ctx: ServiceContext = {+ ...ctxFor(tx),+ actor: {+ type: "slack",+ teamId: "T_SLACK",+ slackUserId: "U_CLICKER",+ userId: ownerId,+ },+ };+ const inc = await declareIncident({+ ctx,+ input: { title: "Search slow", severity: "minor" },+ });+ const { client, calls } = fakeSlack({+ emails: { [memberEmail]: "U_MEMBER" },+ });++ await openIncidentSlackChannel({+ ctx,+ incidentId: inc.id,+ clientFor: () => client,+ dashboardUrl: "https://app.test",+ });++ const invites = calls.filter((c) => c.method === "invite");+ expect(invites.map((c) => c.args.users)).toEqual(["U_CLICKER"]);+ expect(calls.some((c) => c.method === "lookupByEmail")).toBe(false);+ });+ });+test("skips an install that is missing scopes", async () => {await withTestTransaction(async (tx) => {await connectSlack(tx, "T_OLD", "chat:write");diff --git a/packages/services/src/incident/slack-flow.ts b/packages/services/src/incident/slack-flow.tsindex 78129d122..51a3ad66d 100644--- a/packages/services/src/incident/slack-flow.ts+++ b/packages/services/src/incident/slack-flow.ts@@ -1,10 +1,5 @@import { and, eq, isNull } from "@openstatus/db";-import {- type Incident,- slackUser,- user,- usersToWorkspaces,-} from "@openstatus/db/src/schema";+import { type Incident, slackUser, user } from "@openstatus/db/src/schema";import { type ServiceContext, getReadDb } from "../context";import { isFeatureEnabled } from "../features";@@ -137,56 +132,57 @@ export async function incidentSlackReady(return connection;}-/** Link every member whose openstatus email has a Slack account in the team. */-async function autoMapMembers(+/**+ * The Slack user who declared the incident: the clicking user when declared+ * from Slack, else the declarer's linked Slack account, else one found by+ * their openstatus email (and linked for next time).+ */+async function resolveDeclarerSlackId(ctx: ServiceContext,client: SlackIncidentClient,teamId: string,-): Promise<string[]> {+ declaredBy: number | null,+): Promise<string | undefined> {+ if (ctx.actor.type === "slack" && ctx.actor.teamId === teamId) {+ return ctx.actor.slackUserId;+ }+ if (declaredBy === null) return undefined;const db = getReadDb(ctx);- const members = await db- .select({ id: user.id, email: user.email })- .from(usersToWorkspaces)- .innerJoin(user, eq(user.id, usersToWorkspaces.userId))- .where(- and(- eq(usersToWorkspaces.workspaceId, ctx.workspace.id),- isNull(user.deletedAt),- ),- )- .all();const linked = await db- .select({ userId: slackUser.userId, slackUserId: slackUser.slackUserId })+ .select({ slackUserId: slackUser.slackUserId }).from(slackUser).where(and(eq(slackUser.workspaceId, ctx.workspace.id),eq(slackUser.slackTeamId, teamId),+ eq(slackUser.userId, declaredBy),),)- .all();- const slackIds = new Map(linked.map((l) => [l.userId, l.slackUserId]));- const system: ServiceContext = {- ...ctx,- actor: { type: "system", job: "slack-incident-channel" },- };+ .get();+ if (linked) return linked.slackUserId;- for (const member of members) {- if (slackIds.has(member.id) || !member.email) continue;- try {- const res = await client.users.lookupByEmail({ email: member.email });- const slackUserId = res.user?.id;- if (!slackUserId) continue;- await createSlackUserMapping({- ctx: system,- input: { teamId, slackUserId, userId: member.id },- });- slackIds.set(member.id, slackUserId);- } catch {- // users_not_found: no Slack account with this email.- }+ const declarer = await db+ .select({ email: user.email })+ .from(user)+ .where(and(eq(user.id, declaredBy), isNull(user.deletedAt)))+ .get();+ if (!declarer?.email) return undefined;+ try {+ const res = await client.users.lookupByEmail({ email: declarer.email });+ const slackUserId = res.user?.id;+ if (!slackUserId) return undefined;+ await createSlackUserMapping({+ ctx: {+ ...ctx,+ actor: { type: "system", job: "slack-incident-channel" },+ },+ input: { teamId, slackUserId, userId: declaredBy },+ });+ return slackUserId;+ } catch {+ // users_not_found: no Slack account with this email.+ return undefined;}- return [...slackIds.values()];}export type OpenChannelResult =@@ -198,7 +194,7 @@ export type OpenChannelResult =/*** Creates the incident's channel after the declare has committed: a Slack* failure never loses the incident. Order: create (retrying `name_taken`),- * link members by email, invite everyone linked, topic, pinned header card,+ * invite the declarer (others join themselves), topic, pinned header card,* bind. If binding fails twice the channel gets a "link this channel" card.*/export async function openIncidentSlackChannel(args: {@@ -236,15 +232,15 @@ export async function openIncidentSlackChannel(args: {if (!channelId) return { status: "failed", error: "name_taken" };try {- const slackUserIds = await autoMapMembers(ctx, client, connection.teamId);- const invitees = slackUserIds.filter((id) => id !== connection.botUserId);- for (let i = 0; i < invitees.length; i += 1000) {+ const declarer = await resolveDeclarerSlackId(+ ctx,+ client,+ connection.teamId,+ incident.declaredBy,+ );+ if (declarer && declarer !== connection.botUserId) {await client.conversations- .invite({- channel: channelId,- users: invitees.slice(i, i + 1000).join(","),- force: true,- })+ .invite({ channel: channelId, users: declarer, force: true }).catch(() => undefined);}await client.conversations