diff --git a/frontend/src/components/Chat.tsx b/frontend/src/components/Chat.tsx index 99f1c03..45010ec 100644 --- a/frontend/src/components/Chat.tsx +++ b/frontend/src/components/Chat.tsx @@ -5,13 +5,15 @@ import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism"; import type { PipelineState } from "../api/client"; import { api, ChatWebSocket } from "../api/client"; import { useChatHistory } from "../hooks/useChatHistory"; -import type { Message, ProviderConfig, ToolCall } from "../types"; +import type { Message, ProviderConfig } from "../types"; import { AgentPanel } from "./AgentPanel"; import { ChatHeader } from "./ChatHeader"; +import { ChatInput } from "./ChatInput"; import { LozengeFlyProvider } from "./LozengeFlyContext"; +import { MessageItem } from "./MessageItem"; import { StagePanel } from "./StagePanel"; -const { useCallback, useEffect, useRef, useState } = React; +const { useCallback, useEffect, useMemo, useRef, useState } = React; /** Fixed-height thinking trace block that auto-scrolls to bottom as text arrives. */ function ThinkingBlock({ text }: { text: string }) { @@ -63,6 +65,37 @@ function ThinkingBlock({ text }: { text: string }) { ); } +/** Streaming message renderer — stable component to avoid recreation on each render. */ +function StreamingMessage({ content }: { content: string }) { + return ( + { + const match = /language-(\w+)/.exec(className || ""); + const isInline = !className; + return !isInline && match ? ( + + {String(children).replace(/\n$/, "")} + + ) : ( + + {children} + + ); + }, + }} + > + {content} + + ); +} + const NARROW_BREAKPOINT = 900; function formatToolActivity(toolName: string): string { @@ -100,6 +133,16 @@ function formatToolActivity(toolName: string): string { } } +const estimateTokens = (text: string): number => Math.ceil(text.length / 4); + +const getContextWindowSize = (modelName: string): number => { + if (modelName.startsWith("claude-")) return 200000; + if (modelName.includes("llama3")) return 8192; + if (modelName.includes("qwen2.5")) return 32768; + if (modelName.includes("deepseek")) return 16384; + return 8192; +}; + interface ChatProps { projectPath: string; onCloseProject: () => void; @@ -107,7 +150,6 @@ interface ChatProps { export function Chat({ projectPath, onCloseProject }: ChatProps) { const { messages, setMessages, clearMessages } = useChatHistory(projectPath); - const [input, setInput] = useState(""); const [loading, setLoading] = useState(false); const [model, setModel] = useState("llama3.1"); const [enableTools, setEnableTools] = useState(true); @@ -155,30 +197,14 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { const wsRef = useRef(null); const messagesEndRef = useRef(null); - const inputRef = useRef(null); const scrollContainerRef = useRef(null); const shouldAutoScrollRef = useRef(true); const lastScrollTopRef = useRef(0); const userScrolledUpRef = useRef(false); const pendingMessageRef = useRef(""); - const estimateTokens = (text: string): number => Math.ceil(text.length / 4); - - const getContextWindowSize = (modelName: string): number => { - if (modelName.startsWith("claude-")) return 200000; - if (modelName.includes("llama3")) return 8192; - if (modelName.includes("qwen2.5")) return 32768; - if (modelName.includes("deepseek")) return 16384; - return 8192; - }; - - const calculateContextUsage = (): { - used: number; - total: number; - percentage: number; - } => { + const contextUsage = useMemo(() => { let totalTokens = 0; - totalTokens += 200; for (const msg of messages) { @@ -200,9 +226,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { total: contextWindow, percentage, }; - }; - - const contextUsage = calculateContextUsage(); + }, [messages, streamingContent, model]); useEffect(() => { api @@ -371,10 +395,6 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { } }, [autoScrollKey, scrollToBottom]); - useEffect(() => { - inputRef.current?.focus(); - }, []); - // Auto-send queued message when loading ends useEffect(() => { if (pendingAutoSend) { @@ -415,21 +435,17 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { } }; - const sendMessage = async (messageOverride?: string) => { - const messageToSend = messageOverride ?? input; - if (!messageToSend.trim()) return; + const sendMessage = async (messageText: string) => { + if (!messageText.trim()) return; // Agent is busy — queue the message instead of dropping it if (loading) { const newItem = { id: String(queueIdCounterRef.current++), - text: messageToSend, + text: messageText, }; queuedMessagesRef.current = [...queuedMessagesRef.current, newItem]; setQueuedMessages([...queuedMessagesRef.current]); - if (!messageOverride || messageOverride === input) { - setInput(""); - } return; } @@ -437,19 +453,16 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { if (!isClaudeCode && model.startsWith("claude-")) { const hasKey = await api.getAnthropicApiKeyExists(); if (!hasKey) { - pendingMessageRef.current = messageToSend; + pendingMessageRef.current = messageText; setShowApiKeyDialog(true); return; } } - const userMsg: Message = { role: "user", content: messageToSend }; + const userMsg: Message = { role: "user", content: messageText }; const newHistory = [...messages, userMsg]; setMessages(newHistory); - if (!messageOverride || messageOverride === input) { - setInput(""); - } setLoading(true); setStreamingContent(""); setStreamingThinking(""); @@ -536,6 +549,13 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { } }; + const handleRemoveQueuedMessage = useCallback((id: string) => { + queuedMessagesRef.current = queuedMessagesRef.current.filter( + (item) => item.id !== id, + ); + setQueuedMessages([...queuedMessagesRef.current]); + }, []); + return ( )} {messages.map((msg: Message, idx: number) => ( - - - {msg.role === "user" ? ( - msg.content - ) : msg.role === "tool" ? ( - - - ▶ - - Tool Output - {msg.tool_call_id && ` (${msg.tool_call_id})`} - - - - {msg.content} - - - ) : ( - - { - const match = /language-(\w+)/.exec( - className || "", - ); - const isInline = !className; - return !isInline && match ? ( - - {String(children).replace(/\n$/, "")} - - ) : ( - - {children} - - ); - }, - }} - > - {msg.content} - - - )} - - {msg.tool_calls && ( - - {msg.tool_calls.map((tc: ToolCall, i: number) => { - let argsSummary = ""; - try { - const args = JSON.parse(tc.function.arguments); - const firstKey = Object.keys(args)[0]; - if (firstKey && args[firstKey]) { - argsSummary = String(args[firstKey]); - if (argsSummary.length > 50) { - argsSummary = `${argsSummary.substring(0, 47)}...`; - } - } - } catch (_e) { - // ignore - } - - return ( - - ▶ - - {tc.function.name} - {argsSummary && `(${argsSummary})`} - - - ); - })} - - )} - - + msg={msg} + /> ))} {loading && streamingThinking && ( @@ -847,34 +719,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { }} > - { - const match = /language-(\w+)/.exec( - className || "", - ); - const isInline = !className; - return !isInline && match ? ( - - {String(children).replace(/\n$/, "")} - - ) : ( - - {children} - - ); - }, - }} - > - {streamingContent} - + @@ -947,176 +792,13 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { )} {/* Chat input pinned at bottom of left column */} - - - {/* Queued message indicators */} - {queuedMessages.map(({ id, text }) => ( - - - Queued - - - {text} - - { - setInput(text); - queuedMessagesRef.current = - queuedMessagesRef.current.filter( - (item) => item.id !== id, - ); - setQueuedMessages([...queuedMessagesRef.current]); - inputRef.current?.focus(); - }} - style={{ - background: "none", - border: "none", - color: "#666", - cursor: "pointer", - padding: "2px 6px", - fontSize: "0.8rem", - flexShrink: 0, - borderRadius: "4px", - }} - > - Edit - - { - queuedMessagesRef.current = - queuedMessagesRef.current.filter( - (item) => item.id !== id, - ); - setQueuedMessages([...queuedMessagesRef.current]); - }} - style={{ - background: "none", - border: "none", - color: "#666", - cursor: "pointer", - padding: "2px 4px", - fontSize: "0.875rem", - flexShrink: 0, - borderRadius: "4px", - }} - > - ✕ - - - ))} - {/* Input row */} - - setInput(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter" && !e.shiftKey) { - e.preventDefault(); - sendMessage(); - } - }} - placeholder="Send a message..." - rows={1} - style={{ - flex: 1, - padding: "14px 20px", - borderRadius: "24px", - border: "1px solid #333", - outline: "none", - fontSize: "1rem", - fontWeight: "500", - background: "#2f2f2f", - color: "#ececec", - boxShadow: "0 2px 6px rgba(0,0,0,0.02)", - resize: "none", - overflowY: "auto", - fontFamily: "inherit", - }} - /> - sendMessage() - } - disabled={!loading && !input.trim()} - style={{ - background: "#ececec", - color: "black", - border: "none", - borderRadius: "50%", - width: "32px", - height: "32px", - display: "flex", - alignItems: "center", - justifyContent: "center", - cursor: "pointer", - opacity: !loading && !input.trim() ? 0.5 : 1, - flexShrink: 0, - }} - > - {loading && !input.trim() ? "■" : "↑"} - - - - + {/* Right column: panels independently scrollable */} diff --git a/frontend/src/components/ChatInput.test.tsx b/frontend/src/components/ChatInput.test.tsx new file mode 100644 index 0000000..210b525 --- /dev/null +++ b/frontend/src/components/ChatInput.test.tsx @@ -0,0 +1,202 @@ +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { ChatInput } from "./ChatInput"; + +describe("ChatInput component (Story 178 AC1)", () => { + it("renders a textarea with Send a message... placeholder", () => { + render( + , + ); + + const textarea = screen.getByPlaceholderText("Send a message..."); + expect(textarea.tagName.toLowerCase()).toBe("textarea"); + }); + + it("manages input state internally — typing updates value without calling onSubmit", async () => { + const onSubmit = vi.fn(); + + render( + , + ); + + const textarea = screen.getByPlaceholderText("Send a message..."); + + await act(async () => { + fireEvent.change(textarea, { target: { value: "hello world" } }); + }); + + expect((textarea as HTMLTextAreaElement).value).toBe("hello world"); + expect(onSubmit).not.toHaveBeenCalled(); + }); + + it("calls onSubmit with the input text on Enter key press", async () => { + const onSubmit = vi.fn(); + + render( + , + ); + + const textarea = screen.getByPlaceholderText("Send a message..."); + + await act(async () => { + fireEvent.change(textarea, { target: { value: "test message" } }); + }); + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter", shiftKey: false }); + }); + + expect(onSubmit).toHaveBeenCalledWith("test message"); + }); + + it("clears input after submitting", async () => { + render( + , + ); + + const textarea = screen.getByPlaceholderText("Send a message..."); + + await act(async () => { + fireEvent.change(textarea, { target: { value: "hello" } }); + }); + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter", shiftKey: false }); + }); + + expect((textarea as HTMLTextAreaElement).value).toBe(""); + }); + + it("does not submit on Shift+Enter", async () => { + const onSubmit = vi.fn(); + + render( + , + ); + + const textarea = screen.getByPlaceholderText("Send a message..."); + + await act(async () => { + fireEvent.change(textarea, { target: { value: "multiline" } }); + }); + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true }); + }); + + expect(onSubmit).not.toHaveBeenCalled(); + expect((textarea as HTMLTextAreaElement).value).toBe("multiline"); + }); + + it("calls onCancel when stop button is clicked while loading with empty input", async () => { + const onCancel = vi.fn(); + + render( + , + ); + + const stopButton = screen.getByRole("button", { name: "■" }); + await act(async () => { + fireEvent.click(stopButton); + }); + + expect(onCancel).toHaveBeenCalled(); + }); + + it("renders queued message indicators", () => { + render( + , + ); + + const indicators = screen.getAllByTestId("queued-message-indicator"); + expect(indicators).toHaveLength(2); + expect(indicators[0]).toHaveTextContent("first message"); + expect(indicators[1]).toHaveTextContent("second message"); + }); + + it("calls onRemoveQueuedMessage when cancel button is clicked", async () => { + const onRemove = vi.fn(); + + render( + , + ); + + const cancelBtn = screen.getByTitle("Cancel queued message"); + await act(async () => { + fireEvent.click(cancelBtn); + }); + + expect(onRemove).toHaveBeenCalledWith("q1"); + }); + + it("edit button restores queued message text to input and removes from queue", async () => { + const onRemove = vi.fn(); + + render( + , + ); + + const editBtn = screen.getByTitle("Edit queued message"); + await act(async () => { + fireEvent.click(editBtn); + }); + + const textarea = screen.getByPlaceholderText("Send a message..."); + expect((textarea as HTMLTextAreaElement).value).toBe("edit me back"); + expect(onRemove).toHaveBeenCalledWith("q1"); + }); +}); diff --git a/frontend/src/components/ChatInput.tsx b/frontend/src/components/ChatInput.tsx new file mode 100644 index 0000000..7d6c8ab --- /dev/null +++ b/frontend/src/components/ChatInput.tsx @@ -0,0 +1,191 @@ +import * as React from "react"; + +const { useEffect, useRef, useState } = React; + +interface ChatInputProps { + loading: boolean; + queuedMessages: { id: string; text: string }[]; + onSubmit: (message: string) => void; + onCancel: () => void; + onRemoveQueuedMessage: (id: string) => void; +} + +export function ChatInput({ + loading, + queuedMessages, + onSubmit, + onCancel, + onRemoveQueuedMessage, +}: ChatInputProps) { + const [input, setInput] = useState(""); + const inputRef = useRef(null); + + useEffect(() => { + inputRef.current?.focus(); + }, []); + + const handleSubmit = () => { + if (!input.trim()) return; + onSubmit(input); + setInput(""); + }; + + return ( + + + {/* Queued message indicators */} + {queuedMessages.map(({ id, text }) => ( + + + Queued + + + {text} + + { + setInput(text); + onRemoveQueuedMessage(id); + inputRef.current?.focus(); + }} + style={{ + background: "none", + border: "none", + color: "#666", + cursor: "pointer", + padding: "2px 6px", + fontSize: "0.8rem", + flexShrink: 0, + borderRadius: "4px", + }} + > + Edit + + onRemoveQueuedMessage(id)} + style={{ + background: "none", + border: "none", + color: "#666", + cursor: "pointer", + padding: "2px 4px", + fontSize: "0.875rem", + flexShrink: 0, + borderRadius: "4px", + }} + > + ✕ + + + ))} + {/* Input row */} + + setInput(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + handleSubmit(); + } + }} + placeholder="Send a message..." + rows={1} + style={{ + flex: 1, + padding: "14px 20px", + borderRadius: "24px", + border: "1px solid #333", + outline: "none", + fontSize: "1rem", + fontWeight: "500", + background: "#2f2f2f", + color: "#ececec", + boxShadow: "0 2px 6px rgba(0,0,0,0.02)", + resize: "none", + overflowY: "auto", + fontFamily: "inherit", + }} + /> + + {loading && !input.trim() ? "■" : "↑"} + + + + + ); +} diff --git a/frontend/src/components/MessageItem.test.tsx b/frontend/src/components/MessageItem.test.tsx new file mode 100644 index 0000000..85e4638 --- /dev/null +++ b/frontend/src/components/MessageItem.test.tsx @@ -0,0 +1,73 @@ +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; +import { MessageItem } from "./MessageItem"; + +describe("MessageItem component (Story 178 AC3)", () => { + it("renders user message as a bubble", () => { + render(); + + expect(screen.getByText("Hello there!")).toBeInTheDocument(); + }); + + it("renders assistant message with markdown-body class", () => { + render( + , + ); + + expect(screen.getByText("Here is my response.")).toBeInTheDocument(); + const text = screen.getByText("Here is my response."); + expect(text.closest(".markdown-body")).toBeTruthy(); + }); + + it("renders tool message as collapsible details", () => { + render( + , + ); + + expect(screen.getByText(/Tool Output/)).toBeInTheDocument(); + }); + + it("renders tool call badges for assistant messages with tool_calls", () => { + render( + , + ); + + expect(screen.getByText("I will read the file.")).toBeInTheDocument(); + expect(screen.getByText("Read(src/main.rs)")).toBeInTheDocument(); + }); + + it("is wrapped in React.memo (has displayName or $$typeof memo)", () => { + // React.memo wraps the component — verify the export is memoized + // by checking that the component has a memo wrapper + const { type } = { type: MessageItem }; + // React.memo returns an object with $$typeof === Symbol(react.memo) + // biome-ignore lint/suspicious/noExplicitAny: checking React internals for test + expect((type as any).$$typeof).toBeDefined(); + // biome-ignore lint/suspicious/noExplicitAny: checking React internals for test + const typeofStr = String((type as any).$$typeof); + expect(typeofStr).toContain("memo"); + }); +}); diff --git a/frontend/src/components/MessageItem.tsx b/frontend/src/components/MessageItem.tsx new file mode 100644 index 0000000..07a148c --- /dev/null +++ b/frontend/src/components/MessageItem.tsx @@ -0,0 +1,160 @@ +import * as React from "react"; +import Markdown from "react-markdown"; +import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"; +import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism"; +import type { Message, ToolCall } from "../types"; + +// biome-ignore lint/suspicious/noExplicitAny: react-markdown requires any for component props +function CodeBlock({ className, children, ...props }: any) { + const match = /language-(\w+)/.exec(className || ""); + const isInline = !className; + return !isInline && match ? ( + + {String(children).replace(/\n$/, "")} + + ) : ( + + {children} + + ); +} + +interface MessageItemProps { + msg: Message; +} + +function MessageItemInner({ msg }: MessageItemProps) { + return ( + + + {msg.role === "user" ? ( + msg.content + ) : msg.role === "tool" ? ( + + + ▶ + + Tool Output + {msg.tool_call_id && ` (${msg.tool_call_id})`} + + + + {msg.content} + + + ) : ( + + {msg.content} + + )} + + {msg.tool_calls && ( + + {msg.tool_calls.map((tc: ToolCall, i: number) => { + let argsSummary = ""; + try { + const args = JSON.parse(tc.function.arguments); + const firstKey = Object.keys(args)[0]; + if (firstKey && args[firstKey]) { + argsSummary = String(args[firstKey]); + if (argsSummary.length > 50) { + argsSummary = `${argsSummary.substring(0, 47)}...`; + } + } + } catch (_e) { + // ignore + } + + return ( + + ▶ + + {tc.function.name} + {argsSummary && `(${argsSummary})`} + + + ); + })} + + )} + + + ); +} + +export const MessageItem = React.memo(MessageItemInner);
+ {children} +
- {msg.content} -
- {children} -
+ {msg.content} +