Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
fix: link incidents to status bars (#2309)
Colin Ozanne4b410a7ba75f
diff --git a/apps/web/src/app/(landing)/status/[id]/[component]/component-detail.tsx b/apps/web/src/app/(landing)/status/[id]/[component]/component-detail.tsxindex 9e47b6bda..ccb634118 100644--- a/apps/web/src/app/(landing)/status/[id]/[component]/component-detail.tsx+++ b/apps/web/src/app/(landing)/status/[id]/[component]/component-detail.tsx@@ -152,7 +152,7 @@ export function ComponentDetail({});if (!data.found || !data.service || !data.component) return null;- const { service, component, history, incidents } = data;+ const { service, component, history, incidents, overlayIncidents } = data;const fullName = `${service.name} ${component.name}`;const answer = answerFor({@@ -232,7 +232,7 @@ export function ComponentDetail({{component.name} uptime over the last {days} days</h2><div className="not-prose">- <HistoryBars daily={history} days={days} />+ <HistoryBars daily={history} days={days} incidents={overlayIncidents} /></div><h2>{component.name} recent incidents</h2>diff --git a/apps/web/src/app/(landing)/status/[id]/history-bars.tsx b/apps/web/src/app/(landing)/status/[id]/history-bars.tsxindex a41469c3f..a85da73b1 100644--- a/apps/web/src/app/(landing)/status/[id]/history-bars.tsx+++ b/apps/web/src/app/(landing)/status/[id]/history-bars.tsx@@ -6,6 +6,12 @@ import type {StatusType,} from "@openstatus/ui/components/blocks/status.types";+import { renderIncidentEvent } from "../incident-event";+import {+ type OverlayIncident,+ bucketIncidentsByUtcDay,+} from "../incident-events";+type DailyRow = {day: string;worstIndicator: string;@@ -49,6 +55,7 @@ function labelFor(status: StatusType): string {export type HistoryBarsProps = {daily: DailyRow[];days: number;+ incidents?: OverlayIncident[];};const INDICATOR_SEVERITY: Record<string, number> = {@@ -87,6 +94,9 @@ function buildSeries(props: HistoryBarsProps): StatusBarData[] {snapshotCount: prev.snapshotCount + r.snapshotCount,});}+ const eventsByDay = bucketIncidentsByUtcDay(props.incidents ?? [], {+ days: props.days,+ });const out: StatusBarData[] = [];const today = new Date();today.setUTCHours(0, 0, 0, 0);@@ -105,7 +115,7 @@ function buildSeries(props: HistoryBarsProps): StatusBarData[] {day: iso,bar: [{ status, height: 100 }],card: [{ status, value: labelFor(status) }],- events: [],+ events: eventsByDay.get(iso) ?? [],});}return out;@@ -119,7 +129,7 @@ export function HistoryBars(props: HistoryBarsProps) {// single-class utilities) without forking the shared component.return (<div className="[&_[data-slot=status-bar-item]]:rounded-none [&_[data-slot=status-bar-item]>div]:rounded-none [&_[data-slot=status-bar-item]>div>div]:rounded-none">- <StatusBar data={data} />+ <StatusBar data={data} renderEvent={renderIncidentEvent} /></div>);}diff --git a/apps/web/src/app/(landing)/status/[id]/service-detail.tsx b/apps/web/src/app/(landing)/status/[id]/service-detail.tsxindex 4ca6c4771..a06f7363c 100644--- a/apps/web/src/app/(landing)/status/[id]/service-detail.tsx+++ b/apps/web/src/app/(landing)/status/[id]/service-detail.tsx@@ -44,7 +44,7 @@ function jsonLd(args: {export function ServiceDetail({ slug, days }: { slug: string; days: number }) {const [data] = api.externalService.detail.useSuspenseQuery({ slug, days });- const { service, latest, history, effective } = data;+ const { service, latest, history, effective, overlayIncidents } = data;const indicator = effective.indicator;const status = effective.status;@@ -128,7 +128,7 @@ export function ServiceDetail({ slug, days }: { slug: string; days: number }) {{service.name} uptime over the last {days} days</h2><div className="not-prose">- <HistoryBars daily={history} days={days} />+ <HistoryBars daily={history} days={days} incidents={overlayIncidents} /></div><Suspense fallback={null}>diff --git a/apps/web/src/app/(landing)/status/external-service-components.tsx b/apps/web/src/app/(landing)/status/external-service-components.tsxindex 6bdd0be15..aa0cced93 100644--- a/apps/web/src/app/(landing)/status/external-service-components.tsx+++ b/apps/web/src/app/(landing)/status/external-service-components.tsx@@ -16,6 +16,11 @@ import { ChevronDownIcon, ChevronRightIcon } from "lucide-react";import { useState } from "react";import { ExternalServicePill } from "./external-service-pill";+import { renderIncidentEvent } from "./incident-event";+import {+ type OverlayIncident,+ bucketIncidentsByUtcDay,+} from "./incident-events";export type ComponentHistoryDay = {day: string;@@ -34,6 +39,7 @@ export type ExternalServiceComponentItem = {indicator: string;status: string;history: ComponentHistoryDay[];+ incidents?: OverlayIncident[];};export type ExternalServiceComponentsProps = {@@ -89,10 +95,12 @@ function indicatorToStatusType(args: {function buildSeries(history: ComponentHistoryDay[],days: number,+ incidents?: OverlayIncident[],): StatusBarData[] {const byDay = new Map<string, ComponentHistoryDay>();for (const r of history) byDay.set(r.day.slice(0, 10), r);+ const eventsByDay = bucketIncidentsByUtcDay(incidents ?? [], { days });const out: StatusBarData[] = [];const today = new Date();today.setUTCHours(0, 0, 0, 0);@@ -111,7 +119,7 @@ function buildSeries(day: iso,bar: [{ status, height: 100 }],card: [{ status, value: systemStatusLabels[status].short }],- events: [],+ events: eventsByDay.get(iso) ?? [],});}return out;@@ -178,7 +186,7 @@ function ComponentRow({days: number;hrefBase?: string;}) {- const series = buildSeries(component.history, days);+ const series = buildSeries(component.history, days, component.incidents);return (<div className="border-border/50 flex flex-col gap-1 border-b py-2 last:border-b-0"><div className="flex flex-wrap items-center justify-between gap-2">@@ -199,7 +207,7 @@ function ComponentRow({/></div><div className="[&_[data-slot=status-bar-item]]:rounded-none [&_[data-slot=status-bar-item]>div]:rounded-none [&_[data-slot=status-bar-item]>div>div]:rounded-none">- <StatusBar data={series} />+ <StatusBar data={series} renderEvent={renderIncidentEvent} /></div></div>);diff --git a/apps/web/src/app/(landing)/status/incident-event.tsx b/apps/web/src/app/(landing)/status/incident-event.tsxnew file mode 100644index 000000000..710d4691b--- /dev/null+++ b/apps/web/src/app/(landing)/status/incident-event.tsx@@ -0,0 +1,38 @@+import { StatusBarEvent } from "@openstatus/ui/components/blocks/status-bar";+import type { StatusBarData } from "@openstatus/ui/components/blocks/status.types";+import { cn } from "@openstatus/ui/lib/utils";++export function renderIncidentEvent(+ event: StatusBarData["events"][number],+ index: number,+) {+ const key = `${event.id}-${event.type}-${index}`;+ const spacing = index > 0 ? "mt-2" : undefined;+ const node = (+ <StatusBarEvent+ type={event.type}+ name={event.name}+ from={event.from}+ to={event.to}+ isAggregated={event.isAggregated}+ status={event.status}+ />+ );+ if (!event.shortlink)+ return (+ <div key={key} className={spacing}>+ {node}+ </div>+ );+ return (+ <a+ key={key}+ className={cn("block", spacing)}+ href={event.shortlink}+ target="_blank"+ rel="noopener noreferrer"+ >+ {node}+ </a>+ );+}diff --git a/apps/web/src/app/(landing)/status/incident-events.test.ts b/apps/web/src/app/(landing)/status/incident-events.test.tsnew file mode 100644index 000000000..21ddd2cf3--- /dev/null+++ b/apps/web/src/app/(landing)/status/incident-events.test.ts@@ -0,0 +1,153 @@+import { describe, expect, test } from "bun:test";++import {+ type OverlayIncident,+ bucketIncidentsByUtcDay,+} from "./incident-events";++const NOW = new Date("2026-06-24T12:00:00.000Z");+const DAYS = 45; // window start = 2026-05-11++function bucket(incidents: OverlayIncident[]) {+ return bucketIncidentsByUtcDay(incidents, { days: DAYS, now: NOW });+}++function keys(incidents: OverlayIncident[]): string[] {+ return [...bucket(incidents).keys()].sort();+}++describe("bucketIncidentsByUtcDay", () => {+ test("single-day incident maps to one UTC day", () => {+ const inc: OverlayIncident = {+ id: "a",+ name: "Elevated error rate",+ impact: "critical",+ startedAt: "2026-06-23T16:19:00.000Z",+ createdAt: "2026-06-23T16:19:00.000Z",+ resolvedAt: "2026-06-23T18:44:00.000Z",+ };+ const map = bucket([inc]);+ expect([...map.keys()]).toEqual(["2026-06-23"]);+ const [event] = map.get("2026-06-23") ?? [];+ expect(event?.type).toBe("incident");+ expect(event?.to).not.toBeNull();+ });++ test("multi-day incident spans every overlapped UTC day", () => {+ const inc: OverlayIncident = {+ id: "b",+ name: "Long outage",+ startedAt: "2026-06-20T22:00:00.000Z",+ createdAt: "2026-06-20T22:00:00.000Z",+ resolvedAt: "2026-06-22T02:00:00.000Z",+ };+ expect(keys([inc])).toEqual(["2026-06-20", "2026-06-21", "2026-06-22"]);+ });++ test("ongoing incident spans through today with to=null", () => {+ const inc: OverlayIncident = {+ id: "c",+ name: "Still down",+ startedAt: "2026-06-23T10:00:00.000Z",+ createdAt: "2026-06-23T10:00:00.000Z",+ resolvedAt: null,+ };+ const map = bucket([inc]);+ expect([...map.keys()].sort()).toEqual(["2026-06-23", "2026-06-24"]);+ expect(map.get("2026-06-24")?.[0]?.to).toBeNull();+ });++ test("null startedAt falls back to createdAt for the start", () => {+ const inc: OverlayIncident = {+ id: "d",+ name: "No start time",+ createdAt: "2026-06-22T09:00:00.000Z",+ resolvedAt: "2026-06-22T10:00:00.000Z",+ };+ const map = bucket([inc]);+ expect([...map.keys()]).toEqual(["2026-06-22"]);+ expect(map.get("2026-06-22")?.[0]?.from?.toISOString()).toBe(+ "2026-06-22T09:00:00.000Z",+ );+ });++ test("clamps to the window but keeps the full span on from/to", () => {+ const inc: OverlayIncident = {+ id: "e",+ name: "Started before the window",+ startedAt: "2026-05-09T00:00:00.000Z",+ createdAt: "2026-05-09T00:00:00.000Z",+ resolvedAt: "2026-05-13T00:00:00.000Z",+ };+ const map = bucket([inc]);+ expect([...map.keys()].sort()).toEqual([+ "2026-05-11",+ "2026-05-12",+ "2026-05-13",+ ]);+ expect(map.get("2026-05-11")?.[0]?.from?.toISOString()).toBe(+ "2026-05-09T00:00:00.000Z",+ );+ });++ test("incident fully before the window produces no days", () => {+ const inc: OverlayIncident = {+ id: "f",+ name: "Ancient",+ startedAt: "2026-04-01T00:00:00.000Z",+ createdAt: "2026-04-01T00:00:00.000Z",+ resolvedAt: "2026-04-02T00:00:00.000Z",+ };+ expect(keys([inc])).toEqual([]);+ });++ test("resolvedAt before startedAt paints a single day", () => {+ const inc: OverlayIncident = {+ id: "g",+ name: "Bad timestamps",+ startedAt: "2026-06-23T10:00:00.000Z",+ createdAt: "2026-06-23T10:00:00.000Z",+ resolvedAt: "2026-06-23T09:00:00.000Z",+ };+ expect(keys([inc])).toEqual(["2026-06-23"]);+ });++ test("present-but-invalid resolvedAt is resolved, not ongoing", () => {+ const inc: OverlayIncident = {+ id: "j",+ name: "Bad resolvedAt",+ startedAt: "2026-06-23T10:00:00.000Z",+ createdAt: "2026-06-23T10:00:00.000Z",+ resolvedAt: "not-a-date",+ };+ const map = bucket([inc]);+ expect([...map.keys()]).toEqual(["2026-06-23"]);+ expect(map.get("2026-06-23")?.[0]?.to).not.toBeNull();+ });++ test("maintenance impact yields a maintenance event", () => {+ const inc: OverlayIncident = {+ id: "h",+ name: "Scheduled maintenance",+ impact: "maintenance",+ startedAt: "2026-06-23T10:00:00.000Z",+ createdAt: "2026-06-23T10:00:00.000Z",+ resolvedAt: "2026-06-23T11:00:00.000Z",+ };+ expect(bucket([inc]).get("2026-06-23")?.[0]?.type).toBe("maintenance");+ });++ test("carries shortlink onto each day event", () => {+ const inc: OverlayIncident = {+ id: "i",+ name: "Linked",+ shortlink: "https://stspg.io/abc",+ startedAt: "2026-06-23T10:00:00.000Z",+ createdAt: "2026-06-23T10:00:00.000Z",+ resolvedAt: "2026-06-23T11:00:00.000Z",+ };+ expect(bucket([inc]).get("2026-06-23")?.[0]?.shortlink).toBe(+ "https://stspg.io/abc",+ );+ });+});diff --git a/apps/web/src/app/(landing)/status/incident-events.ts b/apps/web/src/app/(landing)/status/incident-events.tsnew file mode 100644index 000000000..2b13a7d9f--- /dev/null+++ b/apps/web/src/app/(landing)/status/incident-events.ts@@ -0,0 +1,82 @@+import type { StatusBarData } from "@openstatus/ui/components/blocks/status.types";++export type OverlayIncident = {+ id: string;+ name: string;+ impact?: string;+ shortlink?: string;+ startedAt?: string;+ createdAt: string;+ resolvedAt?: string | null;+};++type DayEvent = StatusBarData["events"][number];++function floorUtcDay(d: Date): Date {+ const x = new Date(d);+ x.setUTCHours(0, 0, 0, 0);+ return x;+}++// Maps incidents onto the UTC days they overlap, keyed by `YYYY-MM-DD` so the+// keys line up with the day buckets built in the history bars. Each spanned day+// gets the incident's full range (`from`/`to`); `to: null` marks an ongoing one.+export function bucketIncidentsByUtcDay(+ incidents: OverlayIncident[],+ opts: { days: number; now?: Date },+): Map<string, DayEvent[]> {+ const map = new Map<string, DayEvent[]>();+ const now = opts.now ?? new Date();+ const todayUtc = floorUtcDay(now);+ const windowStart = new Date(todayUtc);+ windowStart.setUTCDate(todayUtc.getUTCDate() - (opts.days - 1));++ for (const inc of incidents) {+ const startMs = Date.parse(inc.startedAt ?? inc.createdAt);+ if (Number.isNaN(startMs)) continue;++ // Only a null/absent resolvedAt is ongoing; a present-but-unparseable value+ // is bad data, so resolve it to a zero-length span (not extended to today).+ const from = new Date(startMs);+ let to: Date | null;+ let endMs: number;+ if (inc.resolvedAt == null) {+ to = null;+ endMs = now.getTime();+ } else {+ const resolvedMs = Date.parse(inc.resolvedAt);+ endMs = Number.isNaN(resolvedMs)+ ? startMs+ : Math.max(resolvedMs, startMs);+ to = new Date(endMs);+ }+ const type: DayEvent["type"] =+ inc.impact === "maintenance" ? "maintenance" : "incident";++ let cursor = floorUtcDay(new Date(startMs));+ if (cursor.getTime() < windowStart.getTime())+ cursor = floorUtcDay(windowStart);+ const lastDay = floorUtcDay(new Date(endMs));+ const lastClamped =+ lastDay.getTime() > todayUtc.getTime() ? todayUtc : lastDay;++ while (cursor.getTime() <= lastClamped.getTime()) {+ const iso = cursor.toISOString().slice(0, 10);+ const event: DayEvent = {+ id: inc.id,+ name: inc.name,+ type,+ from,+ to,+ shortlink: inc.shortlink,+ };+ const list = map.get(iso);+ if (list) list.push(event);+ else map.set(iso, [event]);+ cursor = new Date(cursor);+ cursor.setUTCDate(cursor.getUTCDate() + 1);+ }+ }++ return map;+}diff --git a/packages/api/src/router/externalService.ts b/packages/api/src/router/externalService.tsindex be5c80804..70c39e995 100644--- a/packages/api/src/router/externalService.ts+++ b/packages/api/src/router/externalService.ts@@ -9,6 +9,7 @@ import {import {type ExternalIncidentListItem,listExternalIncidentsByComponent,+ listExternalIncidentsByServiceId,listExternalIncidentsBySlug,} from "@openstatus/services/external-service-incident";import {@@ -192,6 +193,7 @@ const componentItemSchema = z.object({indicator: z.string(),status: z.string(),history: z.array(historyRowSchema),+ incidents: z.array(incidentSchema),});const componentDetailSchema = z.object({@@ -216,6 +218,7 @@ const componentDetailSchema = z.object({.nullable(),history: z.array(historyRowSchema),incidents: z.array(incidentSchema),+ overlayIncidents: z.array(incidentSchema),});type HistoryTbRow = {@@ -247,6 +250,24 @@ function toIncidentDTO(i: ExternalIncidentListItem) {};}+// Window for overlaying incidents onto the bars: the visible `days` plus a+// one-day pad so an incident starting just before the first bar still buckets.+function overlaySince(days: number): Date {+ return new Date(Date.now() - (days + 1) * 24 * 60 * 60 * 1000);+}++// An untagged incident (empty affected_component_ids) is service-wide, so it+// applies to every component; otherwise it must name this upstream component.+function incidentAffectsComponent(+ i: ExternalIncidentListItem,+ upstreamComponentId: string,+): boolean {+ return (+ i.affectedComponentIds.length === 0 ||+ i.affectedComponentIds.includes(upstreamComponentId)+ );+}+export const externalServiceRouter = createTRPCRouter({grid: publicProcedure.output(z.array(gridItemSchema)).query(async () => {const [services, latestRows] = await Promise.all([@@ -306,6 +327,7 @@ export const externalServiceRouter = createTRPCRouter({history: z.array(historyRowSchema),effective: effectiveSchema,reports: z.object({ reporters: z.number(), threshold: z.number() }),+ overlayIncidents: z.array(incidentSchema),}),).query(async ({ input }) => {@@ -322,20 +344,28 @@ export const externalServiceRouter = createTRPCRouter({const days = input.days ?? DEFAULT_HISTORY_DAYS;const since = new Date(Date.now() - REPORT_WINDOW_MS);- const [latestRows, historyRows, reportRows] = await Promise.all([- safeData(- tb.externalStatusLatest({ ids: slugChain }),- "externalStatusLatest",- ),- safeData(- tb.externalStatusHistory({ ids: slugChain, days }),- "externalStatusHistory",- ),- safeRows(- getServiceReportWindows({ serviceIds: [service.id], since }),- "getServiceReportWindows (detail)",- ),- ]);+ const [latestRows, historyRows, reportRows, overlayIncidentRows] =+ await Promise.all([+ safeData(+ tb.externalStatusLatest({ ids: slugChain }),+ "externalStatusLatest",+ ),+ safeData(+ tb.externalStatusHistory({ ids: slugChain, days }),+ "externalStatusHistory",+ ),+ safeRows(+ getServiceReportWindows({ serviceIds: [service.id], since }),+ "getServiceReportWindows (detail)",+ ),+ safeRows(+ listExternalIncidentsByServiceId({+ externalServiceId: service.id,+ since: overlaySince(days),+ }),+ "listExternalIncidentsByServiceId (detail)",+ ),+ ]);const newest = [...latestRows].sort((a, b) => b.last_fetched_at - a.last_fetched_at,@@ -373,6 +403,7 @@ export const externalServiceRouter = createTRPCRouter({history: historyRows.map(toHistoryRow),effective,reports: { reporters, threshold },+ overlayIncidents: overlayIncidentRows.map(toIncidentDTO),};}),@@ -424,22 +455,30 @@ export const externalServiceRouter = createTRPCRouter({).query(async ({ input }) => {try {- const { supported, components } = await listExternalComponentsBySlug({- slug: input.slug,- });- if (!supported || components.length === 0) {+ const { supported, components, service } =+ await listExternalComponentsBySlug({ slug: input.slug });+ if (!supported || !service || components.length === 0) {return { supported, components: [] };}const days = input.days ?? DEFAULT_HISTORY_DAYS;const componentIds = components.map((c) => String(c.id));- const historyRows = await safeData(- tb.externalStatusComponentHistory({- component_ids: componentIds,- days,- }),- "externalStatusComponentHistory",- );+ const [historyRows, serviceIncidents] = await Promise.all([+ safeData(+ tb.externalStatusComponentHistory({+ component_ids: componentIds,+ days,+ }),+ "externalStatusComponentHistory",+ ),+ safeRows(+ listExternalIncidentsByServiceId({+ externalServiceId: service.id,+ since: overlaySince(days),+ }),+ "listExternalIncidentsByServiceId (components)",+ ),+ ]);const historyByComponent = new Map<string, typeof historyRows>();for (const row of historyRows) {@@ -462,6 +501,11 @@ export const externalServiceRouter = createTRPCRouter({history: (historyByComponent.get(String(c.id)) ?? []).map(toHistoryRow,),+ incidents: serviceIncidents+ .filter((inc) =>+ incidentAffectsComponent(inc, c.upstreamComponentId),+ )+ .map(toIncidentDTO),})),};} catch (err) {@@ -489,6 +533,7 @@ export const externalServiceRouter = createTRPCRouter({component: null,history: [],incidents: [],+ overlayIncidents: [],};try {const { service, component } = await getExternalComponentBySlug({@@ -499,24 +544,32 @@ export const externalServiceRouter = createTRPCRouter({const days = input.days ?? DEFAULT_HISTORY_DAYS;const since = new Date(Date.now() - REPORT_WINDOW_MS);- const [historyRows, incidents, reportRows] = await Promise.all([- safeData(- tb.externalStatusComponentHistory({- component_ids: [String(component.id)],- days,+ const [historyRows, incidents, reportRows, overlayServiceIncidents] =+ await Promise.all([+ safeData(+ tb.externalStatusComponentHistory({+ component_ids: [String(component.id)],+ days,+ }),+ "externalStatusComponentHistory (component)",+ ),+ listExternalIncidentsByComponent({+ externalServiceId: service.id,+ upstreamComponentId: component.upstreamComponentId,+ limit: INCIDENTS_LIMIT,}),- "externalStatusComponentHistory (component)",- ),- listExternalIncidentsByComponent({- externalServiceId: service.id,- upstreamComponentId: component.upstreamComponentId,- limit: INCIDENTS_LIMIT,- }),- safeRows(- getComponentReportWindows({ serviceId: service.id, since }),- "getComponentReportWindows (component)",- ),- ]);+ safeRows(+ getComponentReportWindows({ serviceId: service.id, since }),+ "getComponentReportWindows (component)",+ ),+ safeRows(+ listExternalIncidentsByServiceId({+ externalServiceId: service.id,+ since: overlaySince(days),+ }),+ "listExternalIncidentsByServiceId (component)",+ ),+ ]);const reporters =reportRows.find((r) => r.componentId === component.id)?.reporters ??@@ -550,6 +603,11 @@ export const externalServiceRouter = createTRPCRouter({},history: historyRows.map(toHistoryRow),incidents: incidents.map(toIncidentDTO),+ overlayIncidents: overlayServiceIncidents+ .filter((inc) =>+ incidentAffectsComponent(inc, component.upstreamComponentId),+ )+ .map(toIncidentDTO),};} catch (err) {console.warn(diff --git a/packages/services/src/external-service-incident/__tests__/external-service-incident.test.ts b/packages/services/src/external-service-incident/__tests__/external-service-incident.test.tsindex 66ddc5a0a..9f1ba0138 100644--- a/packages/services/src/external-service-incident/__tests__/external-service-incident.test.ts+++ b/packages/services/src/external-service-incident/__tests__/external-service-incident.test.ts@@ -9,6 +9,7 @@ import { afterEach, describe, test } from "@std/testing/bdd";import {type UpsertExternalIncidentInput,listExternalIncidentsByComponent,+ listExternalIncidentsByServiceId,listExternalIncidentsBySlug,pruneStaleRawPayloads,upsertExternalIncidentsForService,@@ -594,3 +595,73 @@ describe("pruneStaleRawPayloads", () => {expect(byId.get("ongoing-old")?.rawPayloadPurgedAt).toBeNull();});});++describe("listExternalIncidentsByServiceId since-window", () => {+ test("keeps ongoing and resolved-in-window, drops resolved-before", async () => {+ const serviceId = await seedService({ slug: `${TEST_PREFIX}-since` });+ const now = new Date("2026-06-15T00:00:00.000Z");+ const since = new Date("2026-06-01T00:00:00.000Z");++ await upsertExternalIncidentsForService({+ externalServiceId: serviceId,+ now,+ incidents: [+ {+ providerIncidentId: "ongoing-old",+ name: "Ongoing since May",+ status: "investigating",+ impact: "major",+ shortlink: "https://stspg.io/ongoing",+ startedAt: new Date("2026-05-01T00:00:00.000Z"),+ createdAt: new Date("2026-05-01T00:00:00.000Z"),+ resolvedAt: null,+ affectedComponentIds: ["cmp-a"],+ raw: { id: "ongoing-old" },+ },+ {+ providerIncidentId: "resolved-before",+ name: "Resolved before window",+ status: "resolved",+ impact: "minor",+ startedAt: new Date("2026-05-01T00:00:00.000Z"),+ createdAt: new Date("2026-05-01T00:00:00.000Z"),+ resolvedAt: new Date("2026-05-20T00:00:00.000Z"),+ affectedComponentIds: [],+ raw: { id: "resolved-before" },+ },+ {+ providerIncidentId: "resolved-after",+ name: "Resolved inside window",+ status: "resolved",+ impact: "critical",+ startedAt: new Date("2026-05-25T00:00:00.000Z"),+ createdAt: new Date("2026-05-25T00:00:00.000Z"),+ resolvedAt: new Date("2026-06-10T00:00:00.000Z"),+ affectedComponentIds: ["cmp-b"],+ raw: { id: "resolved-after" },+ },+ ],+ });++ const windowed = await listExternalIncidentsByServiceId({+ externalServiceId: serviceId,+ since,+ });+ const ids = new Set(windowed.map((r) => r.providerIncidentId));+ expect(ids.has("ongoing-old")).toBe(true);+ expect(ids.has("resolved-after")).toBe(true);+ expect(ids.has("resolved-before")).toBe(false);++ // affectedComponentIds is returned for server-side per-component bucketing+ const ongoing = windowed.find(+ (r) => r.providerIncidentId === "ongoing-old",+ );+ expect(ongoing?.affectedComponentIds).toEqual(["cmp-a"]);++ // no `since` returns everything (within the default limit)+ const all = await listExternalIncidentsByServiceId({+ externalServiceId: serviceId,+ });+ expect(all.length).toBe(3);+ });+});diff --git a/packages/services/src/external-service-incident/list.ts b/packages/services/src/external-service-incident/list.tsindex 2d2c4bafa..b54b159d5 100644--- a/packages/services/src/external-service-incident/list.ts+++ b/packages/services/src/external-service-incident/list.ts@@ -1,4 +1,13 @@-import { and, db as defaultDb, desc, eq, sql } from "@openstatus/db";+import {+ and,+ db as defaultDb,+ desc,+ eq,+ gte,+ isNull,+ or,+ sql,+} from "@openstatus/db";import type { ApiConfigType } from "@openstatus/db/src/schema";import { externalServiceIncident } from "@openstatus/db/src/schema";@@ -17,9 +26,37 @@ export type ExternalIncidentListItem = {startedAt: Date | null;createdAt: Date;resolvedAt: Date | null;+ affectedComponentIds: string[];};const DEFAULT_LIMIT = 5;+const OVERLAY_LIMIT = 200;++// An incident is "within the window" if it's ongoing or resolved on/after `since`.+// Keyed off the indexed `resolved_at`, so a long incident still in progress (or+// resolved inside the window) is kept even when it started before `since`.+function withinWindow(since: Date | undefined) {+ return since+ ? or(+ isNull(externalServiceIncident.resolvedAt),+ gte(externalServiceIncident.resolvedAt, since),+ )+ : undefined;+}++const INCIDENT_COLUMNS = {+ id: externalServiceIncident.id,+ externalServiceId: externalServiceIncident.externalServiceId,+ providerIncidentId: externalServiceIncident.providerIncidentId,+ name: externalServiceIncident.name,+ status: externalServiceIncident.status,+ impact: externalServiceIncident.impact,+ shortlink: externalServiceIncident.shortlink,+ startedAt: externalServiceIncident.startedAt,+ createdAt: externalServiceIncident.createdAt,+ resolvedAt: externalServiceIncident.resolvedAt,+ affectedComponentIds: externalServiceIncident.affectedComponentIds,+};// must stay in sync with fetchers that implement `fetchIncidents` in @openstatus/status-fetcherexport const INCIDENT_SUPPORTED_API_CONFIG_TYPES = new Set<ApiConfigType>([@@ -35,27 +72,22 @@ export async function listExternalIncidentsByServiceId(args: {ctx?: GlobalReadContext;externalServiceId: number;limit?: number;+ since?: Date;}): Promise<ExternalIncidentListItem[]> {const { ctx, externalServiceId } = args;const db = ctx?.db ?? defaultDb;- const limit = args.limit ?? DEFAULT_LIMIT;+ const limit = args.limit ?? (args.since ? OVERLAY_LIMIT : DEFAULT_LIMIT);const rows = await retryRead(() =>db- .select({- id: externalServiceIncident.id,- externalServiceId: externalServiceIncident.externalServiceId,- providerIncidentId: externalServiceIncident.providerIncidentId,- name: externalServiceIncident.name,- status: externalServiceIncident.status,- impact: externalServiceIncident.impact,- shortlink: externalServiceIncident.shortlink,- startedAt: externalServiceIncident.startedAt,- createdAt: externalServiceIncident.createdAt,- resolvedAt: externalServiceIncident.resolvedAt,- })+ .select(INCIDENT_COLUMNS).from(externalServiceIncident)- .where(eq(externalServiceIncident.externalServiceId, externalServiceId))+ .where(+ and(+ eq(externalServiceIncident.externalServiceId, externalServiceId),+ withinWindow(args.since),+ ),+ ).orderBy(desc(sql`COALESCE(${externalServiceIncident.startedAt}, ${externalServiceIncident.createdAt})`,@@ -76,30 +108,21 @@ export async function listExternalIncidentsByComponent(args: {externalServiceId: number;upstreamComponentId: string;limit?: number;+ since?: Date;}): Promise<ExternalIncidentListItem[]> {const { ctx, externalServiceId, upstreamComponentId } = args;const db = ctx?.db ?? defaultDb;- const limit = args.limit ?? DEFAULT_LIMIT;+ const limit = args.limit ?? (args.since ? OVERLAY_LIMIT : DEFAULT_LIMIT);const rows = await retryRead(() =>db- .select({- id: externalServiceIncident.id,- externalServiceId: externalServiceIncident.externalServiceId,- providerIncidentId: externalServiceIncident.providerIncidentId,- name: externalServiceIncident.name,- status: externalServiceIncident.status,- impact: externalServiceIncident.impact,- shortlink: externalServiceIncident.shortlink,- startedAt: externalServiceIncident.startedAt,- createdAt: externalServiceIncident.createdAt,- resolvedAt: externalServiceIncident.resolvedAt,- })+ .select(INCIDENT_COLUMNS).from(externalServiceIncident).where(and(eq(externalServiceIncident.externalServiceId, externalServiceId),sql`EXISTS (SELECT 1 FROM json_each(${externalServiceIncident.affectedComponentIds}) WHERE value = ${upstreamComponentId})`,+ withinWindow(args.since),),).orderBy(diff --git a/packages/ui/src/components/blocks/status.types.ts b/packages/ui/src/components/blocks/status.types.tsindex ce3d8e9d3..869831bb5 100644--- a/packages/ui/src/components/blocks/status.types.ts+++ b/packages/ui/src/components/blocks/status.types.ts@@ -67,5 +67,7 @@ export type StatusBarData = {isAggregated?: boolean;/** Overrides the type-derived dot color (e.g. the day's worst report impact). */status?: Exclude<StatusType, "empty">;+ /** External link for the event (e.g. an upstream incident page). */+ shortlink?: string;}[];};