Skip to content

Open-source status page, incident response and uptime monitoring

chore: improve postmortem agent draft + linked status reports (#2860)

Maximilian Kaske0df8b6c9cc57
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
index c47412781..a766184c2 100644
--- a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
@@ -170,9 +170,11 @@ export function Client({ id }: { id: number }) {
</DetailHeader>
<DetailContent>
<DetailMain>
- {/* Resolved incidents lead with the postmortem; open ones with the timeline. */}
+ {/* Resolved incidents lead with the postmortem; open ones with the
+ timeline. A canceled one is a false alarm: no postmortem. */}
{resolved ? postmortem : timeline}
- {resolved ? timeline : postmortem}
+ {resolved ? timeline : null}
+ {resolved || incident.status === "canceled" ? null : postmortem}
</DetailMain>
<DetailAside>
<DetailSection>
diff --git a/apps/dashboard/src/components/incidents/incident-postmortem.tsx b/apps/dashboard/src/components/incidents/incident-postmortem.tsx
index cf1f3063b..baffc5fc9 100644
--- a/apps/dashboard/src/components/incidents/incident-postmortem.tsx
+++ b/apps/dashboard/src/components/incidents/incident-postmortem.tsx
@@ -1,9 +1,10 @@
"use client";
import type { RouterOutputs } from "@openstatus/api";
-import { AI } from "@openstatus/icons";
+import { AI, Check, Copy } from "@openstatus/icons";
import { Button } from "@openstatus/ui/components/ui/button";
import { InputGroupButton } from "@openstatus/ui/components/ui/input-group";
+import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
@@ -63,6 +64,7 @@ export function IncidentPostmortem({
// refetch never clobbers unsaved edits.
const [draft, setDraft] = useState<string | null>(null);
const [confirmClose, setConfirmClose] = useState(false);
+ const { copy, isCopied } = useCopyToClipboard();
const server = postmortem?.content ?? TEMPLATE;
const content = draft ?? server;
@@ -125,6 +127,9 @@ export function IncidentPostmortem({
const canSave = !busy && dirty && content.trim().length > 0;
const canApprove = postmortem !== null && !approved;
+ const showAgent = agentAllowed && !approved;
+ const hasActions = postmortem !== null || showAgent;
+
const hint = dirty
? "Unsaved changes"
: approved && incident.closedAt === null
@@ -136,17 +141,33 @@ export function IncidentPostmortem({
: "No postmortem yet";
return (
- <Composer size="lg" defaultValue={approved ? "preview" : "write"}>
+ <Composer size="lg" defaultValue={postmortem ? "preview" : "write"}>
<ComposerHeader>
- {agentAllowed && !approved ? (
- <InputGroupButton
- variant="outline"
- disabled={busy}
- onClick={() => draftWithAgent.mutate({ id: incident.id })}
- >
- <AI />
- {draftWithAgent.isPending ? "Drafting..." : "Draft with agent"}
- </InputGroupButton>
+ {/* Rendered only with an action, so the header's "Markdown" hint shows otherwise. */}
+ {hasActions ? (
+ <div className="flex items-center gap-1">
+ {postmortem ? (
+ <InputGroupButton
+ variant="ghost"
+ onClick={() =>
+ copy(content, { withToast: "Postmortem copied" })
+ }
+ >
+ {isCopied ? <Check /> : <Copy />}
+ Copy
+ </InputGroupButton>
+ ) : null}
+ {showAgent ? (
+ <InputGroupButton
+ variant="outline"
+ disabled={busy}
+ onClick={() => draftWithAgent.mutate({ id: incident.id })}
+ >
+ <AI />
+ {draftWithAgent.isPending ? "Drafting..." : "Draft with agent"}
+ </InputGroupButton>
+ ) : null}
+ </div>
) : null}
</ComposerHeader>
<ComposerTextarea
diff --git a/apps/dashboard/src/components/incidents/incident-status-report.tsx b/apps/dashboard/src/components/incidents/incident-status-report.tsx
index bb130ad15..700f3e31d 100644
--- a/apps/dashboard/src/components/incidents/incident-status-report.tsx
+++ b/apps/dashboard/src/components/incidents/incident-status-report.tsx
@@ -2,9 +2,33 @@
import type { RouterOutputs } from "@openstatus/api";
import { statusReportStatus } from "@openstatus/db/src/schema/status_reports/constants";
+import { Check, Expand } from "@openstatus/icons";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@openstatus/ui/components/ui/alert-dialog";
import { Button } from "@openstatus/ui/components/ui/button";
import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@openstatus/ui/components/ui/command";
import { Label } from "@openstatus/ui/components/ui/label";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@openstatus/ui/components/ui/popover";
import {
Select,
SelectContent,
@@ -13,6 +37,7 @@ import {
SelectValue,
} from "@openstatus/ui/components/ui/select";
import { Textarea } from "@openstatus/ui/components/ui/textarea";
+import { cn } from "@openstatus/ui/lib/utils";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
@@ -87,6 +112,7 @@ function LinkedReport({
const trpc = useTRPC();
const queryClient = useQueryClient();
const [composing, setComposing] = useState(false);
+ const [confirmUnlink, setConfirmUnlink] = useState(false);
const [status, setStatus] = useState<string>(
report.status === "resolved" ? "monitoring" : report.status,
);
@@ -95,10 +121,18 @@ function LinkedReport({
const update = usePublishUpdate(report.id);
const unlink = useMutation(
trpc.incident.unlinkStatusReport.mutationOptions({
- onSuccess: () =>
- queryClient.invalidateQueries({
- queryKey: trpc.incident.get.queryKey({ id: incident.id }),
- }),
+ onSuccess: () => {
+ setConfirmUnlink(false);
+ return Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey({ id: incident.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.linkedStatusReportIds.queryKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(errorMessage(error)),
}),
);
const closed = incident.closedAt !== null;
@@ -203,8 +237,7 @@ function LinkedReport({
<Button
size="sm"
variant="outline"
- disabled={unlink.isPending}
- onClick={() => unlink.mutate({ id: incident.id })}
+ onClick={() => setConfirmUnlink(true)}
>
Unlink
</Button>
@@ -212,6 +245,30 @@ function LinkedReport({
</>
)}
</ActionCardFooter>
+ <AlertDialog open={confirmUnlink} onOpenChange={setConfirmUnlink}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Unlink this status report?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {report.title} stays on your status page as it is, but updates
+ from this incident no longer reach it. You can link it again
+ later.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep linked</AlertDialogCancel>
+ <AlertDialogAction
+ disabled={unlink.isPending}
+ onClick={(e) => {
+ e.preventDefault();
+ unlink.mutate({ id: incident.id });
+ }}
+ >
+ Unlink
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</ActionCard>
);
}
@@ -221,7 +278,8 @@ function UnlinkedReport({ incident }: { incident: Incident }) {
const queryClient = useQueryClient();
const [createOpen, setCreateOpen] = useState(false);
const [linking, setLinking] = useState(false);
- const [reportId, setReportId] = useState<string>("");
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [reportId, setReportId] = useState<number | null>(null);
const closed = incident.closedAt !== null;
const refresh = () =>
@@ -232,6 +290,9 @@ function UnlinkedReport({ incident }: { incident: Incident }) {
queryClient.invalidateQueries({
queryKey: trpc.incident.listEvents.queryKey({ id: incident.id }),
}),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.linkedStatusReportIds.queryKey(),
+ }),
]);
const link = useMutation(
trpc.incident.linkStatusReport.mutationOptions({ onSuccess: refresh }),
@@ -240,9 +301,17 @@ function UnlinkedReport({ incident }: { incident: Incident }) {
...trpc.statusReport.list.queryOptions({ order: "desc" }),
enabled: !closed,
});
- const openReports = (reports ?? []).filter((r) => r.status !== "resolved");
+ const { data: linkedIds } = useQuery({
+ ...trpc.incident.linkedStatusReportIds.queryOptions(),
+ enabled: !closed,
+ });
+ // Until both load, the list could offer reports another incident holds.
+ const linked = linkedIds ? new Set(linkedIds) : null;
+ const linkable =
+ reports && linked ? reports.filter((r) => !linked.has(r.id)) : [];
+ const selected = linkable.find((r) => r.id === reportId);
// Closing mid-edit would otherwise strand a form whose footer is gone.
- const showLink = !closed && linking && openReports.length > 0;
+ const showLink = !closed && linking && linkable.length > 0;
return (
<ActionCard className="border-dashed">
@@ -262,19 +331,63 @@ function UnlinkedReport({ incident }: { incident: Incident }) {
</ActionCardHeader>
{showLink ? (
<ActionCardContent className="grid gap-2">
- <Select value={reportId} onValueChange={setReportId}>
- <SelectTrigger size="sm" className="w-full">
- <SelectValue placeholder="Select an open report" />
- </SelectTrigger>
- <SelectContent>
- {openReports.map((r) => (
- <SelectItem key={r.id} value={String(r.id)}>
- <StatusDot variant={statusVariants[r.status]} />
- {r.title}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <Popover open={pickerOpen} onOpenChange={setPickerOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ size="sm"
+ variant="outline"
+ role="combobox"
+ aria-expanded={pickerOpen}
+ className={cn(
+ "w-full justify-between font-normal",
+ !selected && "text-muted-foreground",
+ )}
+ >
+ {selected ? (
+ <span className="flex min-w-0 items-center gap-2">
+ <StatusDot variant={statusVariants[selected.status]} />
+ <span className="truncate">{selected.title}</span>
+ </span>
+ ) : (
+ "Search status reports..."
+ )}
+ <Expand className="size-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
+ <Command>
+ <CommandInput placeholder="Search status reports..." />
+ <CommandList>
+ <CommandEmpty>No status report found.</CommandEmpty>
+ <CommandGroup>
+ {linkable.map((r) => (
+ <CommandItem
+ key={r.id}
+ value={String(r.id)}
+ keywords={[r.title, r.page.title, r.status]}
+ onSelect={() => {
+ setReportId(r.id);
+ setPickerOpen(false);
+ }}
+ >
+ <StatusDot variant={statusVariants[r.status]} />
+ <span className="truncate">{r.title}</span>
+ <span className="text-muted-foreground ml-auto truncate text-xs">
+ {r.page.title}
+ </span>
+ <Check
+ className={cn(
+ "size-4 shrink-0",
+ r.id === reportId ? "opacity-100" : "opacity-0",
+ )}
+ />
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
</ActionCardContent>
) : null}
{closed ? null : (
@@ -283,12 +396,13 @@ function UnlinkedReport({ incident }: { incident: Incident }) {
<>
<Button
size="sm"
- disabled={!reportId || link.isPending}
+ disabled={!selected || link.isPending}
onClick={() =>
+ selected &&
toast.promise(
link.mutateAsync({
id: incident.id,
- statusReportId: Number(reportId),
+ statusReportId: selected.id,
}),
{
loading: "Linking...",
@@ -313,7 +427,7 @@ function UnlinkedReport({ incident }: { incident: Incident }) {
<Button size="sm" onClick={() => setCreateOpen(true)}>
Create status report
</Button>
- {openReports.length > 0 ? (
+ {linkable.length > 0 ? (
<Button
size="sm"
variant="outline"
diff --git a/packages/api/src/router/incident.ts b/packages/api/src/router/incident.ts
index b1cd02d37..2b0947df9 100644
--- a/packages/api/src/router/incident.ts
+++ b/packages/api/src/router/incident.ts
@@ -33,6 +33,7 @@ import {
linkIncidentStatusReport,
listIncidentEvents,
listIncidents,
+ listLinkedStatusReportIds,
openIncidentSlackChannel,
setIncidentStatus,
unbindIncidentSlackChannel,
@@ -173,6 +174,14 @@ export const incidentRouter = createTRPCRouter({
}
}),
+ linkedStatusReportIds: protectedProcedure.query(async ({ ctx }) => {
+ try {
+ return await listLinkedStatusReportIds({ ctx: toServiceCtx(ctx) });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
+
listEvents: protectedProcedure
.input(IncidentIdInput)
.query(async ({ ctx, input }) => {
diff --git a/packages/services/src/incident/__tests__/postmortem-draft.test.ts b/packages/services/src/incident/__tests__/postmortem-draft.test.ts
index 1c47080e9..98977c4fe 100644
--- a/packages/services/src/incident/__tests__/postmortem-draft.test.ts
+++ b/packages/services/src/incident/__tests__/postmortem-draft.test.ts
@@ -162,6 +162,7 @@ describe("generatePostmortemDraft", () => {
expect(prompts).toHaveLength(1);
expect(prompts[0]).toContain("Checkout down");
expect(prompts[0]).toContain("DB failover");
+ expect(prompts[0]).not.toContain("slack_channel_bound");
expect(draft.draftedBy).toBe("agent");
expect(draft.sourceTranscript).toContain("DB failover");
expect(draft.content).toContain("Drafted by the openstatus agent");
diff --git a/packages/services/src/incident/index.ts b/packages/services/src/incident/index.ts
index b4f6ddfbb..4bb247c87 100644
--- a/packages/services/src/incident/index.ts
+++ b/packages/services/src/incident/index.ts
@@ -23,6 +23,7 @@ export {
getIncidentBySlackChannel,
getIncidentForStatusReport,
listIncidents,
+ listLinkedStatusReportIds,
} from "./list";
export {
approvePostmortem,
diff --git a/packages/services/src/incident/list.ts b/packages/services/src/incident/list.ts
index d9ead4fef..b24542c0b 100644
--- a/packages/services/src/incident/list.ts
+++ b/packages/services/src/incident/list.ts
@@ -1,4 +1,4 @@
-import { and, desc, eq, inArray, sql } from "@openstatus/db";
+import { and, desc, eq, inArray, isNotNull, sql } from "@openstatus/db";
import { incident } from "@openstatus/db/src/schema";
import { type ServiceContext, getReadDb } from "../context";
@@ -80,6 +80,26 @@ export async function getIncidentForStatusReport(args: {
.get();
}
+/** Status reports already held by an incident; each links to at most one. */
+export async function listLinkedStatusReportIds(args: {
+ ctx: ServiceContext;
+}): Promise<number[]> {
+ const { ctx } = args;
+ const rows = await getReadDb(ctx)
+ .select({ statusReportId: incident.statusReportId })
+ .from(incident)
+ .where(
+ and(
+ eq(incident.workspaceId, ctx.workspace.id),
+ isNotNull(incident.statusReportId),
+ ),
+ )
+ .all();
+ return rows.flatMap((r) =>
+ r.statusReportId === null ? [] : [r.statusReportId],
+ );
+}
+
/** The incident bound to a Slack channel, or `undefined`. */
export async function getIncidentBySlackChannel(args: {
ctx: ServiceContext;
diff --git a/packages/services/src/incident/postmortem-draft.ts b/packages/services/src/incident/postmortem-draft.ts
index 0afd874e4..5452a6801 100644
--- a/packages/services/src/incident/postmortem-draft.ts
+++ b/packages/services/src/incident/postmortem-draft.ts
@@ -1,5 +1,6 @@
import { asc, eq } from "@openstatus/db";
import {
+ type IncidentEventType,
type IncidentPostmortem,
statusReportUpdate,
} from "@openstatus/db/src/schema";
@@ -137,7 +138,19 @@ Write GitHub-flavored markdown with exactly these sections, in order:
## What went well
## What went wrong
## Action items
-Use only the facts given. Where a section has no facts, say what is unknown instead of guessing. Timeline entries are UTC timestamps with one line each. Action items are a checklist ("- [ ] ...") with an owner placeholder when none is known. No preamble, no closing remarks.`;
+Use only the facts given. Where a section has no facts, say what is unknown instead of guessing. The timeline is a bullet list ("- HH:MM UTC - ...") of the key moments only (detection, escalation, decisions, mitigation, resolution); state the date once above the list when the incident spans one day, otherwise use "- YYYY-MM-DD HH:MM UTC - ...". Never mention internal IDs (Slack channel IDs, status report numbers). Action items are a checklist ("- [ ] ...") with an owner placeholder when none is known. No preamble, no closing remarks.`;
+
+/** Events that record wiring, not what happened during the incident. */
+const BOOKKEEPING = new Set<IncidentEventType>([
+ "status_report_linked",
+ "status_report_unlinked",
+ "slack_channel_bound",
+ "slack_channel_unbound",
+ "postmortem_drafted",
+ "postmortem_updated",
+ "postmortem_approved",
+ "closed",
+]);
async function fitTranscript(
transcript: string,
@@ -232,6 +245,7 @@ export async function generatePostmortemDraft(args: {
const timeline = [...events]
.reverse()
+ .filter((e) => !BOOKKEEPING.has(e.type))
.map(
(e) =>
`[${e.createdAt.toISOString()}] ${e.type}${e.createdByUser ? ` by ${displayName(e.createdByUser)}` : ""}: ${e.message ?? ""}`,