feat(web): add agent output terminal tabs for orchestrator sessions (#522)
All checks were successful
ci/woodpecker/push/web Pipeline was successful
All checks were successful
ci/woodpecker/push/web Pipeline was successful
Co-authored-by: Jason Woltje <jason@diversecanvas.com> Co-committed-by: Jason Woltje <jason@diversecanvas.com>
This commit was merged in pull request #522.
This commit is contained in:
368
apps/web/src/components/terminal/AgentTerminal.test.tsx
Normal file
368
apps/web/src/components/terminal/AgentTerminal.test.tsx
Normal file
@@ -0,0 +1,368 @@
|
|||||||
|
/**
|
||||||
|
* @file AgentTerminal.test.tsx
|
||||||
|
* @description Unit tests for the AgentTerminal component
|
||||||
|
*
|
||||||
|
* Tests cover:
|
||||||
|
* - Output rendering
|
||||||
|
* - Status display (status indicator + badge)
|
||||||
|
* - ANSI stripping
|
||||||
|
* - Agent header information (type, duration, jobId)
|
||||||
|
* - Auto-scroll behavior
|
||||||
|
* - Copy-to-clipboard
|
||||||
|
* - Error message display
|
||||||
|
* - Empty state rendering
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { render, screen, fireEvent, act } from "@testing-library/react";
|
||||||
|
import type { ReactElement } from "react";
|
||||||
|
import { AgentTerminal } from "./AgentTerminal";
|
||||||
|
import type { AgentSession } from "@/hooks/useAgentStream";
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Mock navigator.clipboard
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const mockWriteText = vi.fn(() => Promise.resolve());
|
||||||
|
Object.defineProperty(navigator, "clipboard", {
|
||||||
|
value: { writeText: mockWriteText },
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Factory helpers
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
function makeAgent(overrides: Partial<AgentSession> = {}): AgentSession {
|
||||||
|
return {
|
||||||
|
agentId: "test-agent-1",
|
||||||
|
agentType: "worker",
|
||||||
|
status: "running",
|
||||||
|
outputLines: [],
|
||||||
|
startedAt: Date.now() - 5000, // 5s ago
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Tests
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("AgentTerminal", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.useFakeTimers({ shouldAdvanceTime: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Rendering
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("rendering", () => {
|
||||||
|
it("renders the agent terminal container", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-terminal")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("has region role with agent type label", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ agentType: "planner" })} />) as ReactElement);
|
||||||
|
expect(screen.getByRole("region", { name: "Agent output: planner" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets data-agent-id attribute", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ agentId: "my-agent-123" })} />) as ReactElement);
|
||||||
|
const container = screen.getByTestId("agent-terminal");
|
||||||
|
expect(container).toHaveAttribute("data-agent-id", "my-agent-123");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies className prop to the outer container", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} className="custom-cls" />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-terminal")).toHaveClass("custom-cls");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Header
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("header", () => {
|
||||||
|
it("renders the agent type label", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ agentType: "coordinator" })} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-type-label")).toHaveTextContent("coordinator");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes jobId in the label when provided", () => {
|
||||||
|
render(
|
||||||
|
(
|
||||||
|
<AgentTerminal agent={makeAgent({ agentType: "worker", jobId: "job-42" })} />
|
||||||
|
) as ReactElement
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId("agent-type-label")).toHaveTextContent("worker · job-42");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not show jobId separator when jobId is absent", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ agentType: "worker" })} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-type-label")).not.toHaveTextContent("·");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders the duration element", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-duration")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows seconds for short-running agents", () => {
|
||||||
|
const agent = makeAgent({ startedAt: Date.now() - 8000 });
|
||||||
|
render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-duration")).toHaveTextContent("s");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows minutes for long-running agents", () => {
|
||||||
|
const agent = makeAgent({ startedAt: Date.now() - 125000 }); // 2m 5s
|
||||||
|
render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-duration")).toHaveTextContent("m");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Status indicator
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("status indicator", () => {
|
||||||
|
it("shows a running indicator for running status", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ status: "running" })} />) as ReactElement);
|
||||||
|
const indicator = screen.getByTestId("status-indicator");
|
||||||
|
expect(indicator).toHaveAttribute("data-status", "running");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a spawning indicator for spawning status", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ status: "spawning" })} />) as ReactElement);
|
||||||
|
const indicator = screen.getByTestId("status-indicator");
|
||||||
|
expect(indicator).toHaveAttribute("data-status", "spawning");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows completed indicator for completed status", () => {
|
||||||
|
render(
|
||||||
|
(
|
||||||
|
<AgentTerminal agent={makeAgent({ status: "completed", endedAt: Date.now() })} />
|
||||||
|
) as ReactElement
|
||||||
|
);
|
||||||
|
const indicator = screen.getByTestId("status-indicator");
|
||||||
|
expect(indicator).toHaveAttribute("data-status", "completed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows error indicator for error status", () => {
|
||||||
|
render(
|
||||||
|
(
|
||||||
|
<AgentTerminal agent={makeAgent({ status: "error", endedAt: Date.now() })} />
|
||||||
|
) as ReactElement
|
||||||
|
);
|
||||||
|
const indicator = screen.getByTestId("status-indicator");
|
||||||
|
expect(indicator).toHaveAttribute("data-status", "error");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Status badge
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("status badge", () => {
|
||||||
|
it("renders the status badge", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ status: "running" })} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("status-badge")).toHaveTextContent("running");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows 'spawning' badge for spawning status", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ status: "spawning" })} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("status-badge")).toHaveTextContent("spawning");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows 'completed' badge for completed status", () => {
|
||||||
|
render(
|
||||||
|
(
|
||||||
|
<AgentTerminal agent={makeAgent({ status: "completed", endedAt: Date.now() })} />
|
||||||
|
) as ReactElement
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId("status-badge")).toHaveTextContent("completed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows 'error' badge for error status", () => {
|
||||||
|
render(
|
||||||
|
(
|
||||||
|
<AgentTerminal agent={makeAgent({ status: "error", endedAt: Date.now() })} />
|
||||||
|
) as ReactElement
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId("status-badge")).toHaveTextContent("error");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Output rendering
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("output area", () => {
|
||||||
|
it("renders the output pre element", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-output")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows 'Waiting for output...' when outputLines is empty and status is running", () => {
|
||||||
|
render(
|
||||||
|
(
|
||||||
|
<AgentTerminal agent={makeAgent({ status: "running", outputLines: [] })} />
|
||||||
|
) as ReactElement
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId("agent-output")).toHaveTextContent("Waiting for output...");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows 'Spawning agent...' when status is spawning and no output", () => {
|
||||||
|
render(
|
||||||
|
(
|
||||||
|
<AgentTerminal agent={makeAgent({ status: "spawning", outputLines: [] })} />
|
||||||
|
) as ReactElement
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId("agent-output")).toHaveTextContent("Spawning agent...");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders output lines as text content", () => {
|
||||||
|
const agent = makeAgent({
|
||||||
|
outputLines: ["Hello world\n", "Second line\n"],
|
||||||
|
});
|
||||||
|
render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
const output = screen.getByTestId("agent-output");
|
||||||
|
expect(output).toHaveTextContent("Hello world");
|
||||||
|
expect(output).toHaveTextContent("Second line");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips ANSI escape codes from output", () => {
|
||||||
|
const agent = makeAgent({
|
||||||
|
outputLines: ["\x1b[32mGreen text\x1b[0m\n"],
|
||||||
|
});
|
||||||
|
render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
const output = screen.getByTestId("agent-output");
|
||||||
|
expect(output).toHaveTextContent("Green text");
|
||||||
|
expect(output.textContent).not.toContain("\x1b");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("has aria-live=polite for screen reader announcements", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-output")).toHaveAttribute("aria-live", "polite");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Error message
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("error message", () => {
|
||||||
|
it("shows error message when status is error and errorMessage is set", () => {
|
||||||
|
const agent = makeAgent({
|
||||||
|
status: "error",
|
||||||
|
endedAt: Date.now(),
|
||||||
|
errorMessage: "Process crashed",
|
||||||
|
});
|
||||||
|
render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("agent-error-message")).toHaveTextContent("Process crashed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders alert role for error message", () => {
|
||||||
|
const agent = makeAgent({
|
||||||
|
status: "error",
|
||||||
|
endedAt: Date.now(),
|
||||||
|
errorMessage: "OOM killed",
|
||||||
|
});
|
||||||
|
render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
expect(screen.getByRole("alert")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not show error message when status is running", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent({ status: "running" })} />) as ReactElement);
|
||||||
|
expect(screen.queryByTestId("agent-error-message")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not show error message when status is error but errorMessage is absent", () => {
|
||||||
|
const agent = makeAgent({ status: "error", endedAt: Date.now() });
|
||||||
|
render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
expect(screen.queryByTestId("agent-error-message")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Copy to clipboard
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("copy to clipboard", () => {
|
||||||
|
it("renders the copy button", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} />) as ReactElement);
|
||||||
|
expect(screen.getByTestId("copy-button")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("copy button has aria-label='Copy agent output'", () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} />) as ReactElement);
|
||||||
|
expect(screen.getByRole("button", { name: "Copy agent output" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls clipboard.writeText with stripped output on click", async () => {
|
||||||
|
const agent = makeAgent({
|
||||||
|
outputLines: ["\x1b[32mLine 1\x1b[0m\n", "Line 2\n"],
|
||||||
|
});
|
||||||
|
render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(screen.getByTestId("copy-button"));
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mockWriteText).toHaveBeenCalledWith("Line 1\nLine 2\n");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows 'copied' text briefly after clicking copy", async () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} />) as ReactElement);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(screen.getByTestId("copy-button"));
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByTestId("copy-button")).toHaveTextContent("copied");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reverts copy button text after timeout", async () => {
|
||||||
|
render((<AgentTerminal agent={makeAgent()} />) as ReactElement);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(screen.getByTestId("copy-button"));
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(2500);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByTestId("copy-button")).toHaveTextContent("copy");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Auto-scroll
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("auto-scroll", () => {
|
||||||
|
it("does not throw when outputLines changes", () => {
|
||||||
|
const agent = makeAgent({ outputLines: ["Line 1\n"] });
|
||||||
|
const { rerender } = render((<AgentTerminal agent={agent} />) as ReactElement);
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
rerender(
|
||||||
|
(
|
||||||
|
<AgentTerminal agent={{ ...agent, outputLines: ["Line 1\n", "Line 2\n"] }} />
|
||||||
|
) as ReactElement
|
||||||
|
);
|
||||||
|
}).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
381
apps/web/src/components/terminal/AgentTerminal.tsx
Normal file
381
apps/web/src/components/terminal/AgentTerminal.tsx
Normal file
@@ -0,0 +1,381 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AgentTerminal component
|
||||||
|
*
|
||||||
|
* Read-only terminal view for displaying orchestrator agent output.
|
||||||
|
* Uses a <pre> element with monospace font rather than xterm.js because
|
||||||
|
* this is read-only agent stdout/stderr, not an interactive PTY.
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - Displays accumulated output lines with basic ANSI color rendering
|
||||||
|
* - Status badge (spinning/checkmark/X) indicating agent lifecycle
|
||||||
|
* - Header bar with agent type, status, and elapsed duration
|
||||||
|
* - Auto-scrolls to bottom as new output arrives
|
||||||
|
* - Copy-to-clipboard button for full output
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState, useCallback } from "react";
|
||||||
|
import type { ReactElement, CSSProperties } from "react";
|
||||||
|
import type { AgentSession, AgentStatus } from "@/hooks/useAgentStream";
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Types
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
export interface AgentTerminalProps {
|
||||||
|
/** The agent session to display */
|
||||||
|
agent: AgentSession;
|
||||||
|
/** Optional CSS class name for the outer container */
|
||||||
|
className?: string;
|
||||||
|
/** Optional inline style for the outer container */
|
||||||
|
style?: CSSProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// ANSI color strip helper
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
// Simple ANSI escape sequence stripper — produces readable plain text for <pre>.
|
||||||
|
// We strip rather than parse for security and simplicity in read-only display.
|
||||||
|
// eslint-disable-next-line no-control-regex
|
||||||
|
const ANSI_PATTERN = /\x1b\[[0-9;]*[mGKHF]/g;
|
||||||
|
|
||||||
|
function stripAnsi(text: string): string {
|
||||||
|
return text.replace(ANSI_PATTERN, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Duration helper
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
function formatDuration(startedAt: number, endedAt?: number): string {
|
||||||
|
const elapsed = Math.floor(((endedAt ?? Date.now()) - startedAt) / 1000);
|
||||||
|
if (elapsed < 60) return `${elapsed.toString()}s`;
|
||||||
|
const minutes = Math.floor(elapsed / 60);
|
||||||
|
const seconds = elapsed % 60;
|
||||||
|
return `${minutes.toString()}m ${seconds.toString()}s`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Status indicator
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
interface StatusIndicatorProps {
|
||||||
|
status: AgentStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatusIndicator({ status }: StatusIndicatorProps): ReactElement {
|
||||||
|
const baseStyle: CSSProperties = {
|
||||||
|
display: "inline-block",
|
||||||
|
width: 8,
|
||||||
|
height: 8,
|
||||||
|
borderRadius: "50%",
|
||||||
|
flexShrink: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (status === "running" || status === "spawning") {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-testid="status-indicator"
|
||||||
|
data-status={status}
|
||||||
|
style={{
|
||||||
|
...baseStyle,
|
||||||
|
background: "var(--success)",
|
||||||
|
animation: "agentPulse 1.5s ease-in-out infinite",
|
||||||
|
}}
|
||||||
|
aria-label="Running"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status === "completed") {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-testid="status-indicator"
|
||||||
|
data-status={status}
|
||||||
|
style={{
|
||||||
|
...baseStyle,
|
||||||
|
background: "var(--muted)",
|
||||||
|
}}
|
||||||
|
aria-label="Completed"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// error
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-testid="status-indicator"
|
||||||
|
data-status={status}
|
||||||
|
style={{
|
||||||
|
...baseStyle,
|
||||||
|
background: "var(--danger)",
|
||||||
|
}}
|
||||||
|
aria-label="Error"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Status badge
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
interface StatusBadgeProps {
|
||||||
|
status: AgentStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatusBadge({ status }: StatusBadgeProps): ReactElement {
|
||||||
|
const colorMap: Record<AgentStatus, string> = {
|
||||||
|
spawning: "var(--warn)",
|
||||||
|
running: "var(--success)",
|
||||||
|
completed: "var(--muted)",
|
||||||
|
error: "var(--danger)",
|
||||||
|
};
|
||||||
|
|
||||||
|
const labelMap: Record<AgentStatus, string> = {
|
||||||
|
spawning: "spawning",
|
||||||
|
running: "running",
|
||||||
|
completed: "completed",
|
||||||
|
error: "error",
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-testid="status-badge"
|
||||||
|
style={{
|
||||||
|
fontSize: "0.65rem",
|
||||||
|
fontFamily: "var(--mono)",
|
||||||
|
color: colorMap[status],
|
||||||
|
border: `1px solid ${colorMap[status]}`,
|
||||||
|
borderRadius: 3,
|
||||||
|
padding: "1px 5px",
|
||||||
|
lineHeight: 1.6,
|
||||||
|
letterSpacing: "0.03em",
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{labelMap[status]}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Component
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AgentTerminal renders accumulated agent output in a scrollable pre block.
|
||||||
|
* It is intentionally read-only — no keyboard input is accepted.
|
||||||
|
*/
|
||||||
|
export function AgentTerminal({ agent, className = "", style }: AgentTerminalProps): ReactElement {
|
||||||
|
const outputRef = useRef<HTMLPreElement>(null);
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const [tick, setTick] = useState(0);
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Duration ticker — only runs while active
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (agent.status === "running" || agent.status === "spawning") {
|
||||||
|
const id = setInterval(() => {
|
||||||
|
setTick((t) => t + 1);
|
||||||
|
}, 1000);
|
||||||
|
return (): void => {
|
||||||
|
clearInterval(id);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}, [agent.status]);
|
||||||
|
|
||||||
|
// Consume tick to avoid unused-var lint
|
||||||
|
void tick;
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Auto-scroll to bottom on new output
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = outputRef.current;
|
||||||
|
if (el) {
|
||||||
|
el.scrollTop = el.scrollHeight;
|
||||||
|
}
|
||||||
|
}, [agent.outputLines]);
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Copy to clipboard
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const handleCopy = useCallback((): void => {
|
||||||
|
const text = agent.outputLines.map(stripAnsi).join("");
|
||||||
|
void navigator.clipboard.writeText(text).then(() => {
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => {
|
||||||
|
setCopied(false);
|
||||||
|
}, 2000);
|
||||||
|
});
|
||||||
|
}, [agent.outputLines]);
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Styles
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const containerStyle: CSSProperties = {
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
height: "100%",
|
||||||
|
background: "var(--bg-deep)",
|
||||||
|
overflow: "hidden",
|
||||||
|
...style,
|
||||||
|
};
|
||||||
|
|
||||||
|
const headerStyle: CSSProperties = {
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 8,
|
||||||
|
padding: "6px 12px",
|
||||||
|
borderBottom: "1px solid var(--border)",
|
||||||
|
flexShrink: 0,
|
||||||
|
background: "var(--bg-deep)",
|
||||||
|
};
|
||||||
|
|
||||||
|
const titleStyle: CSSProperties = {
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
fontFamily: "var(--mono)",
|
||||||
|
color: "var(--text)",
|
||||||
|
flex: 1,
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
};
|
||||||
|
|
||||||
|
const durationStyle: CSSProperties = {
|
||||||
|
fontSize: "0.65rem",
|
||||||
|
fontFamily: "var(--mono)",
|
||||||
|
color: "var(--muted)",
|
||||||
|
flexShrink: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const outputStyle: CSSProperties = {
|
||||||
|
flex: 1,
|
||||||
|
overflow: "auto",
|
||||||
|
margin: 0,
|
||||||
|
padding: "8px 12px",
|
||||||
|
fontFamily: "var(--mono)",
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
lineHeight: 1.5,
|
||||||
|
color: "var(--text)",
|
||||||
|
background: "var(--bg-deep)",
|
||||||
|
whiteSpace: "pre-wrap",
|
||||||
|
wordBreak: "break-all",
|
||||||
|
};
|
||||||
|
|
||||||
|
const copyButtonStyle: CSSProperties = {
|
||||||
|
background: "transparent",
|
||||||
|
border: "1px solid var(--border)",
|
||||||
|
borderRadius: 3,
|
||||||
|
color: copied ? "var(--success)" : "var(--muted)",
|
||||||
|
cursor: "pointer",
|
||||||
|
fontSize: "0.65rem",
|
||||||
|
fontFamily: "var(--mono)",
|
||||||
|
padding: "2px 6px",
|
||||||
|
flexShrink: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const duration = formatDuration(agent.startedAt, agent.endedAt);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={className}
|
||||||
|
style={containerStyle}
|
||||||
|
role="region"
|
||||||
|
aria-label={`Agent output: ${agent.agentType}`}
|
||||||
|
data-testid="agent-terminal"
|
||||||
|
data-agent-id={agent.agentId}
|
||||||
|
>
|
||||||
|
{/* Header */}
|
||||||
|
<div style={headerStyle} data-testid="agent-terminal-header">
|
||||||
|
<StatusIndicator status={agent.status} />
|
||||||
|
|
||||||
|
<span style={titleStyle} data-testid="agent-type-label">
|
||||||
|
{agent.agentType}
|
||||||
|
{agent.jobId !== undefined ? ` · ${agent.jobId}` : ""}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<StatusBadge status={agent.status} />
|
||||||
|
|
||||||
|
<span style={durationStyle} data-testid="agent-duration">
|
||||||
|
{duration}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{/* Copy button */}
|
||||||
|
<button
|
||||||
|
aria-label="Copy agent output"
|
||||||
|
style={copyButtonStyle}
|
||||||
|
onClick={handleCopy}
|
||||||
|
data-testid="copy-button"
|
||||||
|
onMouseEnter={(e): void => {
|
||||||
|
if (!copied) {
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.color = "var(--text)";
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.borderColor = "var(--text-2)";
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e): void => {
|
||||||
|
if (!copied) {
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.color = "var(--muted)";
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.borderColor = "var(--border)";
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{copied ? "copied" : "copy"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Output area */}
|
||||||
|
<pre
|
||||||
|
ref={outputRef}
|
||||||
|
style={outputStyle}
|
||||||
|
data-testid="agent-output"
|
||||||
|
aria-label="Agent output log"
|
||||||
|
aria-live="polite"
|
||||||
|
aria-atomic="false"
|
||||||
|
>
|
||||||
|
{agent.outputLines.length === 0 ? (
|
||||||
|
<span style={{ color: "var(--muted)" }}>
|
||||||
|
{agent.status === "spawning" ? "Spawning agent..." : "Waiting for output..."}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
agent.outputLines.map(stripAnsi).join("")
|
||||||
|
)}
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
{/* Error message overlay */}
|
||||||
|
{agent.status === "error" && agent.errorMessage !== undefined && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: "4px 12px",
|
||||||
|
fontSize: "0.7rem",
|
||||||
|
fontFamily: "var(--mono)",
|
||||||
|
color: "var(--danger)",
|
||||||
|
background: "var(--bg-deep)",
|
||||||
|
borderTop: "1px solid var(--border)",
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
data-testid="agent-error-message"
|
||||||
|
role="alert"
|
||||||
|
>
|
||||||
|
Error: {agent.errorMessage}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Pulse animation keyframes — injected inline via style tag for zero deps */}
|
||||||
|
<style>{`
|
||||||
|
@keyframes agentPulse {
|
||||||
|
0%, 100% { opacity: 1; }
|
||||||
|
50% { opacity: 0.4; }
|
||||||
|
}
|
||||||
|
`}</style>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -33,6 +33,20 @@ vi.mock("./XTerminal", () => ({
|
|||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Mock AgentTerminal to avoid complexity in panel tests
|
||||||
|
vi.mock("./AgentTerminal", () => ({
|
||||||
|
AgentTerminal: vi.fn(
|
||||||
|
({ agent }: { agent: { agentId: string; agentType: string; status: string } }) => (
|
||||||
|
<div
|
||||||
|
data-testid="mock-agent-terminal"
|
||||||
|
data-agent-id={agent.agentId}
|
||||||
|
data-agent-type={agent.agentType}
|
||||||
|
data-status={agent.status}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
// Mock useTerminalSessions
|
// Mock useTerminalSessions
|
||||||
const mockCreateSession = vi.fn();
|
const mockCreateSession = vi.fn();
|
||||||
const mockCloseSession = vi.fn();
|
const mockCloseSession = vi.fn();
|
||||||
@@ -72,6 +86,29 @@ vi.mock("@/hooks/useTerminalSessions", () => ({
|
|||||||
})),
|
})),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Mock useAgentStream
|
||||||
|
const mockDismissAgent = vi.fn();
|
||||||
|
let mockAgents = new Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
agentId: string;
|
||||||
|
agentType: string;
|
||||||
|
status: "spawning" | "running" | "completed" | "error";
|
||||||
|
outputLines: string[];
|
||||||
|
startedAt: number;
|
||||||
|
}
|
||||||
|
>();
|
||||||
|
let mockAgentStreamConnected = false;
|
||||||
|
|
||||||
|
vi.mock("@/hooks/useAgentStream", () => ({
|
||||||
|
useAgentStream: vi.fn(() => ({
|
||||||
|
agents: mockAgents,
|
||||||
|
isConnected: mockAgentStreamConnected,
|
||||||
|
connectionError: null,
|
||||||
|
dismissAgent: mockDismissAgent,
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
import { TerminalPanel } from "./TerminalPanel";
|
import { TerminalPanel } from "./TerminalPanel";
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -100,6 +137,8 @@ describe("TerminalPanel", () => {
|
|||||||
mockIsConnected = false;
|
mockIsConnected = false;
|
||||||
mockConnectionError = null;
|
mockConnectionError = null;
|
||||||
mockRegisterOutputCallback.mockReturnValue(vi.fn());
|
mockRegisterOutputCallback.mockReturnValue(vi.fn());
|
||||||
|
mockAgents = new Map();
|
||||||
|
mockAgentStreamConnected = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -425,4 +464,118 @@ describe("TerminalPanel", () => {
|
|||||||
expect(mockCreateSession).not.toHaveBeenCalled();
|
expect(mockCreateSession).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Agent tab integration
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("agent tab integration", () => {
|
||||||
|
function setOneAgent(status: "spawning" | "running" | "completed" | "error" = "running"): void {
|
||||||
|
mockAgents = new Map([
|
||||||
|
[
|
||||||
|
"agent-1",
|
||||||
|
{
|
||||||
|
agentId: "agent-1",
|
||||||
|
agentType: "worker",
|
||||||
|
status,
|
||||||
|
outputLines: ["Hello from agent\n"],
|
||||||
|
startedAt: Date.now() - 3000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
it("renders an agent tab when an agent is active", () => {
|
||||||
|
setOneAgent("running");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(screen.getAllByTestId("agent-tab")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders no agent tabs when agents map is empty", () => {
|
||||||
|
mockAgents = new Map();
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(screen.queryByTestId("agent-tab")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("agent tab button has the agent type as label", () => {
|
||||||
|
setOneAgent("running");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(screen.getByRole("tab", { name: "Agent: worker" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("agent tab has role=tab", () => {
|
||||||
|
setOneAgent("running");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(screen.getByRole("tab", { name: "Agent: worker" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows dismiss button for completed agents", () => {
|
||||||
|
setOneAgent("completed");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(screen.getByRole("button", { name: "Dismiss worker agent" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows dismiss button for error agents", () => {
|
||||||
|
setOneAgent("error");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(screen.getByRole("button", { name: "Dismiss worker agent" })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not show dismiss button for running agents", () => {
|
||||||
|
setOneAgent("running");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("button", { name: "Dismiss worker agent" })
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not show dismiss button for spawning agents", () => {
|
||||||
|
setOneAgent("spawning");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("button", { name: "Dismiss worker agent" })
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls dismissAgent when dismiss button is clicked", () => {
|
||||||
|
setOneAgent("completed");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Dismiss worker agent" }));
|
||||||
|
expect(mockDismissAgent).toHaveBeenCalledWith("agent-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders AgentTerminal when agent tab is active", () => {
|
||||||
|
setOneAgent("running");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
// Click the agent tab to make it active
|
||||||
|
fireEvent.click(screen.getByRole("tab", { name: "Agent: worker" }));
|
||||||
|
// AgentTerminal should be rendered (mock shows mock-agent-terminal)
|
||||||
|
expect(screen.getByTestId("mock-agent-terminal")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a divider between terminal and agent tabs", () => {
|
||||||
|
setTwoSessions();
|
||||||
|
setOneAgent("running");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
// The divider div is aria-hidden; check it's present in the DOM
|
||||||
|
const tablist = screen.getByRole("tablist");
|
||||||
|
const divider = tablist.querySelector('[aria-hidden="true"][style*="width: 1"]');
|
||||||
|
expect(divider).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("agent tabs show correct data-agent-status", () => {
|
||||||
|
setOneAgent("running");
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
const tab = screen.getByTestId("agent-tab");
|
||||||
|
expect(tab).toHaveAttribute("data-agent-status", "running");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("empty state not shown when agents exist but no terminal sessions", () => {
|
||||||
|
mockSessions = new Map();
|
||||||
|
setOneAgent("running");
|
||||||
|
mockIsConnected = false;
|
||||||
|
render((<TerminalPanel open={true} onClose={onClose} token="test-token" />) as ReactElement);
|
||||||
|
expect(screen.queryByText("Connecting...")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,18 +7,25 @@
|
|||||||
* rendering one XTerminal per session and keeping all instances mounted (for
|
* rendering one XTerminal per session and keeping all instances mounted (for
|
||||||
* scrollback preservation) while switching visibility with display:none.
|
* scrollback preservation) while switching visibility with display:none.
|
||||||
*
|
*
|
||||||
|
* Also renders read-only agent output tabs from the orchestrator SSE stream
|
||||||
|
* via useAgentStream. Agent tabs are automatically added when agents are active
|
||||||
|
* and can be dismissed when completed or errored.
|
||||||
|
*
|
||||||
* Features:
|
* Features:
|
||||||
* - "+" button to open a new tab
|
* - "+" button to open a new terminal tab
|
||||||
* - Per-tab close button
|
* - Per-tab close button (terminal) / dismiss button (agent)
|
||||||
* - Double-click tab label for inline rename
|
* - Double-click tab label for inline rename (terminal tabs only)
|
||||||
* - Auto-creates the first session on connect
|
* - Auto-creates the first terminal session on connect
|
||||||
* - Connection error state
|
* - Connection error state
|
||||||
|
* - Agent tabs: read-only, auto-appear, dismissable
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useState, useEffect, useRef, useCallback } from "react";
|
import { useState, useEffect, useRef, useCallback } from "react";
|
||||||
import type { ReactElement, CSSProperties, KeyboardEvent } from "react";
|
import type { ReactElement, CSSProperties, KeyboardEvent } from "react";
|
||||||
import { XTerminal } from "./XTerminal";
|
import { XTerminal } from "./XTerminal";
|
||||||
|
import { AgentTerminal } from "./AgentTerminal";
|
||||||
import { useTerminalSessions } from "@/hooks/useTerminalSessions";
|
import { useTerminalSessions } from "@/hooks/useTerminalSessions";
|
||||||
|
import { useAgentStream } from "@/hooks/useAgentStream";
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// Types
|
// Types
|
||||||
@@ -59,6 +66,42 @@ export function TerminalPanel({
|
|||||||
registerOutputCallback,
|
registerOutputCallback,
|
||||||
} = useTerminalSessions({ token });
|
} = useTerminalSessions({ token });
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Agent stream
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const { agents, dismissAgent } = useAgentStream();
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Active tab state (terminal session OR agent)
|
||||||
|
// "terminal:<sessionId>" or "agent:<agentId>"
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
type TabId = string; // prefix-qualified: "terminal:<id>" or "agent:<id>"
|
||||||
|
|
||||||
|
const [activeTabId, setActiveTabId] = useState<TabId | null>(null);
|
||||||
|
|
||||||
|
// Sync activeTabId with the terminal session activeSessionId when no agent tab is selected
|
||||||
|
useEffect(() => {
|
||||||
|
setActiveTabId((prev) => {
|
||||||
|
// If an agent tab is active, don't clobber it
|
||||||
|
if (prev?.startsWith("agent:")) return prev;
|
||||||
|
// Reflect active terminal session
|
||||||
|
if (activeSessionId !== null) return `terminal:${activeSessionId}`;
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
}, [activeSessionId]);
|
||||||
|
|
||||||
|
// If the active agent tab is dismissed, fall back to the terminal session
|
||||||
|
useEffect(() => {
|
||||||
|
if (activeTabId?.startsWith("agent:")) {
|
||||||
|
const agentId = activeTabId.slice("agent:".length);
|
||||||
|
if (!agents.has(agentId)) {
|
||||||
|
setActiveTabId(activeSessionId !== null ? `terminal:${activeSessionId}` : null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [agents, activeTabId, activeSessionId]);
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// Inline rename state
|
// Inline rename state
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -187,6 +230,16 @@ export function TerminalPanel({
|
|||||||
position: "relative",
|
position: "relative",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Agent status dot color
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const agentDotColor = (status: string): string => {
|
||||||
|
if (status === "running" || status === "spawning") return "var(--success)";
|
||||||
|
if (status === "error") return "var(--danger)";
|
||||||
|
return "var(--muted)";
|
||||||
|
};
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// Render
|
// Render
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -203,8 +256,10 @@ export function TerminalPanel({
|
|||||||
<div style={headerStyle}>
|
<div style={headerStyle}>
|
||||||
{/* Tab bar */}
|
{/* Tab bar */}
|
||||||
<div style={tabBarStyle} role="tablist" aria-label="Terminal tabs">
|
<div style={tabBarStyle} role="tablist" aria-label="Terminal tabs">
|
||||||
|
{/* ---- Terminal session tabs ---- */}
|
||||||
{[...sessions.entries()].map(([sessionId, sessionInfo]) => {
|
{[...sessions.entries()].map(([sessionId, sessionInfo]) => {
|
||||||
const isActive = sessionId === activeSessionId;
|
const tabKey = `terminal:${sessionId}`;
|
||||||
|
const isActive = tabKey === activeTabId;
|
||||||
const isEditing = sessionId === editingTabId;
|
const isEditing = sessionId === editingTabId;
|
||||||
|
|
||||||
const tabStyle: CSSProperties = {
|
const tabStyle: CSSProperties = {
|
||||||
@@ -223,7 +278,7 @@ export function TerminalPanel({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={sessionId} style={tabStyle}>
|
<div key={tabKey} style={tabStyle}>
|
||||||
{isEditing ? (
|
{isEditing ? (
|
||||||
<input
|
<input
|
||||||
ref={editInputRef}
|
ref={editInputRef}
|
||||||
@@ -262,6 +317,7 @@ export function TerminalPanel({
|
|||||||
padding: 0,
|
padding: 0,
|
||||||
}}
|
}}
|
||||||
onClick={(): void => {
|
onClick={(): void => {
|
||||||
|
setActiveTabId(tabKey);
|
||||||
setActiveSession(sessionId);
|
setActiveSession(sessionId);
|
||||||
}}
|
}}
|
||||||
onDoubleClick={(): void => {
|
onDoubleClick={(): void => {
|
||||||
@@ -364,6 +420,146 @@ export function TerminalPanel({
|
|||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{/* ---- Agent section divider (only when agents exist) ---- */}
|
||||||
|
{agents.size > 0 && (
|
||||||
|
<div
|
||||||
|
aria-hidden="true"
|
||||||
|
style={{
|
||||||
|
width: 1,
|
||||||
|
height: 16,
|
||||||
|
background: "var(--border)",
|
||||||
|
marginLeft: 6,
|
||||||
|
marginRight: 4,
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ---- Agent tabs ---- */}
|
||||||
|
{[...agents.entries()].map(([agentId, agentSession]) => {
|
||||||
|
const tabKey = `agent:${agentId}`;
|
||||||
|
const isActive = tabKey === activeTabId;
|
||||||
|
|
||||||
|
const canDismiss =
|
||||||
|
agentSession.status === "completed" || agentSession.status === "error";
|
||||||
|
|
||||||
|
const agentTabStyle: CSSProperties = {
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 4,
|
||||||
|
padding: "3px 6px 3px 8px",
|
||||||
|
borderRadius: 4,
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
fontFamily: "var(--mono)",
|
||||||
|
color: isActive ? "var(--text)" : "var(--muted)",
|
||||||
|
background: isActive ? "var(--surface)" : "transparent",
|
||||||
|
border: "none",
|
||||||
|
outline: "none",
|
||||||
|
flexShrink: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={tabKey}
|
||||||
|
style={agentTabStyle}
|
||||||
|
data-testid="agent-tab"
|
||||||
|
data-agent-id={agentId}
|
||||||
|
data-agent-status={agentSession.status}
|
||||||
|
>
|
||||||
|
{/* Status dot */}
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
style={{
|
||||||
|
display: "inline-block",
|
||||||
|
width: 6,
|
||||||
|
height: 6,
|
||||||
|
borderRadius: "50%",
|
||||||
|
background: agentDotColor(agentSession.status),
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Agent tab button — read-only, no rename */}
|
||||||
|
<button
|
||||||
|
role="tab"
|
||||||
|
aria-selected={isActive}
|
||||||
|
style={{
|
||||||
|
background: "transparent",
|
||||||
|
border: "none",
|
||||||
|
outline: "none",
|
||||||
|
fontFamily: "var(--mono)",
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
color: isActive ? "var(--text)" : "var(--muted)",
|
||||||
|
cursor: "pointer",
|
||||||
|
padding: 0,
|
||||||
|
maxWidth: 100,
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
onClick={(): void => {
|
||||||
|
setActiveTabId(tabKey);
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e): void => {
|
||||||
|
if (!isActive) {
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.color = "var(--text-2)";
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e): void => {
|
||||||
|
if (!isActive) {
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.color = "var(--muted)";
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
aria-label={`Agent: ${agentSession.agentType}`}
|
||||||
|
>
|
||||||
|
{agentSession.agentType}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Dismiss button — only for completed/error agents */}
|
||||||
|
{canDismiss && (
|
||||||
|
<button
|
||||||
|
aria-label={`Dismiss ${agentSession.agentType} agent`}
|
||||||
|
style={{
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
borderRadius: 3,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
color: "var(--muted)",
|
||||||
|
cursor: "pointer",
|
||||||
|
background: "transparent",
|
||||||
|
border: "none",
|
||||||
|
outline: "none",
|
||||||
|
padding: 0,
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
onClick={(): void => {
|
||||||
|
dismissAgent(agentId);
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e): void => {
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.background = "var(--surface)";
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.color = "var(--text)";
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e): void => {
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.background = "transparent";
|
||||||
|
(e.currentTarget as HTMLButtonElement).style.color = "var(--muted)";
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg width="8" height="8" viewBox="0 0 8 8" fill="none" aria-hidden="true">
|
||||||
|
<path
|
||||||
|
d="M1 1L7 7M7 1L1 7"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Action buttons */}
|
{/* Action buttons */}
|
||||||
@@ -428,8 +624,10 @@ export function TerminalPanel({
|
|||||||
|
|
||||||
{/* Terminal body — keep all XTerminal instances mounted for scrollback */}
|
{/* Terminal body — keep all XTerminal instances mounted for scrollback */}
|
||||||
<div style={bodyStyle}>
|
<div style={bodyStyle}>
|
||||||
|
{/* ---- Terminal session panels ---- */}
|
||||||
{[...sessions.entries()].map(([sessionId, sessionInfo]) => {
|
{[...sessions.entries()].map(([sessionId, sessionInfo]) => {
|
||||||
const isActive = sessionId === activeSessionId;
|
const tabKey = `terminal:${sessionId}`;
|
||||||
|
const isActive = tabKey === activeTabId;
|
||||||
const termStyle: CSSProperties = {
|
const termStyle: CSSProperties = {
|
||||||
display: isActive ? "flex" : "none",
|
display: isActive ? "flex" : "none",
|
||||||
flex: 1,
|
flex: 1,
|
||||||
@@ -438,7 +636,7 @@ export function TerminalPanel({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={sessionId} style={termStyle}>
|
<div key={tabKey} style={termStyle}>
|
||||||
<XTerminal
|
<XTerminal
|
||||||
sessionId={sessionId}
|
sessionId={sessionId}
|
||||||
sendInput={sendInput}
|
sendInput={sendInput}
|
||||||
@@ -458,8 +656,26 @@ export function TerminalPanel({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
{/* Empty state */}
|
{/* ---- Agent session panels ---- */}
|
||||||
{sessions.size === 0 && (
|
{[...agents.entries()].map(([agentId, agentSession]) => {
|
||||||
|
const tabKey = `agent:${agentId}`;
|
||||||
|
const isActive = tabKey === activeTabId;
|
||||||
|
const agentPanelStyle: CSSProperties = {
|
||||||
|
display: isActive ? "flex" : "none",
|
||||||
|
flex: 1,
|
||||||
|
flexDirection: "column",
|
||||||
|
minHeight: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={tabKey} style={agentPanelStyle}>
|
||||||
|
<AgentTerminal agent={agentSession} style={{ flex: 1, minHeight: 0 }} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{/* Empty state — show only when no terminal sessions AND no agent sessions */}
|
||||||
|
{sessions.size === 0 && agents.size === 0 && (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
flex: 1,
|
flex: 1,
|
||||||
|
|||||||
@@ -2,3 +2,5 @@ export type { TerminalPanelProps } from "./TerminalPanel";
|
|||||||
export { TerminalPanel } from "./TerminalPanel";
|
export { TerminalPanel } from "./TerminalPanel";
|
||||||
export type { XTerminalProps } from "./XTerminal";
|
export type { XTerminalProps } from "./XTerminal";
|
||||||
export { XTerminal } from "./XTerminal";
|
export { XTerminal } from "./XTerminal";
|
||||||
|
export type { AgentTerminalProps } from "./AgentTerminal";
|
||||||
|
export { AgentTerminal } from "./AgentTerminal";
|
||||||
|
|||||||
542
apps/web/src/hooks/__tests__/useAgentStream.test.ts
Normal file
542
apps/web/src/hooks/__tests__/useAgentStream.test.ts
Normal file
@@ -0,0 +1,542 @@
|
|||||||
|
/**
|
||||||
|
* @file useAgentStream.test.ts
|
||||||
|
* @description Unit tests for the useAgentStream hook
|
||||||
|
*
|
||||||
|
* Tests cover:
|
||||||
|
* - SSE event parsing (agent:spawned, agent:output, agent:completed, agent:error)
|
||||||
|
* - Agent lifecycle state transitions
|
||||||
|
* - Auto-reconnect behavior on connection loss
|
||||||
|
* - Cleanup on unmount
|
||||||
|
* - Dismiss agent
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { renderHook, act } from "@testing-library/react";
|
||||||
|
import { useAgentStream } from "../useAgentStream";
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Mock EventSource
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
interface MockEventSourceInstance {
|
||||||
|
url: string;
|
||||||
|
onopen: (() => void) | null;
|
||||||
|
onerror: ((event: Event) => void) | null;
|
||||||
|
onmessage: ((event: MessageEvent) => void) | null;
|
||||||
|
close: ReturnType<typeof vi.fn>;
|
||||||
|
addEventListener: ReturnType<typeof vi.fn>;
|
||||||
|
dispatchEvent: (type: string, data: string) => void;
|
||||||
|
_listeners: Map<string, ((event: MessageEvent<string>) => void)[]>;
|
||||||
|
readyState: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mockEventSourceInstances: MockEventSourceInstance[] = [];
|
||||||
|
|
||||||
|
const MockEventSource = vi.fn(function (this: MockEventSourceInstance, url: string): void {
|
||||||
|
this.url = url;
|
||||||
|
this.onopen = null;
|
||||||
|
this.onerror = null;
|
||||||
|
this.onmessage = null;
|
||||||
|
this.close = vi.fn();
|
||||||
|
this.readyState = 0;
|
||||||
|
this._listeners = new Map();
|
||||||
|
|
||||||
|
this.addEventListener = vi.fn(
|
||||||
|
(type: string, handler: (event: MessageEvent<string>) => void): void => {
|
||||||
|
if (!this._listeners.has(type)) {
|
||||||
|
this._listeners.set(type, []);
|
||||||
|
}
|
||||||
|
const list = this._listeners.get(type);
|
||||||
|
if (list) list.push(handler);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
this.dispatchEvent = (type: string, data: string): void => {
|
||||||
|
const handlers = this._listeners.get(type) ?? [];
|
||||||
|
const event = new MessageEvent(type, { data });
|
||||||
|
for (const handler of handlers) {
|
||||||
|
handler(event);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
mockEventSourceInstances.push(this);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add static constants
|
||||||
|
Object.assign(MockEventSource, {
|
||||||
|
CONNECTING: 0,
|
||||||
|
OPEN: 1,
|
||||||
|
CLOSED: 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.stubGlobal("EventSource", MockEventSource);
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Helpers
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
function getLatestES(): MockEventSourceInstance {
|
||||||
|
const es = mockEventSourceInstances[mockEventSourceInstances.length - 1];
|
||||||
|
if (!es) throw new Error("No EventSource instance created");
|
||||||
|
return es;
|
||||||
|
}
|
||||||
|
|
||||||
|
function triggerOpen(): void {
|
||||||
|
const es = getLatestES();
|
||||||
|
if (es.onopen) es.onopen();
|
||||||
|
}
|
||||||
|
|
||||||
|
function triggerError(): void {
|
||||||
|
const es = getLatestES();
|
||||||
|
if (es.onerror) es.onerror(new Event("error"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function emitEvent(type: string, data: unknown): void {
|
||||||
|
const es = getLatestES();
|
||||||
|
es.dispatchEvent(type, JSON.stringify(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Tests
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("useAgentStream", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.useFakeTimers();
|
||||||
|
mockEventSourceInstances = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.runAllTimers();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Initialization
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("initialization", () => {
|
||||||
|
it("creates an EventSource connecting to /api/orchestrator/events", () => {
|
||||||
|
renderHook(() => useAgentStream());
|
||||||
|
expect(MockEventSource).toHaveBeenCalledWith("/api/orchestrator/events");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("starts with isConnected=false before onopen fires", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
expect(result.current.isConnected).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("starts with an empty agents map", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
expect(result.current.agents.size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets isConnected=true when EventSource opens", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
});
|
||||||
|
expect(result.current.isConnected).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears connectionError when EventSource opens", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
// Trigger an error first to set connectionError
|
||||||
|
act(() => {
|
||||||
|
triggerError();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start a fresh reconnect and open it
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(2000);
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.connectionError).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// SSE event: agent:spawned
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("agent:spawned event", () => {
|
||||||
|
it("adds an agent with status=spawning", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker", jobId: "job-abc" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.has("agent-1")).toBe(true);
|
||||||
|
expect(result.current.agents.get("agent-1")?.status).toBe("spawning");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets agentType from the type field", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "planner" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.agentType).toBe("planner");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("defaults agentType to 'agent' when type is missing", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-2" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-2")?.agentType).toBe("agent");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stores jobId when present", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-3", type: "worker", jobId: "job-xyz" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-3")?.jobId).toBe("job-xyz");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("starts with empty outputLines", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.outputLines).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// SSE event: agent:output
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("agent:output event", () => {
|
||||||
|
it("appends output to the agent's outputLines", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:output", { agentId: "agent-1", data: "Hello world\n" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.outputLines).toContain("Hello world\n");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transitions status from spawning to running on first output", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:output", { agentId: "agent-1", data: "Starting...\n" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.status).toBe("running");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accumulates multiple output lines", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:output", { agentId: "agent-1", data: "Line 1\n" });
|
||||||
|
emitEvent("agent:output", { agentId: "agent-1", data: "Line 2\n" });
|
||||||
|
emitEvent("agent:output", { agentId: "agent-1", data: "Line 3\n" });
|
||||||
|
});
|
||||||
|
|
||||||
|
const lines = result.current.agents.get("agent-1")?.outputLines ?? [];
|
||||||
|
expect(lines).toHaveLength(3);
|
||||||
|
expect(lines[0]).toBe("Line 1\n");
|
||||||
|
expect(lines[1]).toBe("Line 2\n");
|
||||||
|
expect(lines[2]).toBe("Line 3\n");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("creates a new agent entry if output arrives before spawned event", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:output", { agentId: "unknown-agent", data: "Surprise output\n" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.has("unknown-agent")).toBe(true);
|
||||||
|
expect(result.current.agents.get("unknown-agent")?.status).toBe("running");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// SSE event: agent:completed
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("agent:completed event", () => {
|
||||||
|
it("sets status to completed", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:output", { agentId: "agent-1", data: "Working...\n" });
|
||||||
|
emitEvent("agent:completed", { agentId: "agent-1", exitCode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.status).toBe("completed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stores the exitCode", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:completed", { agentId: "agent-1", exitCode: 42 });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.exitCode).toBe(42);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets endedAt timestamp", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:completed", { agentId: "agent-1", exitCode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.endedAt).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores completed event for unknown agent", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:completed", { agentId: "ghost-agent", exitCode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.has("ghost-agent")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// SSE event: agent:error
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("agent:error event", () => {
|
||||||
|
it("sets status to error", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:error", { agentId: "agent-1", error: "Out of memory" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.status).toBe("error");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stores the error message", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:error", { agentId: "agent-1", error: "Segfault" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.errorMessage).toBe("Segfault");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets endedAt on error", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:error", { agentId: "agent-1", error: "Crash" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.get("agent-1")?.endedAt).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores error event for unknown agent", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:error", { agentId: "ghost-agent", error: "Crash" });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.has("ghost-agent")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Reconnect behavior
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("auto-reconnect", () => {
|
||||||
|
it("sets isConnected=false on error", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
triggerError();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.isConnected).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets connectionError on error", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
triggerError();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.connectionError).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("creates a new EventSource after reconnect delay", () => {
|
||||||
|
renderHook(() => useAgentStream());
|
||||||
|
const initialCount = mockEventSourceInstances.length;
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
triggerError();
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(1500); // initial backoff = 1000ms
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mockEventSourceInstances.length).toBeGreaterThan(initialCount);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("closes the old EventSource before reconnecting", () => {
|
||||||
|
renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
triggerError();
|
||||||
|
});
|
||||||
|
|
||||||
|
const closedInstance = mockEventSourceInstances[0];
|
||||||
|
expect(closedInstance?.close).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Cleanup on unmount
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("cleanup on unmount", () => {
|
||||||
|
it("closes EventSource when the hook is unmounted", () => {
|
||||||
|
const { unmount } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
const es = getLatestES();
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
expect(es.close).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not attempt to reconnect after unmount", () => {
|
||||||
|
const { unmount } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
triggerError();
|
||||||
|
});
|
||||||
|
|
||||||
|
const countBeforeUnmount = mockEventSourceInstances.length;
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(5000);
|
||||||
|
});
|
||||||
|
|
||||||
|
// No new instances created after unmount
|
||||||
|
expect(mockEventSourceInstances.length).toBe(countBeforeUnmount);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Dismiss agent
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("dismissAgent", () => {
|
||||||
|
it("removes the agent from the map", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
emitEvent("agent:completed", { agentId: "agent-1", exitCode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.dismissAgent("agent-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.has("agent-1")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is a no-op for unknown agentId", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
emitEvent("agent:spawned", { agentId: "agent-1", type: "worker" });
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.dismissAgent("nonexistent-agent");
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.agents.has("agent-1")).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Malformed event handling
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
describe("malformed events", () => {
|
||||||
|
it("ignores malformed JSON without throwing", () => {
|
||||||
|
const { result } = renderHook(() => useAgentStream());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
triggerOpen();
|
||||||
|
// Dispatch raw bad JSON
|
||||||
|
const es = getLatestES();
|
||||||
|
es.dispatchEvent("agent:spawned", "NOT JSON {{{");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Should not crash, agents map stays empty
|
||||||
|
expect(result.current.agents.size).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
319
apps/web/src/hooks/useAgentStream.ts
Normal file
319
apps/web/src/hooks/useAgentStream.ts
Normal file
@@ -0,0 +1,319 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* useAgentStream hook
|
||||||
|
*
|
||||||
|
* Connects to the orchestrator SSE event stream at /api/orchestrator/events
|
||||||
|
* and maintains a Map of agentId → AgentSession with accumulated output,
|
||||||
|
* status, and lifecycle metadata.
|
||||||
|
*
|
||||||
|
* SSE event types consumed:
|
||||||
|
* - agent:spawned — { agentId, type, jobId }
|
||||||
|
* - agent:output — { agentId, data } (stdout/stderr lines)
|
||||||
|
* - agent:completed — { agentId, exitCode, result }
|
||||||
|
* - agent:error — { agentId, error }
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - Auto-reconnect with exponential backoff on connection loss
|
||||||
|
* - Cleans up EventSource on unmount
|
||||||
|
* - Accumulates output lines per agent
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState, useCallback } from "react";
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Types
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
export type AgentStatus = "spawning" | "running" | "completed" | "error";
|
||||||
|
|
||||||
|
export interface AgentSession {
|
||||||
|
/** Agent identifier from the orchestrator */
|
||||||
|
agentId: string;
|
||||||
|
/** Agent type or name (e.g., "worker", "planner") */
|
||||||
|
agentType: string;
|
||||||
|
/** Optional job ID this agent is associated with */
|
||||||
|
jobId?: string;
|
||||||
|
/** Current lifecycle status */
|
||||||
|
status: AgentStatus;
|
||||||
|
/** Accumulated output lines (stdout/stderr) */
|
||||||
|
outputLines: string[];
|
||||||
|
/** Timestamp when the agent was spawned */
|
||||||
|
startedAt: number;
|
||||||
|
/** Timestamp when the agent completed or errored */
|
||||||
|
endedAt?: number;
|
||||||
|
/** Exit code from agent:completed event */
|
||||||
|
exitCode?: number;
|
||||||
|
/** Error message from agent:error event */
|
||||||
|
errorMessage?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UseAgentStreamReturn {
|
||||||
|
/** Map of agentId → AgentSession */
|
||||||
|
agents: Map<string, AgentSession>;
|
||||||
|
/** Whether the SSE stream is currently connected */
|
||||||
|
isConnected: boolean;
|
||||||
|
/** Connection error message, if any */
|
||||||
|
connectionError: string | null;
|
||||||
|
/** Dismiss (remove) an agent tab by agentId */
|
||||||
|
dismissAgent: (agentId: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// SSE payload shapes
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
interface SpawnedPayload {
|
||||||
|
agentId: string;
|
||||||
|
type?: string;
|
||||||
|
jobId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OutputPayload {
|
||||||
|
agentId: string;
|
||||||
|
data: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CompletedPayload {
|
||||||
|
agentId: string;
|
||||||
|
exitCode?: number;
|
||||||
|
result?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ErrorPayload {
|
||||||
|
agentId: string;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Backoff config
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const RECONNECT_BASE_MS = 1_000;
|
||||||
|
const RECONNECT_MAX_MS = 30_000;
|
||||||
|
const RECONNECT_MULTIPLIER = 2;
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Hook
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connects to the orchestrator SSE stream and tracks all agent sessions.
|
||||||
|
*
|
||||||
|
* @returns Agent sessions map, connection status, and dismiss callback
|
||||||
|
*/
|
||||||
|
export function useAgentStream(): UseAgentStreamReturn {
|
||||||
|
const [agents, setAgents] = useState<Map<string, AgentSession>>(new Map());
|
||||||
|
const [isConnected, setIsConnected] = useState(false);
|
||||||
|
const [connectionError, setConnectionError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const eventSourceRef = useRef<EventSource | null>(null);
|
||||||
|
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const reconnectDelayRef = useRef<number>(RECONNECT_BASE_MS);
|
||||||
|
const isMountedRef = useRef(true);
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Agent state update helpers
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const handleAgentSpawned = useCallback((payload: SpawnedPayload): void => {
|
||||||
|
setAgents((prev) => {
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.set(payload.agentId, {
|
||||||
|
agentId: payload.agentId,
|
||||||
|
agentType: payload.type ?? "agent",
|
||||||
|
...(payload.jobId !== undefined ? { jobId: payload.jobId } : {}),
|
||||||
|
status: "spawning",
|
||||||
|
outputLines: [],
|
||||||
|
startedAt: Date.now(),
|
||||||
|
});
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleAgentOutput = useCallback((payload: OutputPayload): void => {
|
||||||
|
setAgents((prev) => {
|
||||||
|
const existing = prev.get(payload.agentId);
|
||||||
|
if (!existing) {
|
||||||
|
// First output for an agent we haven't seen spawned — create it
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.set(payload.agentId, {
|
||||||
|
agentId: payload.agentId,
|
||||||
|
agentType: "agent",
|
||||||
|
status: "running",
|
||||||
|
outputLines: [payload.data],
|
||||||
|
startedAt: Date.now(),
|
||||||
|
});
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.set(payload.agentId, {
|
||||||
|
...existing,
|
||||||
|
status: existing.status === "spawning" ? "running" : existing.status,
|
||||||
|
outputLines: [...existing.outputLines, payload.data],
|
||||||
|
});
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleAgentCompleted = useCallback((payload: CompletedPayload): void => {
|
||||||
|
setAgents((prev) => {
|
||||||
|
const existing = prev.get(payload.agentId);
|
||||||
|
if (!existing) return prev;
|
||||||
|
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.set(payload.agentId, {
|
||||||
|
...existing,
|
||||||
|
status: "completed",
|
||||||
|
endedAt: Date.now(),
|
||||||
|
...(payload.exitCode !== undefined ? { exitCode: payload.exitCode } : {}),
|
||||||
|
});
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleAgentError = useCallback((payload: ErrorPayload): void => {
|
||||||
|
setAgents((prev) => {
|
||||||
|
const existing = prev.get(payload.agentId);
|
||||||
|
if (!existing) return prev;
|
||||||
|
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.set(payload.agentId, {
|
||||||
|
...existing,
|
||||||
|
status: "error",
|
||||||
|
endedAt: Date.now(),
|
||||||
|
...(payload.error !== undefined ? { errorMessage: payload.error } : {}),
|
||||||
|
});
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// SSE connection
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const connect = useCallback((): void => {
|
||||||
|
if (!isMountedRef.current) return;
|
||||||
|
if (typeof EventSource === "undefined") return;
|
||||||
|
|
||||||
|
// Clean up any existing connection
|
||||||
|
if (eventSourceRef.current) {
|
||||||
|
eventSourceRef.current.close();
|
||||||
|
eventSourceRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const es = new EventSource("/api/orchestrator/events");
|
||||||
|
eventSourceRef.current = es;
|
||||||
|
|
||||||
|
es.onopen = (): void => {
|
||||||
|
if (!isMountedRef.current) return;
|
||||||
|
setIsConnected(true);
|
||||||
|
setConnectionError(null);
|
||||||
|
reconnectDelayRef.current = RECONNECT_BASE_MS;
|
||||||
|
};
|
||||||
|
|
||||||
|
es.onerror = (): void => {
|
||||||
|
if (!isMountedRef.current) return;
|
||||||
|
setIsConnected(false);
|
||||||
|
|
||||||
|
es.close();
|
||||||
|
eventSourceRef.current = null;
|
||||||
|
|
||||||
|
// Schedule reconnect with backoff
|
||||||
|
const delay = reconnectDelayRef.current;
|
||||||
|
reconnectDelayRef.current = Math.min(delay * RECONNECT_MULTIPLIER, RECONNECT_MAX_MS);
|
||||||
|
|
||||||
|
const delaySecs = Math.round(delay / 1000).toString();
|
||||||
|
setConnectionError(`SSE connection lost. Reconnecting in ${delaySecs}s...`);
|
||||||
|
|
||||||
|
reconnectTimerRef.current = setTimeout(() => {
|
||||||
|
if (isMountedRef.current) {
|
||||||
|
connect();
|
||||||
|
}
|
||||||
|
}, delay);
|
||||||
|
};
|
||||||
|
|
||||||
|
es.addEventListener("agent:spawned", (event: MessageEvent<string>) => {
|
||||||
|
if (!isMountedRef.current) return;
|
||||||
|
try {
|
||||||
|
const payload = JSON.parse(event.data) as SpawnedPayload;
|
||||||
|
handleAgentSpawned(payload);
|
||||||
|
} catch {
|
||||||
|
// Ignore malformed events
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
es.addEventListener("agent:output", (event: MessageEvent<string>) => {
|
||||||
|
if (!isMountedRef.current) return;
|
||||||
|
try {
|
||||||
|
const payload = JSON.parse(event.data) as OutputPayload;
|
||||||
|
handleAgentOutput(payload);
|
||||||
|
} catch {
|
||||||
|
// Ignore malformed events
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
es.addEventListener("agent:completed", (event: MessageEvent<string>) => {
|
||||||
|
if (!isMountedRef.current) return;
|
||||||
|
try {
|
||||||
|
const payload = JSON.parse(event.data) as CompletedPayload;
|
||||||
|
handleAgentCompleted(payload);
|
||||||
|
} catch {
|
||||||
|
// Ignore malformed events
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
es.addEventListener("agent:error", (event: MessageEvent<string>) => {
|
||||||
|
if (!isMountedRef.current) return;
|
||||||
|
try {
|
||||||
|
const payload = JSON.parse(event.data) as ErrorPayload;
|
||||||
|
handleAgentError(payload);
|
||||||
|
} catch {
|
||||||
|
// Ignore malformed events
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, [handleAgentSpawned, handleAgentOutput, handleAgentCompleted, handleAgentError]);
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Mount / unmount
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
isMountedRef.current = true;
|
||||||
|
connect();
|
||||||
|
|
||||||
|
return (): void => {
|
||||||
|
isMountedRef.current = false;
|
||||||
|
|
||||||
|
if (reconnectTimerRef.current !== null) {
|
||||||
|
clearTimeout(reconnectTimerRef.current);
|
||||||
|
reconnectTimerRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eventSourceRef.current) {
|
||||||
|
eventSourceRef.current.close();
|
||||||
|
eventSourceRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [connect]);
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// Dismiss agent
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
const dismissAgent = useCallback((agentId: string): void => {
|
||||||
|
setAgents((prev) => {
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.delete(agentId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
agents,
|
||||||
|
isConnected,
|
||||||
|
connectionError,
|
||||||
|
dismissAgent,
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user