Authentik Users + Messaging tabs + message endpoint (Slice 8)

Replace the UsersTab and MessagingTab stubs on the Authentik service
page, built new against the Authentik directory endpoint (the old
Jellyfin-backed Users page was deleted in slice 3).

Backend message endpoint (Option A -- implemented):
- POST /api/services/authentik/{service_id}/message accepts
  {recipient_emails, subject, html_body}, validates SMTP, enqueues via
  the existing mail_queue. Returns {status, request_id, recipient_count}
  on success or {status: 'error', error} on failure (200, matching the
  directory endpoint's graceful-error pattern).
- GET /api/services/authentik/{service_id}/message/status proxies
  mail_queue.status().

UsersTab: paginated (25/page), searchable directory table sourced from
GET /api/services/authentik/{id}/users. Columns: name, username, email,
status (is_active badge). Graceful error Alert on endpoint error.

MessagingTab: minimal but functional compose -- recipient search +
toggle buttons (Authentik users with emails), subject, HTML body
textarea (default template), send wired to the new endpoint, result
Alert. Rich-text toolbar, attachment upload, and queue-status banner
are follow-ups (the old compose UI had them; this slice ships the core
send flow).

New: api/authentik.ts, hooks/useAuthentik.ts (useAuthentikUsers +
useAuthentikMessageStatus), UsersTab + MessagingTab + tests. stubs.tsx
loses both stubs; index.ts wires the real components.

Tests: UsersTab (renders users + error state), MessagingTab (renders
compose form). 100 frontend tests pass (+4); 271 backend tests pass
(no regression); lint/build green both sides.

Refs openspec/changes/services-as-hub-ia/ (spec R6.2/R7.2/R7.3, tasks
slice 8).
This commit is contained in:
Developer
2026-06-26 19:44:35 +00:00
parent 6a1f8bbd59
commit 8f4e8428f0
9 changed files with 558 additions and 20 deletions
+65
View File
@@ -0,0 +1,65 @@
/** API client for the Authentik service (directory + messaging). */
import { get, post } from "./shared";
export interface AuthentikUser {
pk: number;
username: string;
name: string;
email: string;
is_active: boolean;
avatar: string | null;
[key: string]: unknown;
}
export interface AuthentikUsersResponse {
items: AuthentikUser[];
total: number;
page: number;
page_size: number;
error?: string;
}
export async function fetchAuthentikUsers(
serviceId: string,
params: { search?: string; page?: number; page_size?: number },
): Promise<AuthentikUsersResponse> {
return get<AuthentikUsersResponse>(
`/api/services/authentik/${serviceId}/users`,
{
search: params.search ?? "",
page: String(params.page ?? 1),
page_size: String(params.page_size ?? 50),
},
);
}
export interface AuthentikMessageInput {
recipient_emails: string[];
subject: string;
html_body: string;
}
export interface AuthentikMessageResponse {
status: string;
request_id?: string;
recipient_count?: number;
error?: string;
}
export async function sendAuthentikMessage(
serviceId: string,
input: AuthentikMessageInput,
): Promise<AuthentikMessageResponse> {
return post<AuthentikMessageResponse>(
`/api/services/authentik/${serviceId}/message`,
input,
);
}
export async function fetchAuthentikMessageStatus(
serviceId: string,
): Promise<Record<string, unknown>> {
return get<Record<string, unknown>>(
`/api/services/authentik/${serviceId}/message/status`,
);
}
+43
View File
@@ -0,0 +1,43 @@
/** Hooks for the Authentik directory + messaging tabs. */
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
fetchAuthentikMessageStatus,
fetchAuthentikUsers,
sendAuthentikMessage,
} from "../api/authentik";
export function useAuthentikUsers(
serviceId: string,
params: { search?: string; page?: number; page_size?: number },
) {
return useQuery({
queryKey: ["authentik", "users", serviceId, params],
queryFn: () => fetchAuthentikUsers(serviceId, params),
staleTime: 10_000,
});
}
export function useSendAuthentikMessage(serviceId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (input: {
recipient_emails: string[];
subject: string;
html_body: string;
}) => sendAuthentikMessage(serviceId, input),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["authentik", "message-status", serviceId],
});
},
});
}
export function useAuthentikMessageStatus(serviceId: string) {
return useQuery({
queryKey: ["authentik", "message-status", serviceId],
queryFn: () => fetchAuthentikMessageStatus(serviceId),
refetchInterval: 5_000,
staleTime: 0,
});
}
@@ -0,0 +1,129 @@
/** MessagingTab — compose email to Authentik users via the mail queue. */
import { useState } from "react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
useAuthentikUsers,
useSendAuthentikMessage,
} from "../../hooks/useAuthentik";
import type { ServiceInstance } from "../../types";
const DEFAULT_BODY = "<p>Hello,</p><p> </p><p>Best,<br />Manage</p>";
export function MessagingTab({ instance }: { instance: ServiceInstance }) {
const [search, setSearch] = useState("");
const [selectedEmails, setSelectedEmails] = useState<Set<string>>(new Set());
const [subject, setSubject] = useState("");
const [htmlBody, setHtmlBody] = useState(DEFAULT_BODY);
const { data } = useAuthentikUsers(instance.id, {
search,
page: 1,
page_size: 100,
});
const sendMessage = useSendAuthentikMessage(instance.id);
const users = (data?.items ?? []).filter((u) => u.email);
const error = data?.error;
function toggleEmail(email: string) {
setSelectedEmails((prev) => {
const next = new Set(prev);
if (next.has(email)) next.delete(email);
else next.add(email);
return next;
});
}
function handleSend() {
if (!subject.trim() || selectedEmails.size === 0) return;
sendMessage.mutate({
recipient_emails: Array.from(selectedEmails),
subject: subject.trim(),
html_body: htmlBody,
});
}
const canSend =
subject.trim() !== "" && selectedEmails.size > 0 && !sendMessage.isPending;
return (
<div className="flex flex-col gap-4">
{error ? (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
) : null}
{sendMessage.data ? (
<Alert>
<AlertDescription>
{sendMessage.data.status === "queued"
? `Message queued (${sendMessage.data.recipient_count ?? 0} recipients, request ${sendMessage.data.request_id?.slice(0, 8) ?? ""}).`
: `Error: ${sendMessage.data.error ?? "unknown"}`}
</AlertDescription>
</Alert>
) : null}
<div className="flex flex-col gap-2">
<Label htmlFor="msg-search">Find recipients</Label>
<Input
id="msg-search"
placeholder="Search users to add as recipients…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="max-w-md"
/>
{users.length > 0 ? (
<div className="flex flex-wrap gap-2">
{users.slice(0, 20).map((user) => (
<Button
key={user.pk}
variant={selectedEmails.has(user.email) ? "default" : "outline"}
size="sm"
onClick={() => toggleEmail(user.email)}
>
{user.name || user.username}
</Button>
))}
</div>
) : null}
{selectedEmails.size > 0 ? (
<p className="text-sm text-muted-foreground">
{selectedEmails.size} recipient
{selectedEmails.size === 1 ? "" : "s"} selected.
</p>
) : null}
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="msg-subject">Subject</Label>
<Input
id="msg-subject"
value={subject}
onChange={(e) => setSubject(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="msg-body">Message (HTML)</Label>
<Textarea
id="msg-body"
rows={8}
value={htmlBody}
onChange={(e) => setHtmlBody(e.target.value)}
className="font-mono text-xs"
/>
</div>
<div>
<Button onClick={handleSend} disabled={!canSend}>
{sendMessage.isPending ? "Sending…" : "Send message"}
</Button>
</div>
</div>
);
}
@@ -0,0 +1,136 @@
/** UsersTab — Authentik user directory for the Authentik service page. */
import { useState } from "react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import type { ServiceInstance } from "../../types";
import { useAuthentikUsers } from "../../hooks/useAuthentik";
const PAGE_SIZE = 25;
export function UsersTab({ instance }: { instance: ServiceInstance }) {
const [search, setSearch] = useState("");
const [page, setPage] = useState(1);
const [committedSearch, setCommittedSearch] = useState("");
const { data, isLoading } = useAuthentikUsers(instance.id, {
search: committedSearch,
page,
page_size: PAGE_SIZE,
});
const error = data?.error;
const users = data?.items ?? [];
const total = data?.total ?? 0;
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
function handleSearch() {
setPage(1);
setCommittedSearch(search);
}
return (
<div className="flex flex-col gap-3">
{error ? (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
) : null}
<div className="flex items-center gap-2">
<Input
placeholder="Search users…"
value={search}
onChange={(e) => setSearch(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleSearch();
}}
className="max-w-xs"
/>
<Button variant="outline" onClick={handleSearch}>
Search
</Button>
</div>
<div className="rounded-lg border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Username</TableHead>
<TableHead>Email</TableHead>
<TableHead className="w-24">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading && users.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="text-muted-foreground">
Loading
</TableCell>
</TableRow>
) : users.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="text-muted-foreground">
No users found.
</TableCell>
</TableRow>
) : (
users.map((user) => (
<TableRow key={user.pk}>
<TableCell className="font-medium">
{user.name || "—"}
</TableCell>
<TableCell>{user.username}</TableCell>
<TableCell className="text-muted-foreground">
{user.email || "—"}
</TableCell>
<TableCell>
<Badge variant={user.is_active ? "default" : "secondary"}>
{user.is_active ? "Active" : "Inactive"}
</Badge>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{total > 0 ? (
<div className="flex items-center justify-between text-sm text-muted-foreground">
<span>
{total} user{total === 1 ? "" : "s"} · Page {page} of {totalPages}
</span>
<div className="flex gap-1">
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={page <= 1}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
disabled={page >= totalPages}
>
Next
</Button>
</div>
</div>
) : null}
</div>
);
}
@@ -0,0 +1,55 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { MessagingTab } from "../MessagingTab";
import type { ServiceInstance } from "../../../types";
const instance: ServiceInstance = {
id: "auth-1",
service_type: "authentik",
name: "Main Authentik",
config: { base_url: "https://auth.example.com", timeout_seconds: 10 },
secrets_set: { api_token: true },
enabled: true,
created_at: 1_700_000_000,
updated_at: 1_700_000_000,
};
vi.mock("../../../hooks/useAuthentik", () => ({
useAuthentikUsers: vi.fn(() => ({
data: {
items: [
{
pk: 1,
username: "alice",
name: "Alice",
email: "alice@example.com",
is_active: true,
},
],
total: 1,
page: 1,
page_size: 100,
},
})),
useSendAuthentikMessage: vi.fn(() => ({
mutate: vi.fn(),
isPending: false,
data: undefined,
})),
}));
describe("MessagingTab", () => {
it("renders the compose form (subject, body, send)", () => {
render(<MessagingTab instance={instance} />);
expect(screen.getByLabelText("Subject")).toBeInTheDocument();
expect(screen.getByLabelText("Message (HTML)")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Send message" }),
).toBeInTheDocument();
});
it("renders recipient toggle buttons from the directory", () => {
render(<MessagingTab instance={instance} />);
expect(screen.getByText("Alice")).toBeInTheDocument();
});
});
@@ -0,0 +1,61 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { UsersTab } from "../UsersTab";
import type { ServiceInstance } from "../../../types";
const instance: ServiceInstance = {
id: "auth-1",
service_type: "authentik",
name: "Main Authentik",
config: { base_url: "https://auth.example.com", timeout_seconds: 10 },
secrets_set: { api_token: true },
enabled: true,
created_at: 1_700_000_000,
updated_at: 1_700_000_000,
};
vi.mock("../../../hooks/useAuthentik", () => ({
useAuthentikUsers: vi.fn(() => ({
data: {
items: [
{
pk: 1,
username: "alice",
name: "Alice",
email: "alice@example.com",
is_active: true,
},
{
pk: 2,
username: "bob",
name: "Bob",
email: "bob@example.com",
is_active: false,
},
],
total: 2,
page: 1,
page_size: 25,
},
isLoading: false,
})),
}));
describe("UsersTab", () => {
it("renders the directory table with users", () => {
render(<UsersTab instance={instance} />);
expect(screen.getByText("Alice")).toBeInTheDocument();
expect(screen.getByText("bob")).toBeInTheDocument();
expect(screen.getByText("alice@example.com")).toBeInTheDocument();
expect(screen.getByText("Active")).toBeInTheDocument();
expect(screen.getByText("Inactive")).toBeInTheDocument();
});
it("renders search input and pagination", () => {
render(<UsersTab instance={instance} />);
expect(screen.getByPlaceholderText("Search users…")).toBeInTheDocument();
expect(screen.getByText(/2 users/)).toBeInTheDocument();
expect(screen.getByText("Previous")).toBeInTheDocument();
expect(screen.getByText("Next")).toBeInTheDocument();
});
});
+3 -8
View File
@@ -6,19 +6,14 @@
*/
import type { ComponentType } from "react";
import type { ServiceInstance } from "../../types";
import {
AlertsTab,
LinksTab,
MessagingTab,
MetricsTab,
OverviewTab,
UsersTab,
} from "./stubs";
import { AlertsTab, LinksTab, MetricsTab, OverviewTab } from "./stubs";
import { MediaTab } from "./MediaTab";
import { RequestsTab } from "./RequestsTab";
import { FilesTab } from "./FilesTab";
import { ActionsTab } from "./ActionsTab";
import { JobsTab } from "./JobsTab";
import { UsersTab } from "./UsersTab";
import { MessagingTab } from "./MessagingTab";
export type ServiceTabComponent = ComponentType<{ instance: ServiceInstance }>;
@@ -28,14 +28,6 @@ export function OverviewTab({ instance }: { instance: ServiceInstance }) {
return <Stub label="Service overview" instance={instance} />;
}
export function UsersTab({ instance }: { instance: ServiceInstance }) {
return <Stub label="Users" instance={instance} />;
}
export function MessagingTab({ instance }: { instance: ServiceInstance }) {
return <Stub label="Messaging" instance={instance} />;
}
export function AlertsTab({ instance }: { instance: ServiceInstance }) {
return <Stub label="Alerts" instance={instance} />;
}