Skip to content

Open-source status page, incident response and uptime monitoring

dashboard: incident detail page (#2798)

Thibault Le Ouaybe854f648218
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
new file mode 100644
index 000000000..bd2022e83
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
@@ -0,0 +1,137 @@
+"use client";
+
+import type { IncidentStatus } from "@openstatus/db/src/schema/incidents/constants";
+import { Badge } from "@openstatus/ui/components/ui/badge";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@openstatus/ui/components/ui/tabs";
+import { useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+
+import {
+ EmptyStateContainer,
+ EmptyStateTitle,
+} from "@/components/content/empty-state";
+import {
+ Section,
+ SectionDescription,
+ SectionGroup,
+ SectionHeader,
+ SectionTitle,
+} from "@/components/content/section";
+import { IncidentComposer } from "@/components/incidents/incident-composer";
+import { IncidentProperties } from "@/components/incidents/incident-properties";
+import { IncidentStatusReport } from "@/components/incidents/incident-status-report";
+import { IncidentTimeline } from "@/components/incidents/incident-timeline";
+import { ResolveReportDialog } from "@/components/incidents/resolve-report-dialog";
+import { severityConfig } from "@/data/managed-incidents.client";
+import { useFeature } from "@/hooks/use-feature";
+import { useTRPC } from "@/lib/trpc/client";
+import { cn } from "@/lib/utils";
+
+export function Client({ id }: { id: number }) {
+ const trpc = useTRPC();
+ const enabled = useFeature("incident-management");
+ const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
+ const { data: incident, isError } = useQuery({
+ ...trpc.incident.get.queryOptions({ id }),
+ enabled,
+ retry: false,
+ });
+ const { data: events } = useQuery({
+ ...trpc.incident.listEvents.queryOptions({ id }),
+ enabled,
+ });
+ const [followUp, setFollowUp] = useState<{ note: string } | null>(null);
+
+ if (isError) {
+ return (
+ <SectionGroup>
+ <EmptyStateContainer>
+ <EmptyStateTitle>Incident not found</EmptyStateTitle>
+ </EmptyStateContainer>
+ </SectionGroup>
+ );
+ }
+ if (!incident) return null;
+
+ const canNotify = workspace?.limits["status-subscribers"] === true;
+ const report = incident.statusReport;
+ const onStatusChanged = (status: IncidentStatus, note: string) => {
+ if (
+ (status === "resolved" || status === "canceled") &&
+ report &&
+ report.status !== "resolved"
+ ) {
+ setFollowUp({
+ note:
+ note ||
+ (status === "resolved"
+ ? "This incident has been resolved."
+ : "This was a false alarm. Everything is operating normally."),
+ });
+ }
+ };
+
+ return (
+ <SectionGroup>
+ <Section>
+ <SectionHeader>
+ <SectionTitle className="flex items-center gap-2">
+ {incident.title}
+ <Badge
+ variant="outline"
+ className={cn(
+ "font-mono",
+ severityConfig[incident.severity].className,
+ )}
+ >
+ {severityConfig[incident.severity].label}
+ </Badge>
+ </SectionTitle>
+ {incident.summary ? (
+ <SectionDescription>{incident.summary}</SectionDescription>
+ ) : null}
+ </SectionHeader>
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
+ <Tabs defaultValue="timeline" className="min-w-0">
+ <TabsList>
+ <TabsTrigger value="timeline">Timeline</TabsTrigger>
+ </TabsList>
+ <TabsContent value="timeline" className="grid gap-6">
+ {incident.closedAt === null ? (
+ <IncidentComposer
+ incident={incident}
+ onStatusChanged={onStatusChanged}
+ />
+ ) : null}
+ <IncidentTimeline events={events ?? []} />
+ </TabsContent>
+ </Tabs>
+ <aside className="grid content-start gap-6">
+ <IncidentProperties incident={incident} />
+ <div className="grid gap-2 border-t pt-4">
+ <h3 className="text-sm font-medium">Status report</h3>
+ <IncidentStatusReport incident={incident} canNotify={canNotify} />
+ </div>
+ </aside>
+ </div>
+ </Section>
+ {report ? (
+ <ResolveReportDialog
+ incidentId={incident.id}
+ report={report}
+ canNotify={canNotify}
+ defaultMessage={followUp?.note ?? ""}
+ open={followUp !== null}
+ onOpenChange={(open) => {
+ if (!open) setFollowUp(null);
+ }}
+ />
+ ) : null}
+ </SectionGroup>
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/[id]/page.tsx b/apps/dashboard/src/app/(dashboard)/incidents/[id]/page.tsx
new file mode 100644
index 000000000..8c4ec5c03
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/incidents/[id]/page.tsx
@@ -0,0 +1,14 @@
+import { notFound } from "next/navigation";
+
+import { Client } from "./client";
+
+export default async function Page({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ const incidentId = Number(id);
+ if (!Number.isInteger(incidentId)) return notFound();
+ return <Client id={incidentId} />;
+}
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/breadcrumb.tsx b/apps/dashboard/src/app/(dashboard)/incidents/breadcrumb.tsx
index dfe54d300..9043b39b2 100644
--- a/apps/dashboard/src/app/(dashboard)/incidents/breadcrumb.tsx
+++ b/apps/dashboard/src/app/(dashboard)/incidents/breadcrumb.tsx
@@ -1,13 +1,40 @@
"use client";
import { Incident } from "@openstatus/icons";
+import { useQuery } from "@tanstack/react-query";
+import { useParams } from "next/navigation";
import { NavBreadcrumb } from "@/components/nav/nav-breadcrumb";
+import { useTRPC } from "@/lib/trpc/client";
export function Breadcrumb() {
+ const trpc = useTRPC();
+ const params = useParams<{ id?: string }>();
+ const id = params.id ? Number(params.id) : null;
+ const { data: incident } = useQuery({
+ ...trpc.incident.get.queryOptions({ id: id ?? 0 }),
+ enabled: id !== null,
+ retry: false,
+ });
+
+ if (id === null) {
+ return (
+ <NavBreadcrumb
+ items={[{ type: "page", label: "Incidents", icon: Incident }]}
+ />
+ );
+ }
return (
<NavBreadcrumb
- items={[{ type: "page", label: "Incidents", icon: Incident }]}
+ items={[
+ {
+ type: "link",
+ label: "Incidents",
+ icon: Incident,
+ href: "/incidents",
+ },
+ { type: "page", label: incident?.title ?? `Incident #${id}` },
+ ]}
/>
);
}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/page.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/page.tsx
index d5ac7ada5..697a294cc 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/page.tsx
@@ -6,6 +6,7 @@ import { Button } from "@openstatus/ui/components/ui/button";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useParams } from "next/navigation";
+import { Link } from "@/components/common/link";
import {
EmptyStateContainer,
EmptyStateDescription,
@@ -32,6 +33,7 @@ import {
impactsEqual,
toCreateStatusReportUpdateInput,
} from "@/data/status-report-updates.client";
+import { useFeature } from "@/hooks/use-feature";
import { useTRPC } from "@/lib/trpc/client";
export default function Page() {
@@ -43,6 +45,14 @@ export default function Page() {
trpc.statusReport.get.queryOptions({ id: Number.parseInt(reportId) }),
);
+ const incidentsEnabled = useFeature("incident-management");
+ const { data: linkedIncident } = useQuery({
+ ...trpc.incident.forStatusReport.queryOptions({
+ statusReportId: Number.parseInt(reportId),
+ }),
+ enabled: incidentsEnabled,
+ });
+
const sendStatusReportUpdateMutation = useMutation(
trpc.subscriberNotification.statusReport.mutationOptions(),
);
@@ -97,6 +107,16 @@ export default function Page() {
{affected ? affected : "zero"}
</span>{" "}
component(s).
+ {linkedIncident ? (
+ <>
+ {" "}
+ Communicates incident{" "}
+ <Link href={`/incidents/${linkedIncident.id}`}>
+ {linkedIncident.title}
+ </Link>
+ .
+ </>
+ ) : null}
</SectionDescription>
</SectionHeader>
</SectionHeaderRow>
diff --git a/apps/dashboard/src/components/incidents/incident-composer.tsx b/apps/dashboard/src/components/incidents/incident-composer.tsx
new file mode 100644
index 000000000..fde76f1e7
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/incident-composer.tsx
@@ -0,0 +1,146 @@
+"use client";
+
+import type { IncidentStatus } from "@openstatus/db/src/schema/incidents/constants";
+import { Button } from "@openstatus/ui/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@openstatus/ui/components/ui/select";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@openstatus/ui/components/ui/tabs";
+import { Textarea } from "@openstatus/ui/components/ui/textarea";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { isTRPCClientError } from "@trpc/client";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { ProcessMessage } from "@/components/content/process-message";
+import { statusConfig } from "@/data/managed-incidents.client";
+import { useTRPC } from "@/lib/trpc/client";
+
+const UNCHANGED = "unchanged";
+
+/**
+ * Posting with the status unchanged adds a note; picking a new status moves
+ * the incident and carries the text on the same timeline event.
+ */
+export function IncidentComposer({
+ incident,
+ onStatusChanged,
+}: {
+ incident: {
+ id: number;
+ status: IncidentStatus;
+ allowedTransitions: ReadonlyArray<IncidentStatus>;
+ };
+ onStatusChanged: (status: IncidentStatus, note: string) => void;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [status, setStatus] = useState<string>(UNCHANGED);
+ const [message, setMessage] = useState("");
+
+ const invalidate = () =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey({ id: incident.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.listEvents.queryKey({ id: incident.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.list.queryKey(),
+ }),
+ ]);
+
+ const addNote = useMutation(
+ trpc.incident.addNote.mutationOptions({ onSuccess: invalidate }),
+ );
+ const setIncidentStatus = useMutation(
+ trpc.incident.setStatus.mutationOptions({ onSuccess: invalidate }),
+ );
+ const pending = addNote.isPending || setIncidentStatus.isPending;
+ const next = incident.allowedTransitions.find((s) => s === status);
+
+ async function submit() {
+ const note = message.trim();
+ const promise: Promise<void> = next
+ ? setIncidentStatus
+ .mutateAsync({
+ id: incident.id,
+ status: next,
+ note: note || undefined,
+ })
+ .then(() => undefined)
+ : addNote
+ .mutateAsync({ id: incident.id, message: note })
+ .then(() => undefined);
+ toast.promise(promise, {
+ loading: "Posting...",
+ success: "Posted",
+ error: (error) =>
+ isTRPCClientError(error) ? error.message : "Failed to post",
+ });
+ await promise;
+ setMessage("");
+ setStatus(UNCHANGED);
+ if (next) onStatusChanged(next, note);
+ }
+
+ const disabled = pending || (!next && !message.trim());
+
+ return (
+ <div className="bg-background grid gap-2 rounded-lg border p-3">
+ <Tabs defaultValue="write">
+ <div className="flex items-center justify-between gap-2">
+ <TabsList>
+ <TabsTrigger value="write">Write</TabsTrigger>
+ <TabsTrigger value="preview">Preview</TabsTrigger>
+ </TabsList>
+ <Select value={status} onValueChange={setStatus}>
+ <SelectTrigger size="sm" className="w-[180px] font-mono">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={UNCHANGED}>
+ {statusConfig[incident.status].label} (unchanged)
+ </SelectItem>
+ {incident.allowedTransitions.map((s) => (
+ <SelectItem key={s} value={s}>
+ Mark {statusConfig[s].label.toLowerCase()}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <TabsContent value="write">
+ <Textarea
+ rows={4}
+ placeholder="What's happening? Markdown supported."
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ />
+ </TabsContent>
+ <TabsContent value="preview">
+ <div className="prose dark:prose-invert prose-sm min-h-24 rounded-md border px-3 py-2">
+ <ProcessMessage value={message || "_Nothing to preview._"} />
+ </div>
+ </TabsContent>
+ </Tabs>
+ <div className="flex justify-end">
+ <Button size="sm" disabled={disabled} onClick={() => submit()}>
+ {next
+ ? `Post and mark ${statusConfig[next].label.toLowerCase()}`
+ : "Post note"}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/incident-properties.tsx b/apps/dashboard/src/components/incidents/incident-properties.tsx
new file mode 100644
index 000000000..75d0d4ad0
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/incident-properties.tsx
@@ -0,0 +1,229 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { incidentSeverity } from "@openstatus/db/src/schema/incidents/constants";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { Input } from "@openstatus/ui/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@openstatus/ui/components/ui/select";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { isTRPCClientError } from "@trpc/client";
+import { formatDistanceStrict } from "date-fns";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { Link } from "@/components/common/link";
+import { FormAlertDialog } from "@/components/forms/form-alert-dialog";
+import { toLocalInput } from "@/components/forms/incident/form";
+import {
+ personName,
+ severityConfig,
+ statusConfig,
+} from "@/data/managed-incidents.client";
+import { useTRPC } from "@/lib/trpc/client";
+
+type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
+
+const NONE = "none";
+
+function Row({
+ label,
+ children,
+}: {
+ label: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="grid grid-cols-[110px_1fr] items-center gap-2 text-sm">
+ <span className="text-muted-foreground">{label}</span>
+ <div className="min-w-0">{children}</div>
+ </div>
+ );
+}
+
+export function slackChannelUrl(teamId: string, channelId: string): string {
+ return `https://slack.com/app_redirect?team=${teamId}&channel=${channelId}`;
+}
+
+export function IncidentProperties({ incident }: { incident: Incident }) {
+ const trpc = useTRPC();
+ const router = useRouter();
+ const queryClient = useQueryClient();
+ const { data: members } = useQuery(trpc.member.list.queryOptions());
+ const [startedAt, setStartedAt] = useState(toLocalInput(incident.startedAt));
+ const closed = incident.closedAt !== null;
+
+ const refresh = () =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey({ id: incident.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.listEvents.queryKey({ id: incident.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.list.queryKey(),
+ }),
+ ]);
+ const onError = (error: { message: string }) => {
+ toast.error(isTRPCClientError(error) ? error.message : "Failed to save");
+ };
+
+ const update = useMutation(
+ trpc.incident.update.mutationOptions({ onSuccess: refresh, onError }),
+ );
+ const close = useMutation(
+ trpc.incident.close.mutationOptions({ onSuccess: refresh, onError }),
+ );
+ const remove = useMutation(
+ trpc.incident.delete.mutationOptions({
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: trpc.incident.list.queryKey(),
+ });
+ router.push("/incidents");
+ },
+ }),
+ );
+
+ const end =
+ incident.status === "resolved" && incident.resolvedAt
+ ? incident.resolvedAt
+ : (incident.closedAt ?? new Date());
+
+ return (
+ <div className="grid gap-3">
+ <Row label="Severity">
+ <Select
+ disabled={closed}
+ value={incident.severity}
+ onValueChange={(value) => {
+ const severity = incidentSeverity.find((s) => s === value);
+ if (severity) update.mutate({ id: incident.id, severity });
+ }}
+ >
+ <SelectTrigger size="sm" className="w-full font-mono">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {incidentSeverity.map((severity) => (
+ <SelectItem key={severity} value={severity}>
+ {severityConfig[severity].label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Row>
+ <Row label="Status">
+ <span
+ className={`font-mono ${statusConfig[incident.status].className}`}
+ >
+ {statusConfig[incident.status].label}
+ {closed && incident.status !== "canceled" ? " · closed" : null}
+ </span>
+ </Row>
+ <Row label="Commander">
+ <Select
+ disabled={closed}
+ value={incident.commanderId ? String(incident.commanderId) : NONE}
+ onValueChange={(value) =>
+ update.mutate({
+ id: incident.id,
+ commanderId: value === NONE ? null : Number(value),
+ })
+ }
+ >
+ <SelectTrigger size="sm" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={NONE}>No commander</SelectItem>
+ {(members ?? []).map((member) => (
+ <SelectItem key={member.user.id} value={String(member.user.id)}>
+ {personName(member.user) ?? `User ${member.user.id}`}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Row>
+ <Row label="Started at">
+ <div className="flex gap-1">
+ <Input
+ type="datetime-local"
+ disabled={closed}
+ value={startedAt}
+ onChange={(e) => setStartedAt(e.target.value)}
+ />
+ {startedAt !== toLocalInput(incident.startedAt) ? (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() =>
+ update.mutate({
+ id: incident.id,
+ startedAt: new Date(startedAt),
+ })
+ }
+ >
+ Save
+ </Button>
+ ) : null}
+ </div>
+ </Row>
+ <Row label="Duration">
+ <span className="font-mono">
+ {formatDistanceStrict(incident.startedAt, end)}
+ </span>
+ </Row>
+ <Row label="Declared by">
+ {personName(incident.declaredByUser) ?? "System"}
+ </Row>
+ <Row label="Slack">
+ {incident.slackTeamId && incident.slackChannelId ? (
+ <Link
+ href={slackChannelUrl(
+ incident.slackTeamId,
+ incident.slackChannelId,
+ )}
+ target="_blank"
+ rel="noreferrer"
+ >
+ Open channel
+ </Link>
+ ) : (
+ <span className="text-muted-foreground">No channel</span>
+ )}
+ </Row>
+ <div className="flex flex-wrap gap-2 pt-2">
+ {incident.status === "resolved" && !closed ? (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={close.isPending}
+ onClick={() => close.mutate({ id: incident.id })}
+ >
+ Close incident
+ </Button>
+ ) : null}
+ {incident.deletable ? (
+ <FormAlertDialog
+ confirmationValue={incident.title}
+ submitAction={async () => {
+ await remove.mutateAsync({ id: incident.id });
+ }}
+ >
+ <Button size="sm" variant="destructive">
+ Delete
+ </Button>
+ </FormAlertDialog>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/incident-status-report.tsx b/apps/dashboard/src/components/incidents/incident-status-report.tsx
new file mode 100644
index 000000000..661ebc06e
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/incident-status-report.tsx
@@ -0,0 +1,344 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { statusReportStatus } from "@openstatus/db/src/schema/status_reports/constants";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
+import { Input } from "@openstatus/ui/components/ui/input";
+import { Label } from "@openstatus/ui/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@openstatus/ui/components/ui/select";
+import { Textarea } from "@openstatus/ui/components/ui/textarea";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { isTRPCClientError } from "@trpc/client";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { Link } from "@/components/common/link";
+import { useTRPC } from "@/lib/trpc/client";
+
+import { usePublicUpdate } from "./use-public-update";
+
+type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
+
+function toastError(error: Error) {
+ return isTRPCClientError(error) ? error.message : "Something went wrong";
+}
+
+export function IncidentStatusReport({
+ incident,
+ canNotify,
+}: {
+ incident: Incident;
+ canNotify: boolean;
+}) {
+ if (incident.statusReport) {
+ return (
+ <LinkedReport
+ incident={incident}
+ report={incident.statusReport}
+ canNotify={canNotify}
+ />
+ );
+ }
+ return <UnlinkedReport incident={incident} canNotify={canNotify} />;
+}
+
+function LinkedReport({
+ incident,
+ report,
+ canNotify,
+}: {
+ incident: Incident;
+ report: NonNullable<Incident["statusReport"]>;
+ canNotify: boolean;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [status, setStatus] = useState<string>(
+ report.status === "resolved" ? "monitoring" : report.status,
+ );
+ const [message, setMessage] = useState("");
+ const [notifySubscribers, setNotifySubscribers] = useState(canNotify);
+ const update = usePublicUpdate(incident.id);
+ const unlink = useMutation(
+ trpc.incident.unlinkStatusReport.mutationOptions({
+ onSuccess: () =>
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey({ id: incident.id }),
+ }),
+ }),
+ );
+ const closed = incident.closedAt !== null;
+
+ async function post() {
+ const parsed = statusReportStatus.find((s) => s === status);
+ if (!parsed) return;
+ const promise = update.post({
+ statusReportId: report.id,
+ status: parsed,
+ message,
+ notifySubscribers,
+ });
+ toast.promise(promise, {
+ loading: "Posting public update...",
+ success: "Public update posted",
+ error: toastError,
+ });
+ await promise;
+ setMessage("");
+ }
+
+ return (
+ <div className="grid gap-3">
+ <div className="flex items-start justify-between gap-2">
+ <div className="grid gap-0.5">
+ {report.pageId ? (
+ <Link
+ href={`/status-pages/${report.pageId}/status-reports/${report.id}`}
+ className="font-medium"
+ >
+ {report.title}
+ </Link>
+ ) : (
+ <span className="font-medium">{report.title}</span>
+ )}
+ <span className="text-muted-foreground font-mono text-xs capitalize">
+ {report.status}
+ </span>
+ </div>
+ {closed ? null : (
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={unlink.isPending}
+ onClick={() => unlink.mutate({ id: incident.id })}
+ >
+ Unlink
+ </Button>
+ )}
+ </div>
+ <div className="grid gap-2">
+ <Label>Post public update</Label>
+ <Select value={status} onValueChange={setStatus}>
+ <SelectTrigger size="sm" className="font-mono capitalize">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {statusReportStatus.map((s) => (
+ <SelectItem key={s} value={s} className="capitalize">
+ {s}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Textarea
+ rows={3}
+ placeholder="Message shown on your status page"
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ />
+ {canNotify ? (
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id="incident-report-notify"
+ checked={notifySubscribers}
+ onCheckedChange={(checked) =>
+ setNotifySubscribers(checked === true)
+ }
+ />
+ <Label htmlFor="incident-report-notify">Notify subscribers</Label>
+ </div>
+ ) : null}
+ <Button
+ size="sm"
+ disabled={!message.trim() || update.isPending}
+ onClick={() => post().catch(console.error)}
+ >
+ Post public update
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function UnlinkedReport({
+ incident,
+ canNotify,
+}: {
+ incident: Incident;
+ canNotify: boolean;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const { data: reports } = useQuery(
+ trpc.statusReport.list.queryOptions({ order: "desc" }),
+ );
+ const { data: pages } = useQuery(trpc.page.list.queryOptions());
+ const [mode, setMode] = useState<"link" | "create" | null>(null);
+ const [reportId, setReportId] = useState<string>("");
+ const [pageId, setPageId] = useState<string>("");
+ const [title, setTitle] = useState(incident.title);
+ const [message, setMessage] = useState("");
+ const [notifySubscribers, setNotifySubscribers] = useState(canNotify);
+
+ const refresh = () =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey({ id: incident.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.listEvents.queryKey({ id: incident.id }),
+ }),
+ ]);
+ const link = useMutation(
+ trpc.incident.linkStatusReport.mutationOptions({ onSuccess: refresh }),
+ );
+ const create = useMutation(
+ trpc.statusReport.create.mutationOptions({ onSuccess: refresh }),
+ );
+ const notify = useMutation(
+ trpc.subscriberNotification.statusReport.mutationOptions(),
+ );
+
+ if (incident.closedAt !== null) {
+ return (
+ <p className="text-muted-foreground text-sm">No status report linked.</p>
+ );
+ }
+
+ async function createReport() {
+ const promise = (async () => {
+ const created = await create.mutateAsync({
+ title,
+ status: "investigating",
+ pageId: Number(pageId),
+ pageComponents: [],
+ date: new Date(),
+ message,
+ notifySubscribers,
+ incidentId: incident.id,
+ });
+ if (created && notifySubscribers) {
+ await notify.mutateAsync({ id: created.id });
+ }
+ })();
+ toast.promise(promise, {
+ loading: "Creating status report...",
+ success: "Status report created",
+ error: toastError,
+ });
+ await promise;
+ setMode(null);
+ }
+
+ const openReports = (reports ?? []).filter((r) => r.status !== "resolved");
+
+ return (
+ <div className="grid gap-3">
+ <p className="text-muted-foreground text-sm">
+ No status report yet. Your users only see what you publish there.
+ </p>
+ <div className="flex gap-2">
+ <Button
+ size="sm"
+ variant={mode === "create" ? "default" : "outline"}
+ onClick={() => setMode("create")}
+ >
+ Create status report
+ </Button>
+ <Button
+ size="sm"
+ variant={mode === "link" ? "default" : "outline"}
+ onClick={() => setMode("link")}
+ >
+ Link existing
+ </Button>
+ </div>
+ {mode === "link" ? (
+ <div className="grid gap-2">
+ <Select value={reportId} onValueChange={setReportId}>
+ <SelectTrigger size="sm">
+ <SelectValue placeholder="Select an open report" />
+ </SelectTrigger>
+ <SelectContent>
+ {openReports.map((r) => (
+ <SelectItem key={r.id} value={String(r.id)}>
+ {r.title}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Button
+ size="sm"
+ disabled={!reportId || link.isPending}
+ onClick={() =>
+ toast.promise(
+ link.mutateAsync({
+ id: incident.id,
+ statusReportId: Number(reportId),
+ }),
+ {
+ loading: "Linking...",
+ success: "Status report linked",
+ error: toastError,
+ },
+ )
+ }
+ >
+ Link
+ </Button>
+ </div>
+ ) : null}
+ {mode === "create" ? (
+ <div className="grid gap-2">
+ <Select value={pageId} onValueChange={setPageId}>
+ <SelectTrigger size="sm">
+ <SelectValue placeholder="Select a status page" />
+ </SelectTrigger>
+ <SelectContent>
+ {(pages ?? []).map((p) => (
+ <SelectItem key={p.id} value={String(p.id)}>
+ {p.title}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Input value={title} onChange={(e) => setTitle(e.target.value)} />
+ <Textarea
+ rows={3}
+ placeholder="First public message"
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ />
+ {canNotify ? (
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id="incident-create-notify"
+ checked={notifySubscribers}
+ onCheckedChange={(checked) =>
+ setNotifySubscribers(checked === true)
+ }
+ />
+ <Label htmlFor="incident-create-notify">Notify subscribers</Label>
+ </div>
+ ) : null}
+ <Button
+ size="sm"
+ disabled={
+ !pageId || !title.trim() || !message.trim() || create.isPending
+ }
+ onClick={() => createReport().catch(console.error)}
+ >
+ Create and link
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/incident-timeline.tsx b/apps/dashboard/src/components/incidents/incident-timeline.tsx
new file mode 100644
index 000000000..d25cb86b9
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/incident-timeline.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import type { IncidentEventType } from "@openstatus/db/src/schema/incidents/constants";
+import { formatDistanceToNow } from "date-fns";
+
+import { ProcessMessage } from "@/components/content/process-message";
+import { personName } from "@/data/managed-incidents.client";
+
+type Event = NonNullable<RouterOutputs["incident"]["listEvents"]>[number];
+
+const labels: Record<IncidentEventType, string> = {
+ declared: "Declared",
+ severity_changed: "Severity changed",
+ status_changed: "Status changed",
+ commander_changed: "Commander changed",
+ started_at_changed: "Start time changed",
+ note: "Note",
+ status_report_linked: "Status report linked",
+ status_report_unlinked: "Status report unlinked",
+ slack_channel_bound: "Slack channel bound",
+ slack_channel_unbound: "Slack channel unbound",
+ mitigated: "Mitigated",
+ resolved: "Resolved",
+ canceled: "Canceled",
+ postmortem_drafted: "Postmortem drafted",
+ postmortem_updated: "Postmortem updated",
+ postmortem_approved: "Postmortem approved",
+ closed: "Closed",
+};
+
+export function IncidentTimeline({ events }: { events: Event[] }) {
+ if (events.length === 0) return null;
+ return (
+ <ol className="grid gap-4">
+ {events.map((event) => (
+ <li key={event.id} className="grid gap-1 border-l-2 pl-3">
+ <div className="text-muted-foreground flex flex-wrap items-center gap-x-2 text-xs">
+ <span className="text-foreground font-medium">
+ {labels[event.type]}
+ </span>
+ <span>·</span>
+ <span>{personName(event.createdByUser) ?? "System"}</span>
+ <span>·</span>
+ <time
+ dateTime={event.createdAt.toISOString()}
+ title={event.createdAt.toLocaleString()}
+ >
+ {formatDistanceToNow(event.createdAt, { addSuffix: true })}
+ </time>
+ </div>
+ {event.message ? (
+ <div className="prose dark:prose-invert prose-sm max-w-none">
+ <ProcessMessage value={event.message} />
+ </div>
+ ) : null}
+ </li>
+ ))}
+ </ol>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/resolve-report-dialog.tsx b/apps/dashboard/src/components/incidents/resolve-report-dialog.tsx
new file mode 100644
index 000000000..73c1b69f0
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/resolve-report-dialog.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@openstatus/ui/components/ui/alert-dialog";
+import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
+import { Label } from "@openstatus/ui/components/ui/label";
+import { Textarea } from "@openstatus/ui/components/ui/textarea";
+import { isTRPCClientError } from "@trpc/client";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+
+import { usePublicUpdate } from "./use-public-update";
+
+/**
+ * Offered after an incident is resolved or canceled while its status report
+ * is still open. Nothing is posted unless the user confirms the text.
+ */
+export function ResolveReportDialog({
+ incidentId,
+ report,
+ defaultMessage,
+ canNotify,
+ open,
+ onOpenChange,
+}: {
+ incidentId: number;
+ report: { id: number; title: string };
+ defaultMessage: string;
+ canNotify: boolean;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const [message, setMessage] = useState(defaultMessage);
+ const [notifySubscribers, setNotifySubscribers] = useState(canNotify);
+ const update = usePublicUpdate(incidentId);
+
+ useEffect(() => {
+ if (open) setMessage(defaultMessage);
+ }, [open, defaultMessage]);
+
+ async function submit() {
+ const promise = update.post({
+ statusReportId: report.id,
+ status: "resolved",
+ message,
+ notifySubscribers,
+ });
+ toast.promise(promise, {
+ loading: "Resolving status report...",
+ success: "Status report resolved",
+ error: (error) =>
+ isTRPCClientError(error) ? error.message : "Failed to resolve",
+ });
+ await promise;
+ onOpenChange(false);
+ }
+
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Resolve the status report too?</AlertDialogTitle>
+ <AlertDialogDescription>
+ <strong>{report.title}</strong> is still open on your status page.
+ Edit the public message below, or keep the report open.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <Textarea
+ rows={4}
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ />
+ {canNotify ? (
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id="resolve-report-notify"
+ checked={notifySubscribers}
+ onCheckedChange={(checked) =>
+ setNotifySubscribers(checked === true)
+ }
+ />
+ <Label htmlFor="resolve-report-notify">Notify subscribers</Label>
+ </div>
+ ) : null}
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep it open</AlertDialogCancel>
+ <AlertDialogAction
+ disabled={!message.trim() || update.isPending}
+ onClick={(e) => {
+ e.preventDefault();
+ submit().catch(console.error);
+ }}
+ >
+ Post resolved update
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/use-public-update.ts b/apps/dashboard/src/components/incidents/use-public-update.ts
new file mode 100644
index 000000000..8fc69c371
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/use-public-update.ts
@@ -0,0 +1,42 @@
+"use client";
+
+import type { statusReportStatus } from "@openstatus/db/src/schema/status_reports/constants";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { useTRPC } from "@/lib/trpc/client";
+
+/** Posts a status-report update and, when asked, notifies subscribers. */
+export function usePublicUpdate(incidentId: number) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const createUpdate = useMutation(
+ trpc.statusReport.createStatusReportUpdate.mutationOptions(),
+ );
+ const notify = useMutation(
+ trpc.subscriberNotification.statusReport.mutationOptions(),
+ );
+
+ return {
+ isPending: createUpdate.isPending || notify.isPending,
+ async post(args: {
+ statusReportId: number;
+ status: (typeof statusReportStatus)[number];
+ message: string;
+ notifySubscribers: boolean;
+ }) {
+ const update = await createUpdate.mutateAsync({
+ statusReportId: args.statusReportId,
+ status: args.status,
+ message: args.message,
+ date: new Date(),
+ notifySubscribers: args.notifySubscribers,
+ });
+ if (update && args.notifySubscribers) {
+ await notify.mutateAsync({ id: update.id });
+ }
+ await queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey({ id: incidentId }),
+ });
+ },
+ };
+}
diff --git a/packages/api/src/router/incident.ts b/packages/api/src/router/incident.ts
index 1ebdbd20f..733685772 100644
--- a/packages/api/src/router/incident.ts
+++ b/packages/api/src/router/incident.ts
@@ -15,6 +15,7 @@ import {
declareIncident,
deleteIncident,
getIncident,
+ getIncidentForStatusReport,
isDeletable,
linkIncidentStatusReport,
listIncidentEvents,
@@ -70,6 +71,21 @@ export const incidentRouter = createTRPCRouter({
}
}),
+ forStatusReport: protectedProcedure
+ .input(z.object({ statusReportId: z.number().int() }))
+ .query(async ({ ctx, input }) => {
+ try {
+ return (
+ (await getIncidentForStatusReport({
+ ctx: toServiceCtx(ctx),
+ input,
+ })) ?? null
+ );
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
+
listEvents: protectedProcedure
.input(IncidentIdInput)
.query(async ({ ctx, input }) => {
diff --git a/packages/api/src/router/statusReport.ts b/packages/api/src/router/statusReport.ts
index 480e5101b..aa8734be4 100644
--- a/packages/api/src/router/statusReport.ts
+++ b/packages/api/src/router/statusReport.ts
@@ -32,6 +32,7 @@ const createStatusReportTRPCInput = z.object({
date: z.coerce.date(),
message: z.string(),
notifySubscribers: z.boolean().nullish(),
+ incidentId: z.number().int().optional(),
});
const createStatusReportUpdateTRPCInput = z.object({
@@ -77,6 +78,7 @@ export const statusReportRouter = createTRPCRouter({
componentImpacts: input.componentImpacts ?? undefined,
date: input.date,
message: input.message,
+ incidentId: input.incidentId,
},
});
// Notification is a separate, client-driven step
diff --git a/packages/services/src/incident/index.ts b/packages/services/src/incident/index.ts
index 4af4513a2..baa31dbc8 100644
--- a/packages/services/src/incident/index.ts
+++ b/packages/services/src/incident/index.ts
@@ -10,7 +10,7 @@ export {
} from "./link-status-report";
export { listIncidentEvents } from "./list-events";
export { clearIncidentCommander } from "./members";
-export { getIncident, listIncidents } from "./list";
+export { getIncident, getIncidentForStatusReport, listIncidents } from "./list";
export {
AddIncidentNoteInput,
BindIncidentSlackChannelInput,
diff --git a/packages/services/src/incident/list.ts b/packages/services/src/incident/list.ts
index 0b5ef4073..0f58f721c 100644
--- a/packages/services/src/incident/list.ts
+++ b/packages/services/src/incident/list.ts
@@ -62,3 +62,22 @@ export async function getIncident(args: {
},
});
}
+
+/** The incident a status report communicates, if any. */
+export async function getIncidentForStatusReport(args: {
+ ctx: ServiceContext;
+ input: { statusReportId: number };
+}) {
+ const { ctx } = args;
+ requireIncidentFeature(ctx);
+ return getReadDb(ctx)
+ .select({ id: incident.id, title: incident.title, status: incident.status })
+ .from(incident)
+ .where(
+ and(
+ eq(incident.workspaceId, ctx.workspace.id),
+ eq(incident.statusReportId, args.input.statusReportId),
+ ),
+ )
+ .get();
+}