feat: unify alerts into one plugin, channels, rules and inbox

This commit is contained in:
LukeGus committed 2026-09-25 16:26:37 -05:00
1 parent fbe736bc20
commit 7c02daccf4
129 files changed
+20957 -2687

No files matched your search

@@ -0,0 +1,150 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, waitFor } from "@testing-library/react";
import type { PluginApiClient } from "@termix/plugin-sdk/frontend";
import {
renderWithApp,
type RenderedPluginApp,
} from "@termix/plugin-sdk/testing";
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
import * as plugin from "../../src/frontend/index";
import manifestJson from "../../manifest.json";
import locales from "../../locales/en.json";
const manifest = manifestJson as unknown as PluginManifest;
let rendered: RenderedPluginApp | null = null;
afterEach(async () => {
await rendered?.deactivate();
rendered = null;
});
const ITEMS = [
{
id: 2,
source: "acme-ssl",
category: "acme-ssl.renewal_failed",
severity: "critical",
title: "Certificate renewal failed",
body: "rate limited",
link: null,
context: null,
deliveries: [{ channelId: 1, name: "pager", ok: false, error: "HTTP 500" }],
readAt: null,
createdAt: new Date().toISOString(),
},
{
id: 1,
source: "termix",
category: "termix.announcement",
severity: "info",
title: "Termix 2.9 is out",
body: null,
link: { url: "https://termix.site" },
context: { actionText: "Read more" },
deliveries: null,
readAt: "2026-01-01T00:00:00.000Z",
createdAt: "2026-01-01T00:00:00.000Z",
},
];
function stubApi() {
const calls: Array<[string, string, unknown?]> = [];
const api = {
get: vi.fn(async (url: string) => {
calls.push(["GET", url]);
if (url.startsWith("/items"))
return { data: { items: ITEMS, unread: 1 } };
if (url === "/unread") return { data: { count: 1 } };
return { data: [] };
}),
post: vi.fn(async (url: string, body?: unknown) => {
calls.push(["POST", url, body]);
return { data: { count: 0 } };
}),
delete: vi.fn(async (url: string) => {
calls.push(["DELETE", url]);
return { data: { success: true } };
}),
put: vi.fn(),
patch: vi.fn(),
} as unknown as PluginApiClient;
return { api, calls };
}
describe(`${manifest.id} activate`, () => {
it("registers a footer rail item, its panel and tab, the popups and its actions", async () => {
rendered = await renderWithApp(plugin, { manifest, locales });
expect(rendered.registered.railItems()).toEqual([
expect.objectContaining({ id: "alerts", permission: "alerts.use" }),
]);
expect(rendered.registered.panels()).toEqual(["alerts"]);
expect(rendered.registered.tabs()).toEqual(["alerts"]);
expect(rendered.registered.slot("shell.overlay")).toEqual([
"alerts.toaster",
]);
expect(rendered.registered.actions().sort()).toEqual([
"alerts.open",
"alerts.openChannels",
]);
});
it("opens the tab from its actions", async () => {
rendered = await renderWithApp(plugin, { manifest, locales });
await rendered.app.invokeAction("alerts.openChannels");
expect(rendered.shellCalls).toContainEqual({
method: "openSingletonTab",
args: ["alerts"],
});
});
it("removes everything it registered on deactivate", async () => {
const app = await renderWithApp(plugin, { manifest, locales });
await app.deactivate();
expect(app.registered.tabs()).toEqual([]);
expect(app.registered.panels()).toEqual([]);
expect(app.registered.railItems()).toEqual([]);
expect(app.registered.actions()).toEqual([]);
expect(app.registered.slot("shell.overlay")).toEqual([]);
});
});
describe("the alerts panel", () => {
it("lists alerts, flags a failed delivery and marks one read", async () => {
const { api, calls } = stubApi();
rendered = await renderWithApp(plugin, { manifest, locales, api });
const panel = rendered.renderPanel("alerts", { active: true });
await waitFor(() =>
expect(panel.textContent).toContain("Certificate renewal failed"),
);
expect(panel.textContent).toContain("Termix 2.9 is out");
expect(panel.textContent).toContain("1 channel failed");
expect(panel.textContent).toContain("Read more");
fireEvent.click(panel.querySelector('[aria-label="Mark as read"]')!);
await waitFor(() =>
expect(calls).toContainEqual([
"POST",
"/items/read",
{ ids: [2], read: true },
]),
);
});
it("deletes an alert", async () => {
const { api, calls } = stubApi();
rendered = await renderWithApp(plugin, { manifest, locales, api });
const panel = rendered.renderPanel("alerts", { active: true });
await waitFor(() =>
expect(panel.textContent).toContain("Certificate renewal failed"),
);
fireEvent.click(panel.querySelectorAll('[aria-label="Delete"]')[0]);
await waitFor(() => expect(calls).toContainEqual(["DELETE", "/items/2"]));
await waitFor(() =>
expect(panel.textContent).not.toContain("Certificate renewal failed"),
);
});
});
+140
View File
@@ -0,0 +1,140 @@
import { describe, expect, it, vi } from "vitest";
import {
createAlertsStore,
parseServerSentEvents,
} from "../../src/frontend/store";
import { shouldPopUp } from "../../src/frontend/popups";
import {
configFrom,
parseHeaders,
EMPTY,
} from "../../src/frontend/channel-config";
import type { AlertItem } from "../../src/types";
function item(id: number, severity: AlertItem["severity"]): AlertItem {
return {
id,
source: "docker",
category: "docker",
severity,
title: `alert ${id}`,
body: null,
link: null,
context: null,
deliveries: null,
readAt: null,
createdAt: new Date().toISOString(),
};
}
/** A response whose body streams the given chunks, then stays open. */
function streaming(chunks: string[]): Response {
const encoder = new TextEncoder();
const body = new ReadableStream<Uint8Array>({
start(controller) {
for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
},
});
return new Response(body, {
headers: { "Content-Type": "text/event-stream" },
});
}
describe("parseServerSentEvents", () => {
it("parses whole events and keeps the rest for later", () => {
const events: Array<{ event: string; data: string }> = [];
const rest = parseServerSentEvents(
'event: unread\ndata: {"count":2}\n\n: keepalive\n\nevent: item\ndata: {"id"',
(event) => events.push(event),
);
expect(events).toEqual([{ event: "unread", data: '{"count":2}' }]);
expect(rest).toBe('event: item\ndata: {"id"');
});
});
describe("createAlertsStore", () => {
it("follows the unread count and hands on each alert once as new", async () => {
const first = item(7, "critical");
const store = createAlertsStore({
connect: async () =>
streaming([
'event: unread\ndata: {"count":3}\n\n',
`event: item\ndata: ${JSON.stringify(first)}\n\n`,
`event: item\ndata: ${JSON.stringify({ ...first, deliveries: [] })}\n\n`,
]),
loadUnread: async () => 0,
});
const seen: Array<[number, boolean]> = [];
store.onItem((alert, isNew) => seen.push([alert.id, isNew]));
store.start();
await vi.waitFor(() => expect(seen).toHaveLength(2));
store.stop();
expect(store.unread()).toBe(3);
expect(seen).toEqual([
[7, true],
[7, false],
]);
expect(store.version()).toBe(2);
});
it("falls back to the count route while the stream is down", async () => {
const loadUnread = vi.fn(async () => 5);
const store = createAlertsStore({
connect: async () => new Response("", { status: 503 }),
loadUnread,
retryMs: 10_000,
});
store.start();
await vi.waitFor(() => expect(store.unread()).toBe(5));
store.stop();
});
});
describe("popups", () => {
it("follows the user's level", () => {
expect(shouldPopUp(item(1, "info"), "all")).toBe(true);
expect(shouldPopUp(item(1, "info"), "warning")).toBe(false);
expect(shouldPopUp(item(1, "warning"), "warning")).toBe(true);
expect(shouldPopUp(item(1, "warning"), "critical")).toBe(false);
expect(shouldPopUp(item(1, "critical"), "critical")).toBe(true);
expect(shouldPopUp(item(1, "critical"), "off")).toBe(false);
});
});
describe("channel config", () => {
it("reads headers one per line", () => {
expect(
parseHeaders("Authorization: Bearer x\nbad line\nX-Id: 7 "),
).toEqual({ Authorization: "Bearer x", "X-Id": "7" });
});
it("builds only the fields each type uses", () => {
expect(
configFrom({
...EMPTY,
type: "webhook",
url: " https://a.example ",
headers: "A: b",
allowPrivateNetwork: true,
}),
).toEqual({
url: "https://a.example",
method: "POST",
headers: { A: "b" },
allowPrivateNetwork: true,
});
expect(
configFrom({ ...EMPTY, type: "email", to: "ops@example.com" }),
).toEqual({ to: "ops@example.com" });
expect(
configFrom({
...EMPTY,
type: "discord",
url: "https://discord.com/api/webhooks/1",
allowPrivateNetwork: true,
}),
).toEqual({ url: "https://discord.com/api/webhooks/1" });
});
});