"use client";
import { memo } from "react";
import { IconActivity, IconCheck, IconX } from "@tabler/icons-react";
import { GridSpinner } from "@/components/grid-spinner";
import { cn } from "@/lib/utils";
import type { Message } from "@/lib/types/http";
import type { ToolCallMetadata } from "@/components/task/chat/types";
import { readMonitorView } from "@/components/task/chat/types";
import { ExpandableRow } from "./expandable-row";
import { useExpandState } from "./use-expand-state";
type MonitorMessageProps = {
comment: Message;
};
// Status icon mirroring the other tool cards: spinner while watching,
// checkmark when the parent prompt completes naturally, X when the agent
// process restarted (the adapter sets status=cancelled in that case).
function MonitorStatusIcon({ status, ended }: { status: string | undefined; ended: boolean }) {
if (!ended) return ;
if (status === "cancelled") return ;
return ;
}
function formatStatusLabel(
status: string | undefined,
ended: boolean,
endReason: string | undefined,
) {
if (!ended) return "watching";
if (status === "cancelled" || endReason === "session_restart") return "ended (session restart)";
return "ended";
}
type MonitorViewModel = {
status: ToolCallMetadata["status"];
ended: boolean;
endReason: string;
eventCount: number;
recentEvents: string[];
title: string;
countSuffix: string;
};
function pluralizeEventCount(n: number): string {
if (n <= 0) return "";
return ` · ${n} event${n === 1 ? "" : "s"}`;
}
function buildMonitorViewModel(comment: Message): MonitorViewModel {
const metadata = comment.metadata as ToolCallMetadata | undefined;
const view = readMonitorView(metadata?.normalized?.generic) ?? {};
const command = view.command ?? "";
const eventCount = view.event_count ?? 0;
return {
status: metadata?.status,
ended: view.ended === true,
endReason: view.end_reason ?? "",
eventCount,
recentEvents: view.recent_events ?? [],
title: command ? `Monitor: ${command}` : "Monitor",
countSuffix: pluralizeEventCount(eventCount),
};
}
function MonitorHeader({ vm }: { vm: MonitorViewModel }) {
return (
{vm.title}
{vm.countSuffix && (
{vm.countSuffix}
)}
{formatStatusLabel(vm.status, vm.ended, vm.endReason)}
);
}
export const MonitorMessage = memo(function MonitorMessage({ comment }: MonitorMessageProps) {
const vm = buildMonitorViewModel(comment);
// Auto-expand whenever there are events to surface — both during the
// watch (so users see the stream live) and after it ends (so they can
// review what happened). Empty Monitors collapse since there's nothing
// to show.
const { isExpanded, handleToggle } = useExpandState(vm.status, vm.recentEvents.length > 0);
return (
}
header={}
hasExpandableContent={vm.recentEvents.length > 0}
isExpanded={isExpanded}
onToggle={handleToggle}
>
);
});
function MonitorEventList({ events }: { events: string[] }) {
if (events.length === 0) return null;
return (
{events.map((line, idx) => (
{line}
))}
);
}