feat(FN-1586): update ChatView with model selector
- Add model selector to ChatView component for AI model selection - Update ChatView tests to cover model selector functionality - Add styles for model selector in chat interface
This commit is contained in:
@@ -10,19 +10,10 @@ import {
|
||||
Bot,
|
||||
} from "lucide-react";
|
||||
import { useChat } from "../hooks/useChat";
|
||||
import { useAgents } from "../hooks/useAgents";
|
||||
import { useViewportMode } from "./Header";
|
||||
import type { Agent } from "../api";
|
||||
|
||||
export interface ChatViewProps {
|
||||
projectId?: string;
|
||||
addToast: (msg: string, type?: "success" | "error") => void;
|
||||
}
|
||||
|
||||
function getAgentLabel(agent: Agent): string {
|
||||
const base = agent.name?.trim() || agent.id;
|
||||
return `${base} (${agent.role})`;
|
||||
}
|
||||
import { CustomModelDropdown } from "./CustomModelDropdown";
|
||||
import { fetchModels } from "../api";
|
||||
import type { ModelInfo } from "../api";
|
||||
|
||||
function formatRelativeTime(dateStr: string): string {
|
||||
const date = new Date(dateStr);
|
||||
@@ -40,22 +31,54 @@ function formatRelativeTime(dateStr: string): string {
|
||||
return date.toLocaleDateString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constant agent ID for the built-in kb agent.
|
||||
* The chat system always uses createKbAgent with CHAT_SYSTEM_PROMPT regardless
|
||||
* of the agentId stored on the session. This ID serves as metadata only.
|
||||
*/
|
||||
const KB_AGENT_ID = "__kb_agent__";
|
||||
|
||||
interface NewChatDialogProps {
|
||||
agents: Agent[];
|
||||
onClose: () => void;
|
||||
onCreate: (input: { agentId: string; title?: string; modelProvider?: string; modelId?: string }) => void;
|
||||
onCreate: (input: { agentId: string; modelProvider?: string; modelId?: string }) => void;
|
||||
}
|
||||
|
||||
function NewChatDialog({ agents, onClose, onCreate }: NewChatDialogProps) {
|
||||
const [agentId, setAgentId] = useState(agents[0]?.id ?? "");
|
||||
const [title, setTitle] = useState("");
|
||||
const [modelProvider, setModelProvider] = useState("");
|
||||
const [modelId, setModelId] = useState("");
|
||||
function NewChatDialog({ onClose, onCreate }: NewChatDialogProps) {
|
||||
// Model selection state (single combined value: "provider/modelId" or "" for default)
|
||||
const [modelValue, setModelValue] = useState("");
|
||||
const [models, setModels] = useState<ModelInfo[]>([]);
|
||||
const [modelsLoading, setModelsLoading] = useState(true);
|
||||
const [favoriteProviders, setFavoriteProviders] = useState<string[]>([]);
|
||||
const [favoriteModels, setFavoriteModels] = useState<string[]>([]);
|
||||
|
||||
// Load models on mount
|
||||
useEffect(() => {
|
||||
setModelsLoading(true);
|
||||
fetchModels()
|
||||
.then((response) => {
|
||||
setModels(response.models);
|
||||
setFavoriteProviders(response.favoriteProviders);
|
||||
setFavoriteModels(response.favoriteModels);
|
||||
})
|
||||
.catch(() => {
|
||||
// Silently fail - dropdown will show empty list
|
||||
setModels([]);
|
||||
})
|
||||
.finally(() => {
|
||||
setModelsLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!agentId) return;
|
||||
onCreate({ agentId, title: title || undefined, modelProvider: modelProvider || undefined, modelId: modelId || undefined });
|
||||
// Parse modelValue into provider and modelId
|
||||
const parsed = parseModelValue(modelValue);
|
||||
// Always use the kb agent - agentId is metadata only
|
||||
onCreate({
|
||||
agentId: KB_AGENT_ID,
|
||||
modelProvider: parsed.provider,
|
||||
modelId: parsed.modelId,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -63,53 +86,38 @@ function NewChatDialog({ agents, onClose, onCreate }: NewChatDialogProps) {
|
||||
<div className="chat-new-dialog" onClick={(e) => e.stopPropagation()}>
|
||||
<h3>New Chat</h3>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<label>
|
||||
Agent
|
||||
<select
|
||||
value={agentId}
|
||||
onChange={(e) => setAgentId(e.target.value)}
|
||||
required
|
||||
>
|
||||
<option value="">Select an agent</option>
|
||||
{agents.map((agent) => (
|
||||
<option key={agent.id} value={agent.id}>
|
||||
{getAgentLabel(agent)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Title (optional)
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Conversation title"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Model Provider (optional)
|
||||
<input
|
||||
type="text"
|
||||
value={modelProvider}
|
||||
onChange={(e) => setModelProvider(e.target.value)}
|
||||
placeholder="e.g., anthropic"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Model ID (optional)
|
||||
<input
|
||||
type="text"
|
||||
value={modelId}
|
||||
onChange={(e) => setModelId(e.target.value)}
|
||||
placeholder="e.g., claude-sonnet-4-5"
|
||||
<label className="chat-new-dialog-model-label">
|
||||
Model
|
||||
<CustomModelDropdown
|
||||
models={models}
|
||||
value={modelValue}
|
||||
onChange={setModelValue}
|
||||
placeholder={modelsLoading ? "Loading models..." : "Select a model…"}
|
||||
disabled={modelsLoading}
|
||||
label="Chat model"
|
||||
favoriteProviders={favoriteProviders}
|
||||
favoriteModels={favoriteModels}
|
||||
onToggleFavorite={(provider) => {
|
||||
setFavoriteProviders((prev) =>
|
||||
prev.includes(provider)
|
||||
? prev.filter((p) => p !== provider)
|
||||
: [provider, ...prev]
|
||||
);
|
||||
}}
|
||||
onToggleModelFavorite={(modelId) => {
|
||||
setFavoriteModels((prev) =>
|
||||
prev.includes(modelId)
|
||||
? prev.filter((m) => m !== modelId)
|
||||
: [modelId, ...prev]
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="chat-new-dialog-actions">
|
||||
<button type="button" className="btn btn-sm" onClick={onClose}>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" className="btn btn-sm btn-primary" disabled={!agentId}>
|
||||
<button type="submit" className="btn btn-sm btn-primary">
|
||||
Create
|
||||
</button>
|
||||
</div>
|
||||
@@ -119,10 +127,22 @@ function NewChatDialog({ agents, onClose, onCreate }: NewChatDialogProps) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a combined model value ("provider/modelId") into its components.
|
||||
* Returns undefined for both fields if the value is empty or malformed.
|
||||
*/
|
||||
function parseModelValue(value: string): { provider?: string; modelId?: string } {
|
||||
if (!value) return {};
|
||||
const slashIdx = value.indexOf("/");
|
||||
if (slashIdx === -1) return {};
|
||||
return {
|
||||
provider: value.slice(0, slashIdx),
|
||||
modelId: value.slice(slashIdx + 1),
|
||||
};
|
||||
}
|
||||
|
||||
export function ChatView({ projectId, addToast }: ChatViewProps) {
|
||||
const { agents } = useAgents(projectId);
|
||||
const {
|
||||
sessions,
|
||||
activeSession,
|
||||
sessionsLoading,
|
||||
messages,
|
||||
@@ -168,7 +188,7 @@ export function ChatView({ projectId, addToast }: ChatViewProps) {
|
||||
|
||||
// Handle create session
|
||||
const handleCreateSession = useCallback(
|
||||
async (input: { agentId: string; title?: string; modelProvider?: string; modelId?: string }) => {
|
||||
async (input: { agentId: string; modelProvider?: string; modelId?: string }) => {
|
||||
try {
|
||||
await createSession(input);
|
||||
setShowNewDialog(false);
|
||||
@@ -261,7 +281,6 @@ export function ChatView({ projectId, addToast }: ChatViewProps) {
|
||||
if (showNewDialog) {
|
||||
return (
|
||||
<NewChatDialog
|
||||
agents={agents}
|
||||
onClose={() => setShowNewDialog(false)}
|
||||
onCreate={handleCreateSession}
|
||||
/>
|
||||
@@ -272,23 +291,6 @@ export function ChatView({ projectId, addToast }: ChatViewProps) {
|
||||
<div className="chat-empty-state">
|
||||
<MessageSquare size={48} strokeWidth={1.5} />
|
||||
<h2>Start a new conversation</h2>
|
||||
<div className="chat-empty-state-agent-select">
|
||||
<select
|
||||
onChange={(e) => {
|
||||
if (e.target.value) {
|
||||
void handleCreateSession({ agentId: e.target.value });
|
||||
}
|
||||
}}
|
||||
value=""
|
||||
>
|
||||
<option value="">Select an agent to start chatting</option>
|
||||
{agents.map((agent) => (
|
||||
<option key={agent.id} value={agent.id}>
|
||||
{getAgentLabel(agent)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<button className="btn btn-primary" onClick={() => setShowNewDialog(true)}>
|
||||
<Plus size={16} />
|
||||
New Chat
|
||||
@@ -350,7 +352,7 @@ export function ChatView({ projectId, addToast }: ChatViewProps) {
|
||||
{session.lastMessagePreview || "No messages"}
|
||||
</div>
|
||||
<div className="chat-session-meta">
|
||||
<span>{session.agentId.slice(0, 30)}</span>
|
||||
<span>{session.agentId === KB_AGENT_ID ? "AI Assistant" : session.agentId.slice(0, 30)}</span>
|
||||
<span>{session.updatedAt ? formatRelativeTime(session.updatedAt) : ""}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -512,7 +514,6 @@ export function ChatView({ projectId, addToast }: ChatViewProps) {
|
||||
{/* New Chat Dialog (rendered at root level) */}
|
||||
{showNewDialog && (
|
||||
<NewChatDialog
|
||||
agents={agents}
|
||||
onClose={() => setShowNewDialog(false)}
|
||||
onCreate={handleCreateSession}
|
||||
/>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* new chat dialog, and input handling.
|
||||
*/
|
||||
|
||||
import { act, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { ChatView } from "../ChatView";
|
||||
@@ -11,15 +11,11 @@ import { ChatView } from "../ChatView";
|
||||
// Mock scrollIntoView for JSDOM
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
import * as useChatModule from "../../hooks/useChat";
|
||||
import * as useAgentsModule from "../../hooks/useAgents";
|
||||
import type { Agent } from "../../api";
|
||||
|
||||
// Mock the hooks
|
||||
vi.mock("../../hooks/useChat");
|
||||
vi.mock("../../hooks/useAgents");
|
||||
|
||||
const mockUseChat = vi.mocked(useChatModule.useChat);
|
||||
const mockUseAgents = vi.mocked(useAgentsModule.useAgents);
|
||||
|
||||
// Mock lucide-react icons - spread actual module and override specific icons
|
||||
vi.mock("lucide-react", async (importOriginal) => {
|
||||
@@ -39,26 +35,41 @@ vi.mock("lucide-react", async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
const mockAgents: Agent[] = [
|
||||
{
|
||||
id: "agent-001",
|
||||
name: "Agent One",
|
||||
role: "executor",
|
||||
state: "active",
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
metadata: {},
|
||||
},
|
||||
{
|
||||
id: "agent-002",
|
||||
name: "Agent Two",
|
||||
role: "reviewer",
|
||||
state: "active",
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
metadata: {},
|
||||
},
|
||||
];
|
||||
// Mock CustomModelDropdown as a simple test double
|
||||
vi.mock("../CustomModelDropdown", () => ({
|
||||
CustomModelDropdown: ({
|
||||
value,
|
||||
onChange,
|
||||
label,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
label: string;
|
||||
}) => (
|
||||
<select
|
||||
data-testid="mock-model-dropdown"
|
||||
aria-label={label}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
>
|
||||
<option value="">Use default</option>
|
||||
<option value="anthropic/claude-sonnet-4-5">Claude Sonnet 4.5</option>
|
||||
<option value="openai/gpt-4o">GPT-4o</option>
|
||||
</select>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock fetchModels
|
||||
vi.mock("../../api", () => ({
|
||||
fetchModels: vi.fn().mockResolvedValue({
|
||||
models: [
|
||||
{ provider: "anthropic", id: "claude-sonnet-4-5", name: "Claude Sonnet 4.5", reasoning: true, contextWindow: 200000 },
|
||||
{ provider: "openai", id: "gpt-4o", name: "GPT-4o", reasoning: false, contextWindow: 128000 },
|
||||
],
|
||||
favoriteProviders: [],
|
||||
favoriteModels: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
const defaultChatState = {
|
||||
sessions: [],
|
||||
@@ -70,7 +81,7 @@ const defaultChatState = {
|
||||
streamingText: "",
|
||||
streamingThinking: "",
|
||||
selectSession: vi.fn(),
|
||||
createSession: vi.fn().mockResolvedValue({ id: "session-new", agentId: "agent-001" }),
|
||||
createSession: vi.fn().mockResolvedValue({ id: "session-new", agentId: "__kb_agent__" }),
|
||||
archiveSession: vi.fn(),
|
||||
deleteSession: vi.fn(),
|
||||
sendMessage: vi.fn(),
|
||||
@@ -87,21 +98,9 @@ function setupMockChat(overrides: Partial<typeof defaultChatState> = {}) {
|
||||
mockUseChat.mockReturnValue(state as any);
|
||||
}
|
||||
|
||||
function setupMockAgents() {
|
||||
mockUseAgents.mockReturnValue({
|
||||
agents: mockAgents,
|
||||
activeAgents: mockAgents,
|
||||
stats: null,
|
||||
isLoading: false,
|
||||
loadAgents: vi.fn(),
|
||||
loadStats: vi.fn(),
|
||||
} as any);
|
||||
}
|
||||
|
||||
describe("ChatView", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
setupMockAgents();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -174,11 +173,12 @@ describe("ChatView", () => {
|
||||
// Dialog should be open - check for dialog content
|
||||
const dialog = document.querySelector(".chat-new-dialog");
|
||||
expect(dialog).toBeInTheDocument();
|
||||
expect(within(dialog!).getByText("Agent")).toBeInTheDocument();
|
||||
// Should show Model label (not Agent)
|
||||
expect(within(dialog!).getByText("Model")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates session and closes dialog", async () => {
|
||||
const createSession = vi.fn().mockResolvedValue({ id: "session-new", agentId: "agent-001" });
|
||||
it("creates session without model selection (uses default)", async () => {
|
||||
const createSession = vi.fn().mockResolvedValue({ id: "session-new", agentId: "__kb_agent__" });
|
||||
setupMockChat({ sessions: [], filteredSessions: [], createSession });
|
||||
|
||||
render(<ChatView projectId="proj-123" addToast={vi.fn()} />);
|
||||
@@ -186,21 +186,45 @@ describe("ChatView", () => {
|
||||
await userEvent.click(screen.getByTestId("chat-new-btn"));
|
||||
|
||||
const dialog = document.querySelector(".chat-new-dialog");
|
||||
const select = within(dialog!).getByRole("combobox") as HTMLSelectElement;
|
||||
await userEvent.selectOptions(select, "agent-001");
|
||||
|
||||
// Select "Use default" (the first option)
|
||||
const select = within(dialog!).getByTestId("mock-model-dropdown") as HTMLSelectElement;
|
||||
expect(select.value).toBe("");
|
||||
|
||||
await userEvent.click(within(dialog!).getByText("Create"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createSession).toHaveBeenCalledWith({
|
||||
agentId: "agent-001",
|
||||
title: undefined,
|
||||
agentId: "__kb_agent__",
|
||||
modelProvider: undefined,
|
||||
modelId: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("creates session with model selection", async () => {
|
||||
const createSession = vi.fn().mockResolvedValue({ id: "session-new", agentId: "__kb_agent__" });
|
||||
setupMockChat({ sessions: [], filteredSessions: [], createSession });
|
||||
|
||||
render(<ChatView projectId="proj-123" addToast={vi.fn()} />);
|
||||
|
||||
await userEvent.click(screen.getByTestId("chat-new-btn"));
|
||||
|
||||
const dialog = document.querySelector(".chat-new-dialog");
|
||||
const select = within(dialog!).getByTestId("mock-model-dropdown") as HTMLSelectElement;
|
||||
await userEvent.selectOptions(select, "anthropic/claude-sonnet-4-5");
|
||||
|
||||
await userEvent.click(within(dialog!).getByText("Create"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createSession).toHaveBeenCalledWith({
|
||||
agentId: "__kb_agent__",
|
||||
modelProvider: "anthropic",
|
||||
modelId: "claude-sonnet-4-5",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("renders messages for active session", () => {
|
||||
setupMockChat({
|
||||
activeSession: { id: "session-001", agentId: "agent-001", status: "active", title: "Test Chat", updatedAt: "2026-04-08T00:00:00.000Z" },
|
||||
@@ -325,7 +349,7 @@ describe("ChatView", () => {
|
||||
expect(screen.queryByText("Backend API")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows empty state agent selector and Start Chat button", () => {
|
||||
it("shows empty state with Start Chat button (no inline agent selector)", () => {
|
||||
setupMockChat({ sessions: [], filteredSessions: [] });
|
||||
|
||||
render(<ChatView projectId="proj-123" addToast={vi.fn()} />);
|
||||
@@ -334,6 +358,8 @@ describe("ChatView", () => {
|
||||
// Find the New Chat button in the empty state section
|
||||
const emptyState = document.querySelector(".chat-empty-state");
|
||||
expect(within(emptyState!).getByRole("button", { name: /new chat/i })).toBeInTheDocument();
|
||||
// Should NOT have an agent selector in empty state
|
||||
expect(emptyState?.querySelector("select")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows context menu on right-click", async () => {
|
||||
@@ -388,4 +414,30 @@ describe("ChatView", () => {
|
||||
expect(dialog).toBeInTheDocument();
|
||||
expect(within(dialog!).getByText("Delete Conversation?")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows AI Assistant label for kb agent sessions in sidebar", () => {
|
||||
setupMockChat({
|
||||
sessions: [{ id: "session-001", agentId: "__kb_agent__", status: "active", title: "My Chat", updatedAt: "2026-04-08T00:00:00.000Z" }],
|
||||
filteredSessions: [{ id: "session-001", agentId: "__kb_agent__", status: "active", title: "My Chat", updatedAt: "2026-04-08T00:00:00.000Z" }],
|
||||
});
|
||||
|
||||
render(<ChatView projectId="proj-123" addToast={vi.fn()} />);
|
||||
|
||||
const sessionItem = screen.getByTestId("chat-session-session-001");
|
||||
// Should show "AI Assistant" instead of "__kb_agent__"
|
||||
expect(within(sessionItem).getByText("AI Assistant")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows agent ID for non-kb agent sessions in sidebar", () => {
|
||||
setupMockChat({
|
||||
sessions: [{ id: "session-001", agentId: "my-custom-agent", status: "active", title: "Custom Chat", updatedAt: "2026-04-08T00:00:00.000Z" }],
|
||||
filteredSessions: [{ id: "session-001", agentId: "my-custom-agent", status: "active", title: "Custom Chat", updatedAt: "2026-04-08T00:00:00.000Z" }],
|
||||
});
|
||||
|
||||
render(<ChatView projectId="proj-123" addToast={vi.fn()} />);
|
||||
|
||||
const sessionItem = screen.getByTestId("chat-session-session-001");
|
||||
// Should show the agent ID (truncated to 30 chars)
|
||||
expect(within(sessionItem).getByText("my-custom-agent")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25873,6 +25873,18 @@ html .column.drag-over * {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* New Chat dialog model selector */
|
||||
.chat-new-dialog-model-label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* Ensure dropdown portal renders above dialog */
|
||||
.chat-new-dialog {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.quick-chat-fab {
|
||||
right: 16px;
|
||||
|
||||
Reference in New Issue
Block a user