Compare commits

..

16 Commits

Author SHA1 Message Date
90d2fa7563 fix(web): MS23-P2 fix broken lint/typecheck on main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 14:55:04 -06:00
31af6c26ec Merge pull request 'feat(web): MS23-P2-008 Panel grid responsive layout' (#731) from feat/ms23-p2-grid into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 20:48:36 +00:00
e4f942dde7 feat(web): MS23-P2-008 panel grid responsive layout
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 14:47:39 -06:00
4ea31c5749 Merge pull request 'feat: MS23-P2-007 AuditLogDrawer + audit log endpoint' (#730) from feat/ms23-p2-audit into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 20:40:21 +00:00
4792f7b70a feat: MS23-P2-007 AuditLogDrawer + audit log endpoint
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 14:40:06 -06:00
571094a099 Merge pull request 'feat(web): MS23-P2-004 Panel operator controls' (#729) from feat/ms23-p2-controls into main
Some checks failed
ci/woodpecker/push/ci Pipeline failed
2026-03-07 20:35:53 +00:00
adef5bdbb2 feat(web): MS23-P2-004 panel operator controls
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 14:34:31 -06:00
eb771d795a Merge pull request 'feat(web): MS23-P2-003 BargeInInput component' (#728) from feat/ms23-p2-barge into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 20:33:39 +00:00
c9aff531ea Merge pull request 'feat(web): MS23-P2-006 KillAllDialog confirmation modal' (#727) from feat/ms23-p2-killall into main
Some checks failed
ci/woodpecker/push/ci Pipeline failed
2026-03-07 20:33:03 +00:00
b2c751caca feat(web): MS23-P2-003 BargeInInput component
Some checks failed
ci/woodpecker/push/ci Pipeline failed
2026-03-07 14:32:12 -06:00
cd28428cf2 feat(web): MS23-P2-006 KillAllDialog confirmation modal
Some checks failed
ci/woodpecker/push/ci Pipeline failed
2026-03-07 14:31:38 -06:00
2c36569f85 Merge pull request 'feat(web): MS23-P2-005 GlobalAgentRoster sidebar tree' (#726) from feat/ms23-p2-roster into main
Some checks failed
ci/woodpecker/push/ci Pipeline failed
2026-03-07 20:20:17 +00:00
7c086db7e4 feat(web): MS23-P2-005 GlobalAgentRoster sidebar tree
Some checks failed
ci/woodpecker/push/ci Pipeline failed
2026-03-07 14:19:05 -06:00
577e6141e0 Merge pull request 'feat(web): MS23-P2-002 OrchestratorPanel SSE stream component' (#725) from feat/ms23-p2-panel into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 20:17:56 +00:00
631ba499e3 feat(web): MS23-P2-002 OrchestratorPanel SSE stream component
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 14:14:57 -06:00
a61106c24a Merge pull request 'feat(web): MS23-P2-001 Mission Control page route + layout shell' (#724) from feat/ms23-p2-page into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 20:00:55 +00:00
18 changed files with 2083 additions and 34 deletions

View File

@@ -0,0 +1,21 @@
import { Type } from "class-transformer";
import { IsInt, IsOptional, IsString, Max, Min } from "class-validator";
export class GetMissionControlAuditLogQueryDto {
@IsOptional()
@IsString()
sessionId?: string;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page = 1;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(200)
limit = 50;
}

View File

@@ -18,9 +18,10 @@ import type { AgentMessage, AgentSession, InjectResult } from "@mosaic/shared";
import { Observable } from "rxjs"; import { Observable } from "rxjs";
import { AuthGuard } from "../../auth/guards/auth.guard"; import { AuthGuard } from "../../auth/guards/auth.guard";
import { InjectAgentDto } from "../agents/dto/inject-agent.dto"; import { InjectAgentDto } from "../agents/dto/inject-agent.dto";
import { GetMissionControlAuditLogQueryDto } from "./dto/get-mission-control-audit-log-query.dto";
import { GetMissionControlMessagesQueryDto } from "./dto/get-mission-control-messages-query.dto"; import { GetMissionControlMessagesQueryDto } from "./dto/get-mission-control-messages-query.dto";
import { KillSessionDto } from "./dto/kill-session.dto"; import { KillSessionDto } from "./dto/kill-session.dto";
import { MissionControlService } from "./mission-control.service"; import { MissionControlService, type MissionControlAuditLogPage } from "./mission-control.service";
const DEFAULT_OPERATOR_ID = "mission-control"; const DEFAULT_OPERATOR_ID = "mission-control";
@@ -61,6 +62,14 @@ export class MissionControlController {
return { messages }; return { messages };
} }
@Get("audit-log")
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
getAuditLog(
@Query() query: GetMissionControlAuditLogQueryDto
): Promise<MissionControlAuditLogPage> {
return this.missionControlService.getAuditLog(query.sessionId, query.page, query.limit);
}
@Post("sessions/:sessionId/inject") @Post("sessions/:sessionId/inject")
@HttpCode(200) @HttpCode(200)
@UsePipes(new ValidationPipe({ transform: true, whitelist: true })) @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))

View File

@@ -8,6 +8,24 @@ type MissionControlAction = "inject" | "pause" | "resume" | "kill";
const DEFAULT_OPERATOR_ID = "mission-control"; const DEFAULT_OPERATOR_ID = "mission-control";
export interface AuditLogEntry {
id: string;
userId: string;
sessionId: string;
provider: string;
action: string;
content: string | null;
metadata: Prisma.JsonValue;
createdAt: Date;
}
export interface MissionControlAuditLogPage {
items: AuditLogEntry[];
total: number;
page: number;
pages: number;
}
@Injectable() @Injectable()
export class MissionControlService { export class MissionControlService {
constructor( constructor(
@@ -33,6 +51,35 @@ export class MissionControlService {
return provider.getMessages(sessionId, limit, before); return provider.getMessages(sessionId, limit, before);
} }
async getAuditLog(
sessionId: string | undefined,
page: number,
limit: number
): Promise<MissionControlAuditLogPage> {
const normalizedSessionId = sessionId?.trim();
const where: Prisma.OperatorAuditLogWhereInput =
normalizedSessionId && normalizedSessionId.length > 0
? { sessionId: normalizedSessionId }
: {};
const [total, items] = await this.prisma.$transaction([
this.prisma.operatorAuditLog.count({ where }),
this.prisma.operatorAuditLog.findMany({
where,
orderBy: { createdAt: "desc" },
skip: (page - 1) * limit,
take: limit,
}),
]);
return {
items,
total,
page,
pages: total === 0 ? 0 : Math.ceil(total / limit),
};
}
async injectMessage( async injectMessage(
sessionId: string, sessionId: string,
message: string, message: string,

View File

@@ -132,7 +132,7 @@ describe("KanbanPage add task flow", (): void => {
}); });
// Click the "+ Add task" button in the To Do column // Click the "+ Add task" button in the To Do column
const addTaskButtons = screen.getAllByRole("button", { name: /\+ Add task/i }); const addTaskButtons = await screen.findAllByRole("button", { name: /\+ Add task/i });
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
await user.click(addTaskButtons[0]!); // First column is "To Do" await user.click(addTaskButtons[0]!); // First column is "To Do"
@@ -165,7 +165,7 @@ describe("KanbanPage add task flow", (): void => {
}); });
// Click the "+ Add task" button // Click the "+ Add task" button
const addTaskButtons = screen.getAllByRole("button", { name: /\+ Add task/i }); const addTaskButtons = await screen.findAllByRole("button", { name: /\+ Add task/i });
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
await user.click(addTaskButtons[0]!); await user.click(addTaskButtons[0]!);

View File

@@ -0,0 +1,322 @@
"use client";
import { isValidElement, useEffect, useMemo, useState } from "react";
import type { ReactNode } from "react";
import { format } from "date-fns";
import { useQuery } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import type { BadgeVariant } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import { apiGet } from "@/lib/api/client";
const AUDIT_LOG_REFRESH_INTERVAL_MS = 10_000;
const AUDIT_LOG_PAGE_SIZE = 50;
const SUMMARY_MAX_LENGTH = 120;
interface AuditLogDrawerProps {
sessionId?: string;
trigger: ReactNode;
}
interface AuditLogEntry {
id: string;
userId: string;
sessionId: string;
provider: string;
action: string;
content: string | null;
metadata: unknown;
createdAt: string;
}
interface AuditLogResponse {
items: AuditLogEntry[];
total: number;
page: number;
pages: number;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function truncateText(value: string, maxLength: number): string {
if (value.length <= maxLength) {
return value;
}
return `${value.slice(0, maxLength - 1)}`;
}
function truncateSessionId(sessionId: string): string {
return sessionId.slice(0, 8);
}
function formatTimestamp(value: string): string {
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) {
return "Unknown";
}
return format(parsed, "yyyy-MM-dd HH:mm:ss");
}
function stringifyPayloadValue(value: unknown): string {
if (typeof value === "string") {
return value;
}
if (typeof value === "number" || typeof value === "boolean") {
return String(value);
}
try {
return JSON.stringify(value);
} catch {
return "[unserializable]";
}
}
function getPayloadSummary(entry: AuditLogEntry): string {
const metadata = isRecord(entry.metadata) ? entry.metadata : undefined;
const payload = metadata && isRecord(metadata.payload) ? metadata.payload : undefined;
if (typeof entry.content === "string" && entry.content.trim().length > 0) {
return truncateText(entry.content.trim(), SUMMARY_MAX_LENGTH);
}
if (payload) {
const summary = Object.entries(payload)
.map(([key, value]) => `${key}=${stringifyPayloadValue(value)}`)
.join(", ");
if (summary.length > 0) {
return truncateText(summary, SUMMARY_MAX_LENGTH);
}
}
return "—";
}
function getActionVariant(action: string): BadgeVariant {
switch (action) {
case "inject":
return "badge-blue";
case "pause":
return "status-warning";
case "resume":
return "status-success";
case "kill":
return "status-error";
default:
return "status-neutral";
}
}
async function fetchAuditLog(
sessionId: string | undefined,
page: number
): Promise<AuditLogResponse> {
const params = new URLSearchParams({
page: String(page),
limit: String(AUDIT_LOG_PAGE_SIZE),
});
const normalizedSessionId = sessionId?.trim();
if (normalizedSessionId && normalizedSessionId.length > 0) {
params.set("sessionId", normalizedSessionId);
}
return apiGet<AuditLogResponse>(`/api/mission-control/audit-log?${params.toString()}`);
}
export function AuditLogDrawer({ sessionId, trigger }: AuditLogDrawerProps): React.JSX.Element {
const [open, setOpen] = useState(false);
const [page, setPage] = useState(1);
const triggerElement = useMemo(
() =>
isValidElement(trigger) ? (
trigger
) : (
<Button variant="outline" size="sm">
{trigger}
</Button>
),
[trigger]
);
const auditLogQuery = useQuery<AuditLogResponse>({
queryKey: ["mission-control", "audit-log", sessionId ?? "all", page],
queryFn: async (): Promise<AuditLogResponse> => fetchAuditLog(sessionId, page),
enabled: open,
refetchInterval: open ? AUDIT_LOG_REFRESH_INTERVAL_MS : false,
});
useEffect(() => {
if (open) {
setPage(1);
}
}, [open, sessionId]);
useEffect(() => {
const pages = auditLogQuery.data?.pages;
if (pages !== undefined && pages > 0 && page > pages) {
setPage(pages);
}
}, [auditLogQuery.data?.pages, page]);
const totalItems = auditLogQuery.data?.total ?? 0;
const totalPages = auditLogQuery.data?.pages ?? 0;
const items = auditLogQuery.data?.items ?? [];
const canGoPrevious = page > 1;
const canGoNext = totalPages > 0 && page < totalPages;
const errorMessage =
auditLogQuery.error instanceof Error ? auditLogQuery.error.message : "Failed to load audit log";
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>{triggerElement}</SheetTrigger>
<SheetContent className="sm:max-w-[920px]">
<SheetHeader>
<div className="flex items-center justify-between gap-3">
<SheetTitle>Audit Log</SheetTitle>
{auditLogQuery.isFetching ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden="true" />
) : null}
</div>
<SheetDescription>
{sessionId
? `Showing actions for session ${sessionId}.`
: "Showing operator actions across all mission control sessions."}
</SheetDescription>
</SheetHeader>
<div className="mt-4 flex min-h-0 flex-1 flex-col gap-3">
<div className="rounded-md border border-border/70">
<ScrollArea className="h-[64vh]">
<table className="w-full min-w-[760px] border-collapse text-sm">
<thead className="sticky top-0 z-10 bg-muted/90">
<tr>
<th className="px-3 py-2 text-left font-medium text-muted-foreground">
Timestamp
</th>
<th className="px-3 py-2 text-left font-medium text-muted-foreground">
Action
</th>
<th className="px-3 py-2 text-left font-medium text-muted-foreground">
Session
</th>
<th className="px-3 py-2 text-left font-medium text-muted-foreground">
Operator
</th>
<th className="px-3 py-2 text-left font-medium text-muted-foreground">
Payload
</th>
</tr>
</thead>
<tbody>
{auditLogQuery.isLoading ? (
<tr>
<td
colSpan={5}
className="px-3 py-6 text-center text-sm text-muted-foreground"
>
Loading audit log...
</td>
</tr>
) : auditLogQuery.error ? (
<tr>
<td colSpan={5} className="px-3 py-6 text-center text-sm text-red-500">
{errorMessage}
</td>
</tr>
) : items.length === 0 ? (
<tr>
<td
colSpan={5}
className="px-3 py-6 text-center text-sm text-muted-foreground"
>
No audit entries found.
</td>
</tr>
) : (
items.map((entry) => {
const payloadSummary = getPayloadSummary(entry);
return (
<tr key={entry.id} className="border-t border-border/60 align-top">
<td className="px-3 py-2 font-mono text-xs text-muted-foreground">
{formatTimestamp(entry.createdAt)}
</td>
<td className="px-3 py-2">
<Badge variant={getActionVariant(entry.action)} className="capitalize">
{entry.action}
</Badge>
</td>
<td className="px-3 py-2 font-mono text-xs" title={entry.sessionId}>
{truncateSessionId(entry.sessionId)}
</td>
<td
className="px-3 py-2 text-xs text-muted-foreground"
title={entry.userId}
>
{entry.userId}
</td>
<td className="px-3 py-2 text-xs" title={payloadSummary}>
{payloadSummary}
</td>
</tr>
);
})
)}
</tbody>
</table>
</ScrollArea>
</div>
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">{totalItems} total entries</p>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={!canGoPrevious || auditLogQuery.isFetching}
onClick={() => {
setPage((currentPage) => Math.max(1, currentPage - 1));
}}
>
Previous
</Button>
<span className="text-xs text-muted-foreground">
Page {page} of {Math.max(totalPages, 1)}
</span>
<Button
variant="outline"
size="sm"
disabled={!canGoNext || auditLogQuery.isFetching}
onClick={() => {
setPage((currentPage) => currentPage + 1);
}}
>
Next
</Button>
</div>
</div>
</div>
</SheetContent>
</Sheet>
);
}

View File

@@ -0,0 +1,147 @@
"use client";
import { useCallback, useState, type KeyboardEvent } from "react";
import { Loader2 } from "lucide-react";
import { useToast } from "@mosaic/ui";
import { Button } from "@/components/ui/button";
import { apiPost } from "@/lib/api/client";
const MAX_ROWS = 4;
const TEXTAREA_MAX_HEIGHT_REM = 6.5;
interface BargeInMutationResponse {
message?: string;
}
export interface BargeInInputProps {
sessionId: string;
onSent?: () => void;
}
function getErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return "Failed to send message to the session.";
}
export function BargeInInput({ sessionId, onSent }: BargeInInputProps): React.JSX.Element {
const { showToast } = useToast();
const [content, setContent] = useState("");
const [pauseBeforeSend, setPauseBeforeSend] = useState(false);
const [isSending, setIsSending] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const handleSend = useCallback(async (): Promise<void> => {
const trimmedContent = content.trim();
if (!trimmedContent || isSending) {
return;
}
const encodedSessionId = encodeURIComponent(sessionId);
const baseEndpoint = `/api/mission-control/sessions/${encodedSessionId}`;
let didPause = false;
let didInject = false;
setIsSending(true);
setErrorMessage(null);
try {
if (pauseBeforeSend) {
await apiPost<BargeInMutationResponse>(`${baseEndpoint}/pause`);
didPause = true;
}
await apiPost<BargeInMutationResponse>(`${baseEndpoint}/inject`, { content: trimmedContent });
didInject = true;
setContent("");
onSent?.();
} catch (error) {
const message = getErrorMessage(error);
setErrorMessage(message);
showToast(message, "error");
} finally {
if (didPause) {
try {
await apiPost<BargeInMutationResponse>(`${baseEndpoint}/resume`);
} catch (resumeError) {
const resumeMessage = getErrorMessage(resumeError);
const message = didInject
? `Message sent, but failed to resume session: ${resumeMessage}`
: `Failed to resume session: ${resumeMessage}`;
setErrorMessage(message);
showToast(message, "error");
}
}
setIsSending(false);
}
}, [content, isSending, onSent, pauseBeforeSend, sessionId, showToast]);
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>): void => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
void handleSend();
}
},
[handleSend]
);
const isSendDisabled = isSending || content.trim().length === 0;
return (
<div className="space-y-2">
<textarea
value={content}
onChange={(event) => {
setContent(event.target.value);
}}
onKeyDown={handleKeyDown}
disabled={isSending}
rows={MAX_ROWS}
placeholder="Inject a message into this session..."
className="block w-full resize-y rounded-md border border-border bg-background px-3 py-2 text-sm leading-5 text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-60"
style={{ maxHeight: `${String(TEXTAREA_MAX_HEIGHT_REM)}rem` }}
aria-label="Inject message"
/>
<div className="flex items-center justify-between gap-3">
<label className="flex items-center gap-2 text-sm text-muted-foreground">
<input
type="checkbox"
checked={pauseBeforeSend}
onChange={(event) => {
setPauseBeforeSend(event.target.checked);
}}
disabled={isSending}
className="h-4 w-4 rounded border-border"
/>
<span>Pause before send</span>
</label>
<Button
type="button"
variant="primary"
size="sm"
disabled={isSendDisabled}
onClick={() => {
void handleSend();
}}
>
{isSending ? (
<span className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
Sending...
</span>
) : (
"Send"
)}
</Button>
</div>
{errorMessage ? (
<p role="alert" className="text-sm text-red-500">
{errorMessage}
</p>
) : null}
</div>
);
}

View File

@@ -1,15 +1,291 @@
"use client"; "use client";
import { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AgentSession } from "@mosaic/shared";
import { ChevronRight, Loader2, X } from "lucide-react";
import { KillAllDialog } from "@/components/mission-control/KillAllDialog";
import { Badge } from "@/components/ui/badge";
import type { BadgeVariant } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; 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";
const SESSIONS_QUERY_KEY = ["mission-control", "sessions"] as const;
const SESSIONS_POLL_INTERVAL_MS = 5_000;
type MissionControlSessionStatus = AgentSession["status"] | "killed";
interface MissionControlSession extends Omit<AgentSession, "status" | "createdAt" | "updatedAt"> {
status: MissionControlSessionStatus;
createdAt: string | Date;
updatedAt: string | Date;
}
interface SessionsPayload {
sessions: MissionControlSession[];
}
interface ProviderSessionGroup {
providerId: string;
providerType: string;
sessions: MissionControlSession[];
}
export interface GlobalAgentRosterProps {
onSelectSession?: (sessionId: string) => void;
selectedSessionId?: string | undefined;
}
function getStatusVariant(status: MissionControlSessionStatus): BadgeVariant {
switch (status) {
case "active":
return "status-success";
case "paused":
return "status-warning";
case "killed":
return "status-error";
default:
return "status-neutral";
}
}
function truncateSessionId(sessionId: string): string {
return sessionId.slice(0, 8);
}
function resolveProviderName(providerId: string, providerType: string): string {
return providerId === providerType ? providerId : `${providerId} (${providerType})`;
}
function groupByProvider(sessions: MissionControlSession[]): ProviderSessionGroup[] {
const grouped = new Map<string, ProviderSessionGroup>();
for (const session of sessions) {
const existing = grouped.get(session.providerId);
if (existing) {
existing.sessions.push(session);
continue;
}
grouped.set(session.providerId, {
providerId: session.providerId,
providerType: session.providerType,
sessions: [session],
});
}
return Array.from(grouped.values()).sort((a, b) => a.providerId.localeCompare(b.providerId));
}
async function fetchSessions(): Promise<MissionControlSession[]> {
const payload = await apiGet<MissionControlSession[] | SessionsPayload>(
"/api/mission-control/sessions"
);
return Array.isArray(payload) ? payload : payload.sessions;
}
function toKillAllSessions(sessions: MissionControlSession[]): AgentSession[] {
return sessions
.filter(
(session): session is MissionControlSession & { status: AgentSession["status"] } =>
session.status !== "killed"
)
.map((session) => ({
...session,
createdAt:
session.createdAt instanceof Date ? session.createdAt : new Date(session.createdAt),
updatedAt:
session.updatedAt instanceof Date ? session.updatedAt : new Date(session.updatedAt),
}));
}
export function GlobalAgentRoster({
onSelectSession,
selectedSessionId,
}: GlobalAgentRosterProps): React.JSX.Element {
const queryClient = useQueryClient();
const [openProviders, setOpenProviders] = useState<Record<string, boolean>>({});
const sessionsQuery = useQuery<MissionControlSession[]>({
queryKey: SESSIONS_QUERY_KEY,
queryFn: fetchSessions,
refetchInterval: SESSIONS_POLL_INTERVAL_MS,
});
const killMutation = useMutation({
mutationFn: async (sessionId: string): Promise<string> => {
await apiPost<{ message: string }>(`/api/mission-control/sessions/${sessionId}/kill`, {
force: false,
});
return sessionId;
},
onSuccess: (): void => {
void queryClient.invalidateQueries({ queryKey: SESSIONS_QUERY_KEY });
},
});
const groupedSessions = useMemo(
() => groupByProvider(sessionsQuery.data ?? []),
[sessionsQuery.data]
);
const killAllSessions = useMemo(
() => toKillAllSessions(sessionsQuery.data ?? []),
[sessionsQuery.data]
);
const totalSessionCount = sessionsQuery.data?.length ?? 0;
const pendingKillSessionId = killMutation.isPending ? killMutation.variables : undefined;
const toggleProvider = (providerId: string): void => {
setOpenProviders((prev) => ({
...prev,
[providerId]: !(prev[providerId] ?? true),
}));
};
const isProviderOpen = (providerId: string): boolean => openProviders[providerId] ?? true;
const handleKillAllComplete = (): void => {
void queryClient.invalidateQueries({ queryKey: SESSIONS_QUERY_KEY });
};
export function GlobalAgentRoster(): React.JSX.Element {
return ( return (
<Card className="flex h-full min-h-0 flex-col"> <Card className="flex h-full min-h-0 flex-col">
<CardHeader> <CardHeader className="pb-2">
<CardTitle className="text-base">Agent Roster</CardTitle> <CardTitle className="flex items-center justify-between gap-2 text-base">
<span>Agent Roster</span>
<div className="flex items-center gap-2">
{totalSessionCount > 0 ? (
<KillAllDialog sessions={killAllSessions} onComplete={handleKillAllComplete} />
) : null}
{sessionsQuery.isFetching && !sessionsQuery.isLoading ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden="true" />
) : null}
</div>
</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="flex flex-1 items-center justify-center text-sm text-muted-foreground"> <CardContent className="min-h-0 flex-1 px-3 pb-3">
No active agents {sessionsQuery.isLoading ? (
<ScrollArea className="h-full">
<div className="space-y-2 pr-1">
{Array.from({ length: 6 }).map((_, index) => (
<Skeleton key={`roster-skeleton-${String(index)}`} className="h-10 w-full" />
))}
</div>
</ScrollArea>
) : sessionsQuery.error ? (
<div className="flex h-full items-center justify-center text-center text-sm text-red-500">
Failed to load agents: {sessionsQuery.error.message}
</div>
) : groupedSessions.length === 0 ? (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
No active agents
</div>
) : (
<ScrollArea className="h-full">
<div className="space-y-3 pr-1">
{groupedSessions.map((group) => {
const providerOpen = isProviderOpen(group.providerId);
return (
<Collapsible key={group.providerId} open={providerOpen} className="space-y-1">
<button
type="button"
onClick={() => {
toggleProvider(group.providerId);
}}
className="flex w-full items-center gap-2 rounded-md px-1 py-1 text-left text-sm hover:bg-muted/40"
aria-expanded={providerOpen}
>
<ChevronRight
className={`h-4 w-4 text-muted-foreground transition-transform ${providerOpen ? "rotate-90" : ""}`}
aria-hidden="true"
/>
<span className="font-medium">
{resolveProviderName(group.providerId, group.providerType)}
</span>
<span className="ml-auto text-xs text-muted-foreground">
{group.sessions.length}
</span>
</button>
{providerOpen ? (
<div className="space-y-1 pl-2">
{group.sessions.map((session) => {
const isSelected = selectedSessionId === session.id;
const isKilling = pendingKillSessionId === session.id;
return (
<div
key={session.id}
role="button"
tabIndex={0}
onClick={() => {
onSelectSession?.(session.id);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
onSelectSession?.(session.id);
}
}}
className="flex items-center justify-between gap-2 rounded-md border border-transparent px-2 py-1.5 transition-colors hover:bg-muted/40"
style={
isSelected
? {
borderColor: "rgba(47, 128, 255, 0.35)",
backgroundColor: "rgba(47, 128, 255, 0.08)",
}
: undefined
}
>
<div className="flex min-w-0 items-center gap-2">
<span className="font-mono text-xs" title={session.id}>
{truncateSessionId(session.id)}
</span>
<Badge
variant={getStatusVariant(session.status)}
className="capitalize"
>
{session.status}
</Badge>
</div>
<Button
variant="ghost"
size="sm"
className="h-7 min-h-7 w-7 min-w-7 p-0"
disabled={isKilling}
onClick={(event) => {
event.stopPropagation();
killMutation.mutate(session.id);
}}
aria-label={`Kill session ${truncateSessionId(session.id)}`}
>
{isKilling ? (
<Loader2
className="h-3.5 w-3.5 animate-spin"
aria-hidden="true"
/>
) : (
<X className="h-3.5 w-3.5" aria-hidden="true" />
)}
</Button>
</div>
);
})}
</div>
) : null}
</Collapsible>
);
})}
</div>
</ScrollArea>
)}
</CardContent> </CardContent>
</Card> </Card>
); );

View File

@@ -0,0 +1,224 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import type { AgentSession } from "@mosaic/shared";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { apiPost } from "@/lib/api/client";
const CONFIRM_TEXT = "KILL ALL";
const AUTO_CLOSE_DELAY_MS = 2_000;
type KillScope = "internal" | "all";
export interface KillAllDialogProps {
sessions: AgentSession[];
onComplete?: () => void;
}
export function KillAllDialog({ sessions, onComplete }: KillAllDialogProps): React.JSX.Element {
const [open, setOpen] = useState(false);
const [scope, setScope] = useState<KillScope>("internal");
const [confirmationInput, setConfirmationInput] = useState("");
const [isKilling, setIsKilling] = useState(false);
const [completedCount, setCompletedCount] = useState(0);
const [targetCount, setTargetCount] = useState(0);
const [successCount, setSuccessCount] = useState<number | null>(null);
const closeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const internalSessions = useMemo(
() => sessions.filter((session) => session.providerType.toLowerCase() === "internal"),
[sessions]
);
const scopedSessions = useMemo(
() => (scope === "all" ? sessions : internalSessions),
[scope, sessions, internalSessions]
);
const hasConfirmation = confirmationInput === CONFIRM_TEXT;
const isConfirmDisabled =
isKilling || successCount !== null || !hasConfirmation || scopedSessions.length === 0;
useEffect((): (() => void) => {
return (): void => {
if (closeTimeoutRef.current !== null) {
clearTimeout(closeTimeoutRef.current);
}
};
}, []);
const resetState = (): void => {
setScope("internal");
setConfirmationInput("");
setIsKilling(false);
setCompletedCount(0);
setTargetCount(0);
setSuccessCount(null);
};
const handleOpenChange = (nextOpen: boolean): void => {
if (!nextOpen && isKilling) {
return;
}
if (!nextOpen) {
if (closeTimeoutRef.current !== null) {
clearTimeout(closeTimeoutRef.current);
}
resetState();
}
setOpen(nextOpen);
};
const handleKillAll = async (): Promise<void> => {
if (isConfirmDisabled) {
return;
}
const targetSessions = [...scopedSessions];
setIsKilling(true);
setCompletedCount(0);
setTargetCount(targetSessions.length);
setSuccessCount(null);
const killRequests = targetSessions.map(async (session) => {
try {
await apiPost<{ message: string }>(`/api/mission-control/sessions/${session.id}/kill`, {
force: true,
});
return true;
} catch {
return false;
} finally {
setCompletedCount((currentCount) => currentCount + 1);
}
});
const results = await Promise.all(killRequests);
const successfulKills = results.filter(Boolean).length;
setIsKilling(false);
setSuccessCount(successfulKills);
onComplete?.();
closeTimeoutRef.current = setTimeout(() => {
setOpen(false);
resetState();
}, AUTO_CLOSE_DELAY_MS);
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="danger" size="sm">
Kill All
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[520px]">
<DialogHeader>
<DialogTitle>Kill All Agents</DialogTitle>
<DialogDescription>
This force-kills every selected agent session. This action cannot be undone.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<fieldset className="space-y-2">
<legend className="text-sm font-medium">Scope</legend>
<label className="flex cursor-pointer items-center gap-2 text-sm text-foreground">
<input
type="radio"
name="kill-all-scope"
checked={scope === "internal"}
disabled={isKilling}
onChange={() => {
setScope("internal");
}}
/>
<span>Internal provider only ({internalSessions.length})</span>
</label>
<label className="flex cursor-pointer items-center gap-2 text-sm text-foreground">
<input
type="radio"
name="kill-all-scope"
checked={scope === "all"}
disabled={isKilling}
onChange={() => {
setScope("all");
}}
/>
<span>All providers ({sessions.length})</span>
</label>
</fieldset>
<div className="space-y-2">
<Label htmlFor="kill-all-confirmation-input">Type KILL ALL to confirm</Label>
<Input
id="kill-all-confirmation-input"
value={confirmationInput}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setConfirmationInput(event.target.value);
}}
placeholder={CONFIRM_TEXT}
autoComplete="off"
disabled={isKilling}
/>
</div>
{scopedSessions.length === 0 ? (
<p className="text-sm text-red-500">No sessions in the selected scope.</p>
) : null}
{isKilling ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
<span>
Killing {completedCount} of {targetCount} agents...
</span>
</div>
) : successCount !== null ? (
<p className="text-sm text-muted-foreground">
Killed {successCount} of {targetCount} agents. Closing...
</p>
) : null}
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
disabled={isKilling}
onClick={() => {
setOpen(false);
}}
>
Cancel
</Button>
<Button
type="button"
variant="danger"
disabled={isConfirmDisabled}
onClick={() => {
void handleKillAll();
}}
>
Kill All Agents
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,19 +1,113 @@
"use client"; "use client";
import { useCallback, useState } from "react";
import { AuditLogDrawer } from "@/components/mission-control/AuditLogDrawer";
import { GlobalAgentRoster } from "@/components/mission-control/GlobalAgentRoster"; import { GlobalAgentRoster } from "@/components/mission-control/GlobalAgentRoster";
import { MissionControlPanel } from "@/components/mission-control/MissionControlPanel"; import {
MAX_PANEL_COUNT,
MIN_PANEL_COUNT,
MissionControlPanel,
type PanelConfig,
} from "@/components/mission-control/MissionControlPanel";
import { Button } from "@/components/ui/button";
const DEFAULT_PANEL_SLOTS = ["panel-1", "panel-2", "panel-3", "panel-4"] as const; const INITIAL_PANELS: PanelConfig[] = [{}];
export function MissionControlLayout(): React.JSX.Element { export function MissionControlLayout(): React.JSX.Element {
const [panels, setPanels] = useState<PanelConfig[]>(INITIAL_PANELS);
const [selectedSessionId, setSelectedSessionId] = useState<string>();
const handleSelectSession = useCallback((sessionId: string): void => {
setSelectedSessionId(sessionId);
setPanels((currentPanels) => {
if (currentPanels.some((panel) => panel.sessionId === sessionId)) {
return currentPanels;
}
const firstEmptyPanelIndex = currentPanels.findIndex(
(panel) => panel.sessionId === undefined
);
if (firstEmptyPanelIndex >= 0) {
return currentPanels.map((panel, index) =>
index === firstEmptyPanelIndex ? { ...panel, sessionId } : panel
);
}
if (currentPanels.length >= MAX_PANEL_COUNT) {
return currentPanels;
}
return [...currentPanels, { sessionId }];
});
}, []);
const handleAddPanel = useCallback((): void => {
setPanels((currentPanels) => {
if (currentPanels.length >= MAX_PANEL_COUNT) {
return currentPanels;
}
return [...currentPanels, {}];
});
}, []);
const handleRemovePanel = useCallback((panelIndex: number): void => {
setPanels((currentPanels) => {
if (panelIndex < 0 || panelIndex >= currentPanels.length) {
return currentPanels;
}
if (currentPanels.length <= MIN_PANEL_COUNT) {
return currentPanels;
}
const nextPanels = currentPanels.filter((_, index) => index !== panelIndex);
return nextPanels.length === 0 ? INITIAL_PANELS : nextPanels;
});
}, []);
const handleExpandPanel = useCallback((panelIndex: number): void => {
setPanels((currentPanels) => {
if (panelIndex < 0 || panelIndex >= currentPanels.length) {
return currentPanels;
}
const shouldExpand = !currentPanels[panelIndex]?.expanded;
return currentPanels.map((panel, index) => ({
...panel,
expanded: shouldExpand && index === panelIndex,
}));
});
}, []);
return ( return (
<section className="h-full min-h-0 overflow-hidden" aria-label="Mission Control"> <section className="flex h-full min-h-0 flex-col overflow-hidden" aria-label="Mission Control">
<div className="grid h-full min-h-0 gap-4 xl:grid-cols-[280px_minmax(0,1fr)]"> <header className="mb-3 flex items-center justify-end">
<AuditLogDrawer
trigger={
<Button variant="outline" size="sm">
Audit Log
</Button>
}
/>
</header>
<div className="grid min-h-0 flex-1 gap-4 xl:grid-cols-[280px_minmax(0,1fr)]">
<aside className="h-full min-h-0"> <aside className="h-full min-h-0">
<GlobalAgentRoster /> <GlobalAgentRoster
onSelectSession={handleSelectSession}
{...(selectedSessionId !== undefined ? { selectedSessionId } : {})}
/>
</aside> </aside>
<main className="h-full min-h-0 overflow-hidden"> <main className="h-full min-h-0 overflow-hidden">
<MissionControlPanel panels={DEFAULT_PANEL_SLOTS} /> <MissionControlPanel
panels={panels}
onAddPanel={handleAddPanel}
onRemovePanel={handleRemovePanel}
onExpandPanel={handleExpandPanel}
/>
</main> </main>
</div> </div>
</section> </section>

View File

@@ -1,17 +1,107 @@
"use client"; "use client";
import { useEffect } from "react";
import { OrchestratorPanel } from "@/components/mission-control/OrchestratorPanel"; import { OrchestratorPanel } from "@/components/mission-control/OrchestratorPanel";
import { Button } from "@/components/ui/button";
interface MissionControlPanelProps { export interface PanelConfig {
panels: readonly string[]; sessionId?: string;
expanded?: boolean;
} }
export function MissionControlPanel({ panels }: MissionControlPanelProps): React.JSX.Element { interface MissionControlPanelProps {
panels: PanelConfig[];
onAddPanel: () => void;
onRemovePanel: (index: number) => void;
onExpandPanel: (index: number) => void;
}
export const MIN_PANEL_COUNT = 1;
export const MAX_PANEL_COUNT = 6;
export function MissionControlPanel({
panels,
onAddPanel,
onRemovePanel,
onExpandPanel,
}: MissionControlPanelProps): React.JSX.Element {
const expandedPanelIndex = panels.findIndex((panel) => panel.expanded);
const expandedPanel = expandedPanelIndex >= 0 ? panels[expandedPanelIndex] : undefined;
const canAddPanel = panels.length < MAX_PANEL_COUNT;
const canRemovePanel = panels.length > MIN_PANEL_COUNT;
useEffect(() => {
if (expandedPanelIndex < 0) {
return;
}
const handleKeyDown = (event: KeyboardEvent): void => {
if (event.key === "Escape") {
onExpandPanel(expandedPanelIndex);
}
};
window.addEventListener("keydown", handleKeyDown);
return (): void => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [expandedPanelIndex, onExpandPanel]);
return ( return (
<div className="grid h-full min-h-0 auto-rows-fr grid-cols-1 gap-4 overflow-y-auto pr-1 md:grid-cols-2"> <div className="flex h-full min-h-0 flex-col gap-3">
{panels.map((panelId) => ( <div className="flex items-center justify-between">
<OrchestratorPanel key={panelId} /> <h2 className="text-sm font-medium text-muted-foreground">Panels</h2>
))} <Button
type="button"
variant="outline"
size="icon"
onClick={onAddPanel}
disabled={!canAddPanel}
aria-label="Add panel"
title={canAddPanel ? "Add panel" : "Maximum of 6 panels"}
>
<span aria-hidden="true" className="text-lg leading-none">
+
</span>
</Button>
</div>
<div className="min-h-0 flex-1">
{expandedPanelIndex >= 0 && expandedPanel ? (
<div className="h-full min-h-0">
<OrchestratorPanel
{...(expandedPanel.sessionId !== undefined
? { sessionId: expandedPanel.sessionId }
: {})}
onClose={() => {
onRemovePanel(expandedPanelIndex);
}}
closeDisabled={!canRemovePanel}
onExpand={() => {
onExpandPanel(expandedPanelIndex);
}}
expanded
/>
</div>
) : (
<div className="grid h-full min-h-0 auto-rows-fr grid-cols-1 gap-4 overflow-y-auto pr-1 md:grid-cols-2 xl:grid-cols-3">
{panels.map((panel, index) => (
<OrchestratorPanel
key={`panel-${String(index)}`}
{...(panel.sessionId !== undefined ? { sessionId: panel.sessionId } : {})}
onClose={() => {
onRemovePanel(index);
}}
closeDisabled={!canRemovePanel}
onExpand={() => {
onExpandPanel(index);
}}
expanded={panel.expanded ?? false}
/>
))}
</div>
)}
</div>
</div> </div>
); );
} }

View File

@@ -1,15 +1,216 @@
"use client"; "use client";
import { useEffect, useRef, useState } from "react";
import { formatDistanceToNow } from "date-fns";
import { BargeInInput } from "@/components/mission-control/BargeInInput";
import { Badge } from "@/components/ui/badge";
import type { BadgeVariant } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { PanelControls } from "@/components/mission-control/PanelControls";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
useSessionStream,
useSessions,
type MissionControlConnectionStatus,
type MissionControlMessageRole,
} from "@/hooks/useMissionControl";
const ROLE_BADGE_VARIANT: Record<MissionControlMessageRole, BadgeVariant> = {
user: "badge-blue",
assistant: "status-success",
tool: "badge-amber",
system: "badge-muted",
};
const CONNECTION_DOT_CLASS: Record<MissionControlConnectionStatus, string> = {
connected: "bg-emerald-500",
connecting: "bg-amber-500",
error: "bg-red-500",
};
const CONNECTION_TEXT: Record<MissionControlConnectionStatus, string> = {
connected: "Connected",
connecting: "Connecting",
error: "Error",
};
export interface OrchestratorPanelProps {
sessionId?: string;
onClose?: () => void;
closeDisabled?: boolean;
onExpand?: () => void;
expanded?: boolean;
}
interface PanelHeaderActionsProps {
onClose?: () => void;
closeDisabled?: boolean;
onExpand?: () => void;
expanded?: boolean;
}
function PanelHeaderActions({
onClose,
closeDisabled = false,
onExpand,
expanded = false,
}: PanelHeaderActionsProps): React.JSX.Element | null {
if (!onClose && !onExpand) {
return null;
}
return (
<div className="flex items-center gap-1">
{onExpand ? (
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onExpand}
aria-label={expanded ? "Collapse panel" : "Expand panel"}
title={expanded ? "Collapse panel" : "Expand panel"}
>
<span aria-hidden="true" className="text-base leading-none">
{expanded ? "↙" : "↗"}
</span>
</Button>
) : null}
{onClose ? (
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onClose}
disabled={closeDisabled}
aria-label="Remove panel"
title="Remove panel"
>
<span aria-hidden="true" className="text-base leading-none">
×
</span>
</Button>
) : null}
</div>
);
}
function formatRelativeTimestamp(timestamp: string): string {
const parsedDate = new Date(timestamp);
if (Number.isNaN(parsedDate.getTime())) {
return "just now";
}
return formatDistanceToNow(parsedDate, { addSuffix: true });
}
export function OrchestratorPanel({
sessionId,
onClose,
closeDisabled,
onExpand,
expanded,
}: OrchestratorPanelProps): React.JSX.Element {
const { messages, status, error } = useSessionStream(sessionId ?? "");
const { sessions } = useSessions();
const bottomAnchorRef = useRef<HTMLDivElement | null>(null);
const [optimisticStatus, setOptimisticStatus] = useState<string | null>(null);
const selectedSessionStatus = sessions.find((session) => session.id === sessionId)?.status;
const controlsStatus = optimisticStatus ?? selectedSessionStatus ?? "unknown";
const panelHeaderActionProps = {
...(onClose !== undefined ? { onClose } : {}),
...(closeDisabled !== undefined ? { closeDisabled } : {}),
...(onExpand !== undefined ? { onExpand } : {}),
...(expanded !== undefined ? { expanded } : {}),
};
useEffect(() => {
bottomAnchorRef.current?.scrollIntoView({ block: "end" });
}, [messages.length]);
useEffect(() => {
setOptimisticStatus(null);
}, [sessionId, selectedSessionStatus]);
if (!sessionId) {
return (
<Card className="flex h-full min-h-[220px] flex-col">
<CardHeader>
<div className="flex items-start justify-between gap-2">
<CardTitle className="text-base">Orchestrator Panel</CardTitle>
<PanelHeaderActions {...panelHeaderActionProps} />
</div>
</CardHeader>
<CardContent className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
Select an agent to view its stream
</CardContent>
</Card>
);
}
export function OrchestratorPanel(): React.JSX.Element {
return ( return (
<Card className="flex h-full min-h-[220px] flex-col"> <Card className="flex h-full min-h-[220px] flex-col">
<CardHeader> <CardHeader className="space-y-2">
<CardTitle className="text-base">Orchestrator Panel</CardTitle> <div className="flex items-start justify-between gap-2">
<CardTitle className="text-base">Orchestrator Panel</CardTitle>
<PanelHeaderActions {...panelHeaderActionProps} />
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span
className={`h-2.5 w-2.5 rounded-full ${CONNECTION_DOT_CLASS[status]} ${
status === "connecting" ? "animate-pulse" : ""
}`}
aria-hidden="true"
/>
<span>{CONNECTION_TEXT[status]}</span>
</div>
<PanelControls
sessionId={sessionId}
status={controlsStatus}
onStatusChange={setOptimisticStatus}
/>
</div>
<p className="truncate text-xs text-muted-foreground">Session: {sessionId}</p>
</CardHeader> </CardHeader>
<CardContent className="flex flex-1 items-center justify-center text-sm text-muted-foreground"> <CardContent className="flex min-h-0 flex-1 flex-col p-0">
Select an agent <div className="min-h-0 flex-1">
<ScrollArea className="h-full w-full">
<div className="flex min-h-full flex-col gap-3 p-4">
{messages.length === 0 ? (
<p className="mt-6 text-center text-sm text-muted-foreground">
{error ?? "Waiting for messages..."}
</p>
) : (
messages.map((message) => (
<article
key={message.id}
className="rounded-lg border border-border/70 bg-card px-3 py-2"
>
<div className="mb-2 flex items-center justify-between gap-2">
<Badge variant={ROLE_BADGE_VARIANT[message.role]} className="uppercase">
{message.role}
</Badge>
<time className="text-xs text-muted-foreground">
{formatRelativeTimestamp(message.timestamp)}
</time>
</div>
<p className="whitespace-pre-wrap break-words text-sm text-foreground">
{message.content}
</p>
</article>
))
)}
<div ref={bottomAnchorRef} />
</div>
</ScrollArea>
</div>
<div className="border-t border-border/70 p-3">
<BargeInInput sessionId={sessionId} />
</div>
</CardContent> </CardContent>
</Card> </Card>
); );

View File

@@ -0,0 +1,259 @@
"use client";
import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { apiPost } from "@/lib/api/client";
const SESSIONS_QUERY_KEY = ["mission-control", "sessions"] as const;
type PanelAction = "pause" | "resume" | "graceful-kill" | "force-kill";
type KillConfirmationState = "graceful" | "force" | null;
interface PanelActionResult {
nextStatus: string;
}
export interface PanelControlsProps {
sessionId: string;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
status: "active" | "paused" | "killed" | string;
onStatusChange?: (newStatus: string) => void;
}
function getErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return "Failed to update agent session.";
}
export function PanelControls({
sessionId,
status,
onStatusChange,
}: PanelControlsProps): React.JSX.Element {
const queryClient = useQueryClient();
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [confirmingKill, setConfirmingKill] = useState<KillConfirmationState>(null);
useEffect(() => {
setErrorMessage(null);
setConfirmingKill(null);
}, [sessionId]);
const controlMutation = useMutation({
mutationFn: async (action: PanelAction): Promise<PanelActionResult> => {
switch (action) {
case "pause":
await apiPost<{ message: string }>(
`/api/mission-control/sessions/${encodeURIComponent(sessionId)}/pause`
);
return { nextStatus: "paused" };
case "resume":
await apiPost<{ message: string }>(
`/api/mission-control/sessions/${encodeURIComponent(sessionId)}/resume`
);
return { nextStatus: "active" };
case "graceful-kill":
await apiPost<{ message: string }>(
`/api/mission-control/sessions/${encodeURIComponent(sessionId)}/kill`,
{ force: false }
);
return { nextStatus: "killed" };
case "force-kill":
await apiPost<{ message: string }>(
`/api/mission-control/sessions/${encodeURIComponent(sessionId)}/kill`,
{ force: true }
);
return { nextStatus: "killed" };
}
},
onSuccess: ({ nextStatus }): void => {
setErrorMessage(null);
setConfirmingKill(null);
onStatusChange?.(nextStatus);
void queryClient.invalidateQueries({ queryKey: SESSIONS_QUERY_KEY });
},
onError: (error: unknown): void => {
setConfirmingKill(null);
setErrorMessage(getErrorMessage(error));
},
});
const normalizedStatus = status.toLowerCase();
const isKilled = normalizedStatus === "killed";
const isBusy = controlMutation.isPending;
const pendingAction = isBusy ? controlMutation.variables : undefined;
const submitAction = (action: PanelAction): void => {
setErrorMessage(null);
controlMutation.mutate(action);
};
const pauseDisabled = isBusy || normalizedStatus === "paused" || isKilled;
const resumeDisabled = isBusy || normalizedStatus === "active" || isKilled;
const gracefulKillDisabled = isBusy || isKilled;
const forceKillDisabled = isBusy || isKilled;
return (
<div className="flex flex-col items-end gap-2">
<div className="flex flex-wrap items-center justify-end gap-1.5">
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => {
submitAction("pause");
}}
disabled={pauseDisabled}
aria-label="Pause session"
>
{pendingAction === "pause" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
) : (
<span aria-hidden="true"></span>
)}
<span>Pause</span>
</Button>
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => {
submitAction("resume");
}}
disabled={resumeDisabled}
aria-label="Resume session"
>
{pendingAction === "resume" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
) : (
<span aria-hidden="true"></span>
)}
<span>Resume</span>
</Button>
<div className="relative">
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => {
setErrorMessage(null);
setConfirmingKill((current) => (current === "graceful" ? null : "graceful"));
}}
disabled={gracefulKillDisabled}
aria-label="Gracefully kill session"
>
{pendingAction === "graceful-kill" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
) : (
<span aria-hidden="true"></span>
)}
<span>Graceful Kill</span>
</Button>
{confirmingKill === "graceful" ? (
<div className="absolute right-0 top-[calc(100%+0.375rem)] z-20 w-72 rounded-md border border-border bg-card p-2 shadow-lg">
<p className="text-xs text-muted-foreground">
Gracefully stop this agent after it finishes the current step?
</p>
<div className="mt-2 flex justify-end gap-1.5">
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => {
setConfirmingKill(null);
}}
disabled={isBusy}
>
Cancel
</Button>
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => {
submitAction("graceful-kill");
}}
disabled={isBusy}
>
{pendingAction === "graceful-kill" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
) : null}
<span>Confirm</span>
</Button>
</div>
</div>
) : null}
</div>
<div className="relative">
<Button
type="button"
size="sm"
variant="danger"
onClick={() => {
setErrorMessage(null);
setConfirmingKill((current) => (current === "force" ? null : "force"));
}}
disabled={forceKillDisabled}
aria-label="Force kill session"
>
{pendingAction === "force-kill" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
) : (
<span aria-hidden="true">💀</span>
)}
<span>Force Kill</span>
</Button>
{confirmingKill === "force" ? (
<div className="absolute right-0 top-[calc(100%+0.375rem)] z-20 w-72 rounded-md border border-border bg-card p-2 shadow-lg">
<p className="text-xs text-muted-foreground">
This will hard-kill the agent immediately.
</p>
<div className="mt-2 flex justify-end gap-1.5">
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => {
setConfirmingKill(null);
}}
disabled={isBusy}
>
Cancel
</Button>
<Button
type="button"
size="sm"
variant="danger"
onClick={() => {
submitAction("force-kill");
}}
disabled={isBusy}
>
{pendingAction === "force-kill" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
) : null}
<span>Confirm</span>
</Button>
</div>
</div>
) : null}
</div>
</div>
{errorMessage ? (
<Badge variant="status-error" className="max-w-[32rem] whitespace-normal text-xs">
{errorMessage}
</Badge>
) : null}
</div>
);
}

View File

@@ -102,5 +102,5 @@ describe("OnboardingWizard", () => {
await waitFor(() => { await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith("/"); expect(mockPush).toHaveBeenCalledWith("/");
}); });
}); }, 10_000);
}); });

View File

@@ -0,0 +1,13 @@
import * as React from "react";
export interface CollapsibleProps extends React.HTMLAttributes<HTMLDivElement> {
open?: boolean;
}
export function Collapsible({
open = true,
className = "",
...props
}: CollapsibleProps): React.JSX.Element {
return <div data-state={open ? "open" : "closed"} className={className} {...props} />;
}

View File

@@ -0,0 +1,15 @@
import * as React from "react";
export type ScrollAreaProps = React.HTMLAttributes<HTMLDivElement>;
export const ScrollArea = React.forwardRef<HTMLDivElement, ScrollAreaProps>(
({ className = "", children, ...props }, ref) => {
return (
<div ref={ref} className={`relative overflow-hidden ${className}`} {...props}>
<div className="h-full w-full overflow-auto">{children}</div>
</div>
);
}
);
ScrollArea.displayName = "ScrollArea";

View File

@@ -0,0 +1,137 @@
import * as React from "react";
import { X } from "lucide-react";
export interface SheetProps {
open?: boolean;
onOpenChange?: (open: boolean) => void;
children?: React.ReactNode;
}
export interface SheetTriggerProps {
children?: React.ReactNode;
asChild?: boolean;
}
export interface SheetContentProps {
children?: React.ReactNode;
className?: string;
}
export interface SheetHeaderProps {
children?: React.ReactNode;
className?: string;
}
export interface SheetTitleProps {
children?: React.ReactNode;
className?: string;
}
export interface SheetDescriptionProps {
children?: React.ReactNode;
className?: string;
}
const SheetContext = React.createContext<{
open?: boolean;
onOpenChange?: (open: boolean) => void;
}>({});
export function Sheet({ open, onOpenChange, children }: SheetProps): React.JSX.Element {
const contextValue: { open?: boolean; onOpenChange?: (open: boolean) => void } = {};
if (open !== undefined) {
contextValue.open = open;
}
if (onOpenChange !== undefined) {
contextValue.onOpenChange = onOpenChange;
}
return <SheetContext.Provider value={contextValue}>{children}</SheetContext.Provider>;
}
export function SheetTrigger({ children, asChild }: SheetTriggerProps): React.JSX.Element {
const { onOpenChange } = React.useContext(SheetContext);
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children, {
onClick: () => onOpenChange?.(true),
} as React.HTMLAttributes<HTMLElement>);
}
return (
<button type="button" onClick={() => onOpenChange?.(true)}>
{children}
</button>
);
}
export function SheetContent({
children,
className = "",
}: SheetContentProps): React.JSX.Element | null {
const { open, onOpenChange } = React.useContext(SheetContext);
React.useEffect(() => {
if (!open) {
return;
}
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key === "Escape") {
onOpenChange?.(false);
}
};
window.addEventListener("keydown", onKeyDown);
return (): void => {
window.removeEventListener("keydown", onKeyDown);
};
}, [onOpenChange, open]);
if (!open) {
return null;
}
return (
<div className="fixed inset-0 z-50">
<button
type="button"
aria-label="Close sheet"
className="absolute inset-0 h-full w-full bg-black/50"
onClick={() => onOpenChange?.(false)}
/>
<div
className={`absolute inset-y-0 right-0 z-10 flex h-full w-full max-w-3xl flex-col border-l border-border bg-background p-6 shadow-xl ${className}`}
>
<button
type="button"
onClick={() => onOpenChange?.(false)}
className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</button>
{children}
</div>
</div>
);
}
export function SheetHeader({ children, className = "" }: SheetHeaderProps): React.JSX.Element {
return <div className={`space-y-1 pr-8 ${className}`}>{children}</div>;
}
export function SheetTitle({ children, className = "" }: SheetTitleProps): React.JSX.Element {
return <h2 className={`text-lg font-semibold ${className}`}>{children}</h2>;
}
export function SheetDescription({
children,
className = "",
}: SheetDescriptionProps): React.JSX.Element {
return <p className={`text-sm text-muted-foreground ${className}`}>{children}</p>;
}

View File

@@ -0,0 +1,15 @@
import * as React from "react";
export type SkeletonProps = React.HTMLAttributes<HTMLDivElement>;
export const Skeleton = React.forwardRef<HTMLDivElement, SkeletonProps>(
({ className = "", ...props }, ref) => (
<div
ref={ref}
className={`animate-pulse rounded-md bg-[rgb(var(--surface-2))] ${className}`}
{...props}
/>
)
);
Skeleton.displayName = "Skeleton";

View File

@@ -1,10 +1,189 @@
interface UseMissionControlResult { "use client";
sessions: [];
loading: boolean; import { useEffect, useRef, useState } from "react";
error: null; import { useQuery } from "@tanstack/react-query";
import type { AgentMessageRole, AgentSessionStatus } from "@mosaic/shared";
import { apiGet } from "@/lib/api/client";
const MISSION_CONTROL_SESSIONS_QUERY_KEY = ["mission-control", "sessions"] as const;
const SESSIONS_REFRESH_INTERVAL_MS = 15_000;
export type MissionControlMessageRole = AgentMessageRole;
export interface MissionControlSession {
id: string;
providerId: string;
providerType: string;
label?: string;
status: AgentSessionStatus;
parentSessionId?: string;
createdAt: string;
updatedAt: string;
metadata?: Record<string, unknown>;
} }
// Stub — will be wired in P2-002 interface MissionControlSessionsResponse {
export function useMissionControl(): UseMissionControlResult { sessions: MissionControlSession[];
return { sessions: [], loading: false, error: null }; }
export interface MissionControlStreamMessage {
id: string;
sessionId: string;
role: MissionControlMessageRole;
content: string;
timestamp: string;
metadata?: Record<string, unknown>;
}
export type MissionControlConnectionStatus = "connecting" | "connected" | "error";
export interface UseSessionsResult {
sessions: MissionControlSession[];
loading: boolean;
error: Error | null;
}
export interface UseSessionStreamResult {
messages: MissionControlStreamMessage[];
status: MissionControlConnectionStatus;
error: string | null;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isMessageRole(value: unknown): value is MissionControlMessageRole {
return value === "assistant" || value === "system" || value === "tool" || value === "user";
}
function isMissionControlStreamMessage(value: unknown): value is MissionControlStreamMessage {
if (!isRecord(value)) {
return false;
}
const { id, sessionId, role, content, timestamp, metadata } = value;
if (
typeof id !== "string" ||
typeof sessionId !== "string" ||
!isMessageRole(role) ||
typeof content !== "string" ||
typeof timestamp !== "string"
) {
return false;
}
if (metadata !== undefined && !isRecord(metadata)) {
return false;
}
return true;
}
/**
* Fetches Mission Control sessions.
*/
export function useSessions(): UseSessionsResult {
const query = useQuery<MissionControlSessionsResponse>({
queryKey: MISSION_CONTROL_SESSIONS_QUERY_KEY,
queryFn: async (): Promise<MissionControlSessionsResponse> => {
return apiGet<MissionControlSessionsResponse>("/api/mission-control/sessions");
},
refetchInterval: SESSIONS_REFRESH_INTERVAL_MS,
});
return {
sessions: query.data?.sessions ?? [],
loading: query.isLoading,
error: query.error ?? null,
};
}
/**
* Backward-compatible alias for early Mission Control integration.
*/
export function useMissionControl(): UseSessionsResult {
return useSessions();
}
/**
* Streams Mission Control session messages over SSE.
*/
export function useSessionStream(sessionId: string): UseSessionStreamResult {
const [messages, setMessages] = useState<MissionControlStreamMessage[]>([]);
const [status, setStatus] = useState<MissionControlConnectionStatus>("connecting");
const [error, setError] = useState<string | null>(null);
const eventSourceRef = useRef<EventSource | null>(null);
useEffect(() => {
if (eventSourceRef.current !== null) {
eventSourceRef.current.close();
eventSourceRef.current = null;
}
setMessages([]);
setError(null);
if (!sessionId) {
setStatus("connecting");
return;
}
if (typeof EventSource === "undefined") {
setStatus("error");
setError("Mission Control stream is not supported by this browser.");
return;
}
setStatus("connecting");
const source = new EventSource(
`/api/mission-control/sessions/${encodeURIComponent(sessionId)}/stream`
);
eventSourceRef.current = source;
source.onopen = (): void => {
setStatus("connected");
setError(null);
};
source.onmessage = (event: MessageEvent<string>): void => {
try {
const parsed = JSON.parse(event.data) as unknown;
if (!isMissionControlStreamMessage(parsed)) {
return;
}
setMessages((previousMessages) => [...previousMessages, parsed]);
} catch {
// Ignore malformed events from the stream.
}
};
source.onerror = (): void => {
if (source.readyState === EventSource.CONNECTING) {
setStatus("connecting");
setError(null);
return;
}
setStatus("error");
setError("Mission Control stream disconnected.");
};
return (): void => {
source.close();
if (eventSourceRef.current === source) {
eventSourceRef.current = null;
}
};
}, [sessionId]);
return {
messages,
status,
error,
};
} }