Compare commits

..

5 Commits

Author SHA1 Message Date
72d295edd6 feat(web): add queue notification feed
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-08 18:18:07 -05:00
6e9def3c5a Merge pull request 'feat(api): MS24 queue notifications module' (#750) from feat/ms24-queue-api into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-08 23:04:16 +00:00
456d53fc7f fix(api): add SkipCsrf to queue notification ack endpoint
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-08 17:54:35 -05:00
8014930b70 Merge pull request 'fix(api): proxy mission-control routes to orchestrator' (#748) from fix/mission-control-proxy into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-08 22:51:08 +00:00
06f2cc4be3 feat(api): add queue notifications module
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-08 17:27:41 -05:00
14 changed files with 1280 additions and 4 deletions

View File

@@ -56,6 +56,7 @@
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"better-auth": "^1.4.17", "better-auth": "^1.4.17",
"bullmq": "^5.67.2", "bullmq": "^5.67.2",
"chokidar": "^4.0.3",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.3", "class-validator": "^0.14.3",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",

View File

@@ -62,6 +62,7 @@ import { OnboardingModule } from "./onboarding/onboarding.module";
import { ChatProxyModule } from "./chat-proxy/chat-proxy.module"; import { ChatProxyModule } from "./chat-proxy/chat-proxy.module";
import { MissionControlProxyModule } from "./mission-control-proxy/mission-control-proxy.module"; import { MissionControlProxyModule } from "./mission-control-proxy/mission-control-proxy.module";
import { OrchestratorModule } from "./orchestrator/orchestrator.module"; import { OrchestratorModule } from "./orchestrator/orchestrator.module";
import { QueueNotificationsModule } from "./queue-notifications/queue-notifications.module";
@Module({ @Module({
imports: [ imports: [
@@ -145,6 +146,7 @@ import { OrchestratorModule } from "./orchestrator/orchestrator.module";
ChatProxyModule, ChatProxyModule,
MissionControlProxyModule, MissionControlProxyModule,
OrchestratorModule, OrchestratorModule,
QueueNotificationsModule,
], ],
controllers: [AppController, CsrfController], controllers: [AppController, CsrfController],
providers: [ providers: [

View File

@@ -0,0 +1,120 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { NotFoundException } from "@nestjs/common";
import type { Response } from "express";
import { ConfigService } from "@nestjs/config";
import { Test, type TestingModule } from "@nestjs/testing";
import { QueueNotificationsController } from "./queue-notifications.controller";
import { QueueNotificationsService } from "./queue-notifications.service";
import { ApiKeyGuard } from "../common/guards/api-key.guard";
describe("QueueNotificationsController", () => {
let controller: QueueNotificationsController;
const mockService = {
listNotifications: vi.fn(),
streamNotifications: vi.fn(),
ackNotification: vi.fn(),
listTasks: vi.fn(),
};
const mockConfigService = {
get: vi.fn().mockReturnValue("coordinator-api-key"),
};
beforeEach(async () => {
vi.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
controllers: [QueueNotificationsController],
providers: [
{ provide: QueueNotificationsService, useValue: mockService },
{ provide: ConfigService, useValue: mockConfigService },
],
})
.overrideGuard(ApiKeyGuard)
.useValue({ canActivate: () => true })
.compile();
controller = module.get<QueueNotificationsController>(QueueNotificationsController);
});
it("returns notification objects", async () => {
mockService.listNotifications.mockResolvedValue([
{
id: "notif-1",
agent: "mosaic",
filename: "notif-1.json",
payload: { type: "task.ready" },
createdAt: new Date("2026-03-08T22:00:00.000Z"),
},
]);
await expect(controller.getNotifications()).resolves.toEqual([
expect.objectContaining({
id: "notif-1",
agent: "mosaic",
filename: "notif-1.json",
payload: { type: "task.ready" },
}),
]);
});
it("streams notifications through the response object", async () => {
const res = {
setHeader: vi.fn(),
flushHeaders: vi.fn(),
write: vi.fn(),
on: vi.fn(),
end: vi.fn(),
} as unknown as Response;
mockService.streamNotifications.mockResolvedValue(undefined);
await controller.streamNotifications(res);
expect(mockService.streamNotifications).toHaveBeenCalledWith(res);
});
it("acks a notification by id", async () => {
mockService.ackNotification.mockResolvedValue({ success: true, id: "notif-2" });
await expect(controller.ackNotification("notif-2")).resolves.toEqual({
success: true,
id: "notif-2",
});
});
it("surfaces ack errors", async () => {
mockService.ackNotification.mockRejectedValue(new NotFoundException("missing"));
await expect(controller.ackNotification("missing")).rejects.toThrow(NotFoundException);
});
it("returns parsed queue tasks", async () => {
mockService.listTasks.mockResolvedValue([
{
id: "task-1",
project: "mosaic-stack",
taskId: "MS24-API-001",
status: "pending",
description: "Build queue notifications module",
},
]);
await expect(controller.getTasks()).resolves.toEqual([
{
id: "task-1",
project: "mosaic-stack",
taskId: "MS24-API-001",
status: "pending",
description: "Build queue notifications module",
},
]);
});
it("uses ApiKeyGuard at the controller level", () => {
const guards = Reflect.getMetadata("__guards__", QueueNotificationsController) as unknown[];
expect(guards).toContain(ApiKeyGuard);
});
});

View File

@@ -0,0 +1,36 @@
import { Controller, Get, Param, Post, Res, UseGuards } from "@nestjs/common";
import type { Response } from "express";
import { SkipCsrf } from "../common/decorators/skip-csrf.decorator";
import { ApiKeyGuard } from "../common/guards/api-key.guard";
import {
QueueNotificationsService,
type QueueNotification,
type QueueTask,
} from "./queue-notifications.service";
@Controller("queue")
@UseGuards(ApiKeyGuard)
export class QueueNotificationsController {
constructor(private readonly queueNotificationsService: QueueNotificationsService) {}
@Get("notifications")
async getNotifications(): Promise<QueueNotification[]> {
return this.queueNotificationsService.listNotifications();
}
@Get("notifications/stream")
async streamNotifications(@Res() res: Response): Promise<void> {
await this.queueNotificationsService.streamNotifications(res);
}
@SkipCsrf()
@Post("notifications/:id/ack")
async ackNotification(@Param("id") id: string): Promise<{ success: true; id: string }> {
return this.queueNotificationsService.ackNotification(id);
}
@Get("tasks")
async getTasks(): Promise<QueueTask[]> {
return this.queueNotificationsService.listTasks();
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { AuthModule } from "../auth/auth.module";
import { ApiKeyGuard } from "../common/guards/api-key.guard";
import { QueueNotificationsController } from "./queue-notifications.controller";
import { QueueNotificationsService } from "./queue-notifications.service";
@Module({
imports: [ConfigModule, AuthModule],
controllers: [QueueNotificationsController],
providers: [QueueNotificationsService, ApiKeyGuard],
exports: [QueueNotificationsService],
})
export class QueueNotificationsModule {}

View File

@@ -0,0 +1,172 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ConfigService } from "@nestjs/config";
import { Logger, NotFoundException } from "@nestjs/common";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { execFile } from "node:child_process";
import { QueueNotificationsService } from "./queue-notifications.service";
vi.mock("node:child_process", () => ({
execFile: vi.fn(),
}));
describe("QueueNotificationsService", () => {
let service: QueueNotificationsService;
let inboxDir: string;
let configService: ConfigService;
beforeEach(async () => {
vi.clearAllMocks();
inboxDir = await mkdtemp(join(tmpdir(), "queue-notifications-"));
configService = {
get: vi.fn((key: string) => {
if (key === "MOSAIC_QUEUE_INBOX_DIR") {
return inboxDir;
}
if (key === "MOSAIC_QUEUE_CLI") {
return "/tmp/mosaic-queue-cli.js";
}
return undefined;
}),
} as unknown as ConfigService;
service = new QueueNotificationsService(configService);
});
afterEach(async () => {
vi.restoreAllMocks();
await rm(inboxDir, { recursive: true, force: true });
});
describe("onModuleInit", () => {
it("logs a warning when the inbox directory does not exist", async () => {
await rm(inboxDir, { recursive: true, force: true });
const warnSpy = vi.spyOn(Logger.prototype, "warn").mockImplementation(() => undefined);
await service.onModuleInit();
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("Queue notifications inbox directory does not exist")
);
});
});
describe("listNotifications", () => {
it("returns parsed notifications from agent inbox directories", async () => {
await mkdir(join(inboxDir, "mosaic"), { recursive: true });
await mkdir(join(inboxDir, "mosaic", "_acked"), { recursive: true });
await mkdir(join(inboxDir, "sage"), { recursive: true });
await writeFile(
join(inboxDir, "mosaic", "notif-1.json"),
JSON.stringify({ type: "task.ready", taskId: "MS24-API-001" })
);
await writeFile(
join(inboxDir, "mosaic", "_acked", "notif-ignored.json"),
JSON.stringify({ ignored: true })
);
await writeFile(join(inboxDir, "sage", "notif-2.json"), JSON.stringify({ type: "done" }));
const notifications = await service.listNotifications();
expect(notifications).toHaveLength(2);
expect(notifications).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: "notif-1",
agent: "mosaic",
filename: "notif-1.json",
payload: { type: "task.ready", taskId: "MS24-API-001" },
}),
expect.objectContaining({
id: "notif-2",
agent: "sage",
filename: "notif-2.json",
payload: { type: "done" },
}),
])
);
});
it("returns an empty array when the inbox directory is missing", async () => {
await rm(inboxDir, { recursive: true, force: true });
await expect(service.listNotifications()).resolves.toEqual([]);
});
});
describe("ackNotification", () => {
it("executes the queue CLI with node and ack args", async () => {
await mkdir(join(inboxDir, "mosaic"), { recursive: true });
await writeFile(join(inboxDir, "mosaic", "notif-3.json"), JSON.stringify({ ok: true }));
vi.mocked(execFile).mockImplementation(
(
_command: string,
_args: readonly string[],
callback: (error: Error | null, stdout: string, stderr: string) => void
) => callback(null, "acked", "")
);
await expect(service.ackNotification("notif-3")).resolves.toEqual({
success: true,
id: "notif-3",
});
expect(execFile).toHaveBeenCalledWith(
"node",
["/tmp/mosaic-queue-cli.js", "ack", "notif-3"],
expect.any(Function)
);
});
it("throws NotFoundException when the notification does not exist", async () => {
await expect(service.ackNotification("missing")).rejects.toThrow(NotFoundException);
expect(execFile).not.toHaveBeenCalled();
});
});
describe("listTasks", () => {
it("parses tab-separated CLI output", async () => {
vi.mocked(execFile).mockImplementation(
(
_command: string,
_args: readonly string[],
callback: (error: Error | null, stdout: string, stderr: string) => void
) =>
callback(
null,
[
"task-1\tmosaic-stack/MS24-API-001\t[pending]\tBuild queue notifications module",
"task-2\tmosaic-stack/MS24-API-002\t[done]\tWrite tests",
].join("\n"),
""
)
);
await expect(service.listTasks()).resolves.toEqual([
{
id: "task-1",
project: "mosaic-stack",
taskId: "MS24-API-001",
status: "pending",
description: "Build queue notifications module",
},
{
id: "task-2",
project: "mosaic-stack",
taskId: "MS24-API-002",
status: "done",
description: "Write tests",
},
]);
expect(execFile).toHaveBeenCalledWith(
"node",
["/tmp/mosaic-queue-cli.js", "list", "mosaic-stack"],
expect.any(Function)
);
});
});
});

View File

@@ -0,0 +1,231 @@
import {
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
OnModuleInit,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { execFile } from "node:child_process";
import { access, readdir, readFile, stat } from "node:fs/promises";
import { homedir } from "node:os";
import { basename, join } from "node:path";
import type { Response } from "express";
import chokidar from "chokidar";
export interface QueueNotification {
id: string;
agent: string;
filename: string;
payload: unknown;
createdAt: Date;
}
export interface QueueTask {
id: string;
project: string;
taskId: string;
status: string;
description: string;
}
@Injectable()
export class QueueNotificationsService implements OnModuleInit {
private readonly logger = new Logger(QueueNotificationsService.name);
constructor(private readonly configService: ConfigService) {}
async onModuleInit(): Promise<void> {
if (!(await this.inboxDirExists())) {
this.logger.warn(`Queue notifications inbox directory does not exist: ${this.getInboxDir()}`);
}
}
async listNotifications(): Promise<QueueNotification[]> {
const inboxDir = this.getInboxDir();
if (!(await this.inboxDirExists())) {
return [];
}
// Paths come from controlled config plus directory entries under the inbox root.
// eslint-disable-next-line security/detect-non-literal-fs-filename
const agentEntries = await readdir(inboxDir, { withFileTypes: true });
const notifications: QueueNotification[] = [];
for (const agentEntry of agentEntries) {
if (!agentEntry.isDirectory() || this.isIgnoredDirectory(agentEntry.name)) {
continue;
}
const agentDir = join(inboxDir, agentEntry.name);
// eslint-disable-next-line security/detect-non-literal-fs-filename
const files = await readdir(agentDir, { withFileTypes: true });
for (const fileEntry of files) {
if (!fileEntry.isFile() || !fileEntry.name.endsWith(".json")) {
continue;
}
const filePath = join(agentDir, fileEntry.name);
const [rawPayload, fileStats] = await Promise.all([
// eslint-disable-next-line security/detect-non-literal-fs-filename
readFile(filePath, "utf8"),
// eslint-disable-next-line security/detect-non-literal-fs-filename
stat(filePath),
]);
notifications.push({
id: basename(fileEntry.name, ".json"),
agent: agentEntry.name,
filename: fileEntry.name,
payload: JSON.parse(rawPayload) as unknown,
createdAt: fileStats.birthtime,
});
}
}
return notifications.sort(
(left, right) => right.createdAt.getTime() - left.createdAt.getTime()
);
}
async streamNotifications(res: Response): Promise<void> {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
if (typeof res.flushHeaders === "function") {
res.flushHeaders();
}
const emitNotifications = async (): Promise<void> => {
try {
const notifications = await this.listNotifications();
res.write(`data: ${JSON.stringify(notifications)}\n\n`);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
res.write(`event: error\n`);
res.write(`data: ${JSON.stringify({ error: message })}\n\n`);
}
};
await emitNotifications();
const watcher = chokidar.watch(this.getInboxDir(), {
ignoreInitial: true,
persistent: true,
ignored: (watchedPath: string) => {
return watchedPath.includes("/_acked/") || watchedPath.includes("/_dead-letter/");
},
});
watcher.on("add", () => {
void emitNotifications();
});
watcher.on("unlink", () => {
void emitNotifications();
});
res.on("close", () => {
void watcher.close();
res.end();
});
}
async ackNotification(id: string): Promise<{ success: true; id: string }> {
const notification = (await this.listNotifications()).find((entry) => entry.id === id);
if (!notification) {
throw new NotFoundException(`Queue notification ${id} not found`);
}
await this.execQueueCli(["ack", notification.id]);
return {
success: true,
id: notification.id,
};
}
async listTasks(): Promise<QueueTask[]> {
const stdout = await this.execQueueCli(["list", "mosaic-stack"]);
return stdout
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const [rawId = "", projectTaskId = "", rawStatus = "", description = ""] = line.split("\t");
const [project = "", taskId = ""] = projectTaskId.split("/");
return {
id: rawId,
project,
taskId,
status: rawStatus.replace(/^\[/, "").replace(/\]$/, ""),
description,
};
});
}
private async execQueueCli(args: string[]): Promise<string> {
const cliPath = this.getQueueCliPath();
return new Promise<string>((resolve, reject) => {
execFile("node", [cliPath, ...args], (error, stdout, stderr) => {
if (error) {
this.logger.error(
`Queue CLI command failed: node ${cliPath} ${args.join(" ")} | ${stderr || error.message}`
);
reject(
new InternalServerErrorException(`Queue CLI command failed: ${stderr || error.message}`)
);
return;
}
resolve(stdout);
});
});
}
private getInboxDir(): string {
return this.expandHomePath(
this.configService.get<string>("MOSAIC_QUEUE_INBOX_DIR") ??
"~/.openclaw/workspace/agent-inbox"
);
}
private getQueueCliPath(): string {
return this.expandHomePath(
this.configService.get<string>("MOSAIC_QUEUE_CLI") ?? "~/src/mosaic-queue/dist/cli.js"
);
}
private expandHomePath(value: string): string {
if (value === "~") {
return homedir();
}
if (value.startsWith("~/")) {
return join(homedir(), value.slice(2));
}
return value;
}
private async inboxDirExists(): Promise<boolean> {
try {
await access(this.getInboxDir());
return true;
} catch {
return false;
}
}
private isIgnoredDirectory(name: string): boolean {
return name === "_acked" || name === "_dead-letter";
}
}

View File

@@ -0,0 +1,57 @@
import { NextResponse } from "next/server";
const DEFAULT_ORCHESTRATOR_URL = "http://localhost:3001";
function getOrchestratorUrl(): string {
return (
process.env.ORCHESTRATOR_URL ??
process.env.NEXT_PUBLIC_ORCHESTRATOR_URL ??
process.env.NEXT_PUBLIC_API_URL ??
DEFAULT_ORCHESTRATOR_URL
);
}
export const dynamic = "force-dynamic";
export async function GET(): Promise<NextResponse> {
const orchestratorApiKey = process.env.ORCHESTRATOR_API_KEY;
if (!orchestratorApiKey) {
return NextResponse.json(
{ error: "ORCHESTRATOR_API_KEY is not configured on the web server." },
{ status: 503 }
);
}
try {
const upstream = await fetch(`${getOrchestratorUrl()}/api/queue/notifications/stream`, {
method: "GET",
headers: {
"X-API-Key": orchestratorApiKey,
Accept: "text/event-stream",
},
cache: "no-store",
});
if (!upstream.ok || upstream.body === null) {
const message = await upstream.text();
return new NextResponse(message || "Failed to connect to queue notifications stream", {
status: upstream.status || 502,
headers: {
"Content-Type": upstream.headers.get("Content-Type") ?? "text/plain; charset=utf-8",
},
});
}
return new NextResponse(upstream.body, {
status: upstream.status,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
} catch {
return NextResponse.json({ error: "Unable to reach orchestrator." }, { status: 502 });
}
}

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import { useEffect, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import Image from "next/image"; import Image from "next/image";
@@ -29,6 +29,10 @@ interface NavGroup {
items: NavItemConfig[]; items: NavItemConfig[];
} }
interface QueueNotification {
id: string;
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// SVG Icons (16x16 viewBox, stroke="currentColor", strokeWidth="1.5") // SVG Icons (16x16 viewBox, stroke="currentColor", strokeWidth="1.5")
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -685,6 +689,72 @@ function CollapseToggle({ collapsed, onToggle }: CollapseToggleProps): React.JSX
export function AppSidebar(): React.JSX.Element { export function AppSidebar(): React.JSX.Element {
const pathname = usePathname(); const pathname = usePathname();
const { collapsed, toggleCollapsed, mobileOpen, setMobileOpen, isMobile } = useSidebar(); const { collapsed, toggleCollapsed, mobileOpen, setMobileOpen, isMobile } = useSidebar();
const [missionControlBadgeCount, setMissionControlBadgeCount] = useState<number>(0);
useEffect(() => {
let isActive = true;
const loadNotificationCount = async (): Promise<void> => {
try {
const response = await fetch("/api/orchestrator/api/queue/notifications", {
method: "GET",
});
if (!response.ok) {
return;
}
const payload = (await response.json()) as QueueNotification[];
if (isActive) {
setMissionControlBadgeCount(Array.isArray(payload) ? payload.length : 0);
}
} catch {
// Ignore badge failures in the nav.
}
};
void loadNotificationCount();
if (typeof EventSource === "undefined") {
return (): void => {
isActive = false;
};
}
const source = new EventSource("/api/orchestrator/queue/notifications/stream");
source.onmessage = (event: MessageEvent<string>): void => {
try {
const payload = JSON.parse(event.data) as QueueNotification[];
if (isActive) {
setMissionControlBadgeCount(Array.isArray(payload) ? payload.length : 0);
}
} catch {
// Ignore malformed badge updates.
}
};
return (): void => {
isActive = false;
source.close();
};
}, []);
const navGroups = useMemo(
() =>
NAV_GROUPS.map((group) => ({
...group,
items: group.items.map((item) =>
item.href === "/mission-control" && missionControlBadgeCount > 0
? {
...item,
badge: { label: String(missionControlBadgeCount) },
}
: item
),
})),
[missionControlBadgeCount]
);
return ( return (
<> <>
@@ -722,7 +792,7 @@ export function AppSidebar(): React.JSX.Element {
}} }}
aria-label="Main navigation" aria-label="Main navigation"
> >
{NAV_GROUPS.map((group) => ( {navGroups.map((group) => (
<div key={group.label} style={{ marginBottom: "18px" }}> <div key={group.label} style={{ marginBottom: "18px" }}>
{/* Group label — hidden when collapsed */} {/* Group label — hidden when collapsed */}
{!collapsed && ( {!collapsed && (

View File

@@ -8,6 +8,7 @@ interface MockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
const mockGlobalAgentRoster = vi.fn(); const mockGlobalAgentRoster = vi.fn();
const mockMissionControlPanel = vi.fn(); const mockMissionControlPanel = vi.fn();
const mockQueueNotificationFeed = vi.fn();
vi.mock("@/components/mission-control/AuditLogDrawer", () => ({ vi.mock("@/components/mission-control/AuditLogDrawer", () => ({
AuditLogDrawer: ({ trigger }: { trigger: ReactNode }): React.JSX.Element => ( AuditLogDrawer: ({ trigger }: { trigger: ReactNode }): React.JSX.Element => (
@@ -31,6 +32,13 @@ vi.mock("@/components/mission-control/MissionControlPanel", () => ({
MIN_PANEL_COUNT: 1, MIN_PANEL_COUNT: 1,
})); }));
vi.mock("@/components/mission-control/QueueNotificationFeed", () => ({
QueueNotificationFeed: (props: unknown): React.JSX.Element => {
mockQueueNotificationFeed(props);
return <div data-testid="queue-notification-feed" />;
},
}));
vi.mock("@/components/ui/button", () => ({ vi.mock("@/components/ui/button", () => ({
Button: ({ children, ...props }: MockButtonProps): React.JSX.Element => ( Button: ({ children, ...props }: MockButtonProps): React.JSX.Element => (
<button {...props}>{children}</button> <button {...props}>{children}</button>
@@ -66,5 +74,6 @@ describe("MissionControlLayout", (): void => {
expect(region.querySelector("main")).toBeInTheDocument(); expect(region.querySelector("main")).toBeInTheDocument();
expect(screen.getByTestId("global-agent-roster")).toBeInTheDocument(); expect(screen.getByTestId("global-agent-roster")).toBeInTheDocument();
expect(screen.getByTestId("mission-control-panel")).toBeInTheDocument(); expect(screen.getByTestId("mission-control-panel")).toBeInTheDocument();
expect(screen.getByTestId("queue-notification-feed")).toBeInTheDocument();
}); });
}); });

View File

@@ -9,6 +9,7 @@ import {
MissionControlPanel, MissionControlPanel,
type PanelConfig, type PanelConfig,
} from "@/components/mission-control/MissionControlPanel"; } from "@/components/mission-control/MissionControlPanel";
import { QueueNotificationFeed } from "@/components/mission-control/QueueNotificationFeed";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
const INITIAL_PANELS: PanelConfig[] = [{}]; const INITIAL_PANELS: PanelConfig[] = [{}];
@@ -94,7 +95,7 @@ export function MissionControlLayout(): React.JSX.Element {
/> />
</header> </header>
<div className="grid min-h-0 flex-1 gap-4 xl:grid-cols-[280px_minmax(0,1fr)]"> <div className="grid min-h-0 flex-1 gap-4 xl:grid-cols-[280px_minmax(0,1fr)_320px]">
<aside className="h-full min-h-0"> <aside className="h-full min-h-0">
<GlobalAgentRoster <GlobalAgentRoster
onSelectSession={handleSelectSession} onSelectSession={handleSelectSession}
@@ -109,6 +110,9 @@ export function MissionControlLayout(): React.JSX.Element {
onExpandPanel={handleExpandPanel} onExpandPanel={handleExpandPanel}
/> />
</main> </main>
<aside className="h-full min-h-0">
<QueueNotificationFeed />
</aside>
</div> </div>
</section> </section>
); );

View File

@@ -0,0 +1,225 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { ButtonHTMLAttributes, HTMLAttributes, ReactNode } from "react";
vi.mock("date-fns", () => ({
formatDistanceToNow: (): string => "5 minutes ago",
}));
interface MockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
}
interface MockContainerProps extends HTMLAttributes<HTMLElement> {
children: ReactNode;
}
interface MockEventSourceInstance {
url: string;
onerror: ((event: Event) => void) | null;
onmessage: ((event: MessageEvent<string>) => void) | null;
close: ReturnType<typeof vi.fn>;
emitMessage: (payload: unknown) => void;
}
interface QueueNotification {
id: string;
agent: string;
filename: string;
payload: unknown;
createdAt: string;
}
const mockApiGet = vi.fn<(endpoint: string) => Promise<QueueNotification[]>>();
const mockApiPost = vi.fn<(endpoint: string) => Promise<{ success: true; id: string }>>();
const mockShowToast = vi.fn<(message: string, variant?: string) => void>();
let mockEventSourceInstances: MockEventSourceInstance[] = [];
const MockEventSource = vi.fn(function (this: MockEventSourceInstance, url: string): void {
this.url = url;
this.onerror = null;
this.onmessage = null;
this.close = vi.fn();
this.emitMessage = (payload: unknown): void => {
this.onmessage?.(new MessageEvent("message", { data: JSON.stringify(payload) }));
};
mockEventSourceInstances.push(this);
});
vi.mock("@/lib/api/client", () => ({
apiGet: (endpoint: string): Promise<QueueNotification[]> => mockApiGet(endpoint),
apiPost: (endpoint: string): Promise<{ success: true; id: string }> => mockApiPost(endpoint),
}));
vi.mock("@mosaic/ui", () => ({
useToast: (): { showToast: typeof mockShowToast; removeToast: ReturnType<typeof vi.fn> } => ({
showToast: mockShowToast,
removeToast: vi.fn(),
}),
}));
vi.mock("@/components/ui/button", () => ({
Button: ({ children, ...props }: MockButtonProps): React.JSX.Element => (
<button {...props}>{children}</button>
),
}));
vi.mock("@/components/ui/badge", () => ({
Badge: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<span {...props}>{children}</span>
),
}));
vi.mock("@/components/ui/card", () => ({
Card: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<section {...props}>{children}</section>
),
CardHeader: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<header {...props}>{children}</header>
),
CardContent: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<div {...props}>{children}</div>
),
CardTitle: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<h2 {...props}>{children}</h2>
),
}));
vi.mock("@/components/ui/collapsible", () => ({
Collapsible: ({ children }: MockContainerProps): React.JSX.Element => <div>{children}</div>,
}));
vi.mock("@/components/ui/scroll-area", () => ({
ScrollArea: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<div {...props}>{children}</div>
),
}));
vi.mock("@/components/ui/skeleton", () => ({
Skeleton: (props: HTMLAttributes<HTMLDivElement>): React.JSX.Element => <div {...props} />,
}));
import { QueueNotificationFeed } from "./QueueNotificationFeed";
function latestEventSource(): MockEventSourceInstance {
const instance = mockEventSourceInstances[mockEventSourceInstances.length - 1];
if (!instance) {
throw new Error("Expected an EventSource instance");
}
return instance;
}
function makeNotification(overrides: Partial<QueueNotification>): QueueNotification {
return {
id: "notif-1",
agent: "mosaic",
filename: "notif-1.json",
payload: {
taskId: "MS24-WEB-001",
eventType: "task.ready",
},
createdAt: "2026-03-08T23:00:00.000Z",
...overrides,
};
}
describe("QueueNotificationFeed", (): void => {
beforeEach((): void => {
vi.clearAllMocks();
vi.stubGlobal("EventSource", MockEventSource);
vi.stubGlobal("fetch", vi.fn());
mockEventSourceInstances = [];
mockApiGet.mockResolvedValue([]);
mockApiPost.mockResolvedValue({ success: true, id: "notif-1" });
});
afterEach((): void => {
vi.unstubAllGlobals();
});
it("loads and renders notifications grouped by agent", async (): Promise<void> => {
mockApiGet.mockResolvedValue([
makeNotification({ id: "notif-1", agent: "mosaic" }),
makeNotification({
id: "notif-2",
agent: "dyor",
payload: { taskId: "MS24-WEB-002", eventType: "task.blocked" },
}),
]);
render(<QueueNotificationFeed />);
await waitFor((): void => {
expect(mockApiGet).toHaveBeenCalledWith("/api/orchestrator/api/queue/notifications");
});
expect(screen.getByText("mosaic")).toBeInTheDocument();
expect(screen.getByText("dyor")).toBeInTheDocument();
expect(screen.getByText("MS24-WEB-001")).toBeInTheDocument();
expect(screen.getByText("task.ready")).toBeInTheDocument();
expect(screen.getAllByText("5 minutes ago")).toHaveLength(2);
expect(MockEventSource).toHaveBeenCalledWith("/api/orchestrator/queue/notifications/stream");
});
it("acknowledges a notification and removes it from the list", async (): Promise<void> => {
const user = userEvent.setup();
mockApiGet.mockResolvedValue([makeNotification({ id: "notif-ack" })]);
render(<QueueNotificationFeed />);
await waitFor((): void => {
expect(screen.getByText("MS24-WEB-001")).toBeInTheDocument();
});
await user.click(screen.getByRole("button", { name: "ACK notification MS24-WEB-001" }));
await waitFor((): void => {
expect(mockApiPost).toHaveBeenCalledWith(
"/api/orchestrator/api/queue/notifications/notif-ack/ack"
);
});
await waitFor((): void => {
expect(screen.getByText("No pending notifications")).toBeInTheDocument();
});
});
it("renders the empty state when there are no notifications", async (): Promise<void> => {
mockApiGet.mockResolvedValue([]);
render(<QueueNotificationFeed />);
await waitFor((): void => {
expect(screen.getByText("No pending notifications")).toBeInTheDocument();
});
});
it("refreshes the list when an SSE message arrives", async (): Promise<void> => {
mockApiGet.mockResolvedValue([makeNotification({ id: "notif-before" })]);
render(<QueueNotificationFeed />);
await waitFor((): void => {
expect(screen.getByText("MS24-WEB-001")).toBeInTheDocument();
});
act(() => {
latestEventSource().emitMessage([
makeNotification({
id: "notif-after",
agent: "sage",
payload: { taskId: "MS24-WEB-003", eventType: "task.failed" },
}),
]);
});
await waitFor((): void => {
expect(screen.getByText("sage")).toBeInTheDocument();
expect(screen.getByText("MS24-WEB-003")).toBeInTheDocument();
expect(screen.getByText("task.failed")).toBeInTheDocument();
});
});
});

View File

@@ -0,0 +1,332 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { formatDistanceToNow } from "date-fns";
import { BellOff, ChevronLeft, ChevronRight, Loader2 } from "lucide-react";
import { useToast } from "@mosaic/ui";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Collapsible } from "@/components/ui/collapsible";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Skeleton } from "@/components/ui/skeleton";
import { apiGet, apiPost } from "@/lib/api/client";
export interface QueueNotificationFeedProps {
className?: string;
}
interface QueueNotification {
id: string;
agent: string;
filename: string;
payload: unknown;
createdAt: string;
}
interface QueuePayloadRecord {
taskId?: unknown;
type?: unknown;
eventType?: unknown;
event?: unknown;
}
interface NotificationGroup {
agent: string;
notifications: QueueNotification[];
}
const NOTIFICATIONS_ENDPOINT = "/api/orchestrator/api/queue/notifications";
const NOTIFICATIONS_STREAM_ENDPOINT = "/api/orchestrator/queue/notifications/stream";
function joinClasses(...classes: (string | undefined)[]): string {
return classes.filter((value) => typeof value === "string" && value.length > 0).join(" ");
}
function asPayloadRecord(payload: unknown): QueuePayloadRecord | null {
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
return null;
}
return payload as QueuePayloadRecord;
}
function getNotificationTaskId(notification: QueueNotification): string {
const payload = asPayloadRecord(notification.payload);
return typeof payload?.taskId === "string" && payload.taskId.trim().length > 0
? payload.taskId
: notification.id;
}
function getNotificationEventType(notification: QueueNotification): string {
const payload = asPayloadRecord(notification.payload);
const candidates = [payload?.eventType, payload?.type, payload?.event];
for (const candidate of candidates) {
if (typeof candidate === "string" && candidate.trim().length > 0) {
return candidate;
}
}
return "notification";
}
function formatNotificationAge(createdAt: string): string {
const parsedDate = new Date(createdAt);
if (Number.isNaN(parsedDate.getTime())) {
return "just now";
}
return formatDistanceToNow(parsedDate, { addSuffix: true });
}
function groupNotificationsByAgent(notifications: QueueNotification[]): NotificationGroup[] {
const grouped = new Map<string, QueueNotification[]>();
for (const notification of notifications) {
const current = grouped.get(notification.agent) ?? [];
current.push(notification);
grouped.set(notification.agent, current);
}
return Array.from(grouped.entries())
.sort(([leftAgent], [rightAgent]) => leftAgent.localeCompare(rightAgent))
.map(([agent, items]) => ({
agent,
notifications: [...items].sort(
(left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime()
),
}));
}
export function QueueNotificationFeed({
className,
}: QueueNotificationFeedProps): React.JSX.Element {
const { showToast } = useToast();
const [notifications, setNotifications] = useState<QueueNotification[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [acknowledgingIds, setAcknowledgingIds] = useState<Record<string, boolean>>({});
const [isCollapsed, setIsCollapsed] = useState(false);
const [now, setNow] = useState(Date.now());
const refreshNotifications = useCallback(async (): Promise<void> => {
try {
const payload = await apiGet<QueueNotification[]>(NOTIFICATIONS_ENDPOINT);
setNotifications(payload);
setErrorMessage(null);
} catch (error) {
const message =
error instanceof Error && error.message.trim().length > 0
? error.message
: "Failed to load queue notifications.";
setErrorMessage(message);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
void refreshNotifications();
}, [refreshNotifications]);
useEffect(() => {
if (typeof EventSource === "undefined") {
return undefined;
}
const source = new EventSource(NOTIFICATIONS_STREAM_ENDPOINT);
source.onmessage = (event: MessageEvent<string>): void => {
try {
const payload = JSON.parse(event.data) as QueueNotification[];
setNotifications(payload);
setErrorMessage(null);
setIsLoading(false);
} catch {
setErrorMessage("Received an invalid notification stream payload.");
}
};
source.onerror = (): void => {
setErrorMessage((current) => current ?? "Queue notification stream disconnected.");
};
return (): void => {
source.close();
};
}, []);
useEffect(() => {
const intervalId = window.setInterval(() => {
setNow(Date.now());
}, 60_000);
return (): void => {
window.clearInterval(intervalId);
};
}, []);
const groupedNotifications = useMemo(
() => groupNotificationsByAgent(notifications),
[notifications]
);
const pendingCount = notifications.length;
const handleAck = useCallback(
async (notificationId: string): Promise<void> => {
setAcknowledgingIds((current) => ({
...current,
[notificationId]: true,
}));
try {
await apiPost<{ success: true; id: string }>(
`/api/orchestrator/api/queue/notifications/${encodeURIComponent(notificationId)}/ack`
);
setNotifications((current) => current.filter((item) => item.id !== notificationId));
} catch (error) {
const message =
error instanceof Error && error.message.trim().length > 0
? error.message
: "Failed to acknowledge notification.";
showToast(message, "error");
} finally {
setAcknowledgingIds((current) => {
const { [notificationId]: _omitted, ...remaining } = current;
return remaining;
});
}
},
[showToast]
);
return (
<Card className={joinClasses("flex h-full min-h-0 flex-col", className)}>
<CardHeader className="pb-2">
<div className="flex items-start justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<CardTitle className="text-base">Queue Notifications</CardTitle>
<Badge variant={pendingCount > 0 ? "status-info" : "secondary"}>{pendingCount}</Badge>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => {
setIsCollapsed((current) => !current);
}}
aria-label={isCollapsed ? "Expand queue notifications" : "Collapse queue notifications"}
title={isCollapsed ? "Expand queue notifications" : "Collapse queue notifications"}
>
{isCollapsed ? (
<ChevronLeft className="h-4 w-4" aria-hidden="true" />
) : (
<ChevronRight className="h-4 w-4" aria-hidden="true" />
)}
</Button>
</div>
</CardHeader>
<Collapsible open={!isCollapsed} className="min-h-0 flex-1">
{!isCollapsed ? (
<CardContent className="min-h-0 flex-1 px-3 pb-3">
{isLoading ? (
<ScrollArea className="h-full">
<div className="space-y-2 pr-1">
{Array.from({ length: 6 }).map((_, index) => (
<Skeleton
key={`queue-notification-skeleton-${String(index)}`}
className="h-14 w-full"
/>
))}
</div>
</ScrollArea>
) : errorMessage && notifications.length === 0 ? (
<div className="flex h-full items-center justify-center px-4 text-center text-sm text-red-500">
{errorMessage}
</div>
) : groupedNotifications.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-2 text-center text-sm text-muted-foreground">
<BellOff className="h-5 w-5" aria-hidden="true" />
<span>No pending notifications</span>
</div>
) : (
<ScrollArea className="h-full">
<div className="space-y-4 pr-1">
{groupedNotifications.map((group) => (
<section key={group.agent} className="space-y-2">
<div className="flex items-center justify-between gap-2">
<h3 className="text-sm font-semibold text-foreground">{group.agent}</h3>
<span className="text-xs text-muted-foreground">
{group.notifications.length}
</span>
</div>
<div className="space-y-2">
{group.notifications.map((notification) => {
const taskId = getNotificationTaskId(notification);
const eventType = getNotificationEventType(notification);
const isAcknowledging = acknowledgingIds[notification.id] ?? false;
return (
<article
key={notification.id}
className="rounded-lg border border-border/70 bg-card px-3 py-2"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<span className="font-mono text-xs text-foreground">
{taskId}
</span>
<Badge variant="secondary">{eventType}</Badge>
</div>
<time
className="block text-xs text-muted-foreground"
dateTime={notification.createdAt}
>
{formatNotificationAge(notification.createdAt)}
</time>
</div>
<Button
type="button"
variant="outline"
size="sm"
disabled={isAcknowledging}
onClick={() => {
void handleAck(notification.id);
}}
aria-label={`ACK notification ${taskId}`}
>
{isAcknowledging ? (
<span className="flex items-center gap-2">
<Loader2
className="h-4 w-4 animate-spin"
aria-hidden="true"
/>
ACK
</span>
) : (
"ACK"
)}
</Button>
</div>
</article>
);
})}
</div>
</section>
))}
</div>
</ScrollArea>
)}
</CardContent>
) : null}
</Collapsible>
<span className="sr-only" aria-live="polite">
{pendingCount} pending notifications, refreshed at {new Date(now).toISOString()}
</span>
</Card>
);
}

5
pnpm-lock.yaml generated
View File

@@ -162,6 +162,9 @@ importers:
bullmq: bullmq:
specifier: ^5.67.2 specifier: ^5.67.2
version: 5.67.2 version: 5.67.2
chokidar:
specifier: ^4.0.3
version: 4.0.3
class-transformer: class-transformer:
specifier: ^0.5.1 specifier: ^0.5.1
version: 0.5.1 version: 0.5.1
@@ -1625,7 +1628,6 @@ packages:
'@mosaicstack/telemetry-client@0.1.1': '@mosaicstack/telemetry-client@0.1.1':
resolution: {integrity: sha512-1udg6p4cs8rhQgQ2pKCfi7EpRlJieRRhA5CIqthRQ6HQZLgQ0wH+632jEulov3rlHSM1iplIQ+AAe5DWrvSkEA==, tarball: https://git.mosaicstack.dev/api/packages/mosaic/npm/%40mosaicstack%2Ftelemetry-client/-/0.1.1/telemetry-client-0.1.1.tgz} resolution: {integrity: sha512-1udg6p4cs8rhQgQ2pKCfi7EpRlJieRRhA5CIqthRQ6HQZLgQ0wH+632jEulov3rlHSM1iplIQ+AAe5DWrvSkEA==, tarball: https://git.mosaicstack.dev/api/packages/mosaic/npm/%40mosaicstack%2Ftelemetry-client/-/0.1.1/telemetry-client-0.1.1.tgz}
engines: {node: '>=18'}
'@mrleebo/prisma-ast@0.13.1': '@mrleebo/prisma-ast@0.13.1':
resolution: {integrity: sha512-XyroGQXcHrZdvmrGJvsA9KNeOOgGMg1Vg9OlheUsBOSKznLMDl+YChxbkboRHvtFYJEMRYmlV3uoo/njCw05iw==} resolution: {integrity: sha512-XyroGQXcHrZdvmrGJvsA9KNeOOgGMg1Vg9OlheUsBOSKznLMDl+YChxbkboRHvtFYJEMRYmlV3uoo/njCw05iw==}
@@ -5176,6 +5178,7 @@ packages:
glob@10.5.0: glob@10.5.0:
resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
hasBin: true hasBin: true
glob@13.0.0: glob@13.0.0: