// ChatView.css is imported eagerly from App.tsx to avoid a flash of
// unstyled content when the lazy chunk loads. Do not re-import here.
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { Components } from "react-markdown";
import {
MessageSquare,
Send,
Plus,
Search,
Trash2,
Archive,
ChevronLeft,
Bot,
Square,
Eye,
EyeOff,
Paperclip,
File,
} from "lucide-react";
import { useChat, type ToolCallInfo } from "../hooks/useChat";
import { useViewportMode } from "./Header";
import { fetchAgents, fetchDiscoveredSkills, fetchModels, updateGlobalSettings } from "../api";
import type { Agent } from "@fusion/core";
import type { DiscoveredSkill } from "@fusion/dashboard";
import type { ModelInfo } from "../api";
import { CustomModelDropdown } from "./CustomModelDropdown";
import { AgentMentionPopup } from "./AgentMentionPopup";
import { FileMentionPopup } from "./FileMentionPopup";
import { useFileMention } from "../hooks/useFileMention";
import { useMobileKeyboard } from "../hooks/useMobileKeyboard";
import { ChatToolCalls } from "./ChatToolCalls";
export interface ChatViewProps {
projectId?: string;
addToast: (msg: string, type?: "success" | "error") => void;
}
function formatRelativeTime(dateStr: string): string {
const date = new Date(dateStr);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffSecs = Math.floor(diffMs / 1000);
const diffMins = Math.floor(diffSecs / 60);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffSecs < 60) return "just now";
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays < 7) return `${diffDays}d ago`;
return date.toLocaleDateString();
}
/**
* Format a model provider and ID into a human-readable tag.
* Returns null if provider or modelId is missing/empty.
*/
function formatModelTag(provider?: string | null, modelId?: string | null): string | null {
if (!provider || !modelId) return null;
// Handle known provider/model patterns
const normalizedModel = modelId.toLowerCase();
// Claude models: "claude-sonnet-4-5" -> "Claude Sonnet 4.5"
if (normalizedModel.includes("claude")) {
let formatted = modelId
.replace(/^claude[- ]/i, "Claude ")
.replace(/sonnet[- ](\d+)[- ](\d+)/i, "Sonnet $1.$2")
.replace(/sonnet[- ](\d+)/i, "Sonnet $1")
.replace(/haiku[- ](\d+)/i, "Haiku $1")
.replace(/opus[- ](\d+)/i, "Opus $1")
.replace(/sonnet/i, "Sonnet")
.replace(/haiku/i, "Haiku")
.replace(/opus/i, "Opus")
.replace(/-/g, " ")
.trim();
// Fix double spaces
formatted = formatted.replace(/\s+/g, " ");
return formatted.length > 30 ? formatted.slice(0, 30) + "…" : formatted;
}
// OpenAI models: "gpt-4o" -> "GPT-4o", "gpt-4-turbo" -> "GPT-4 Turbo"
if (normalizedModel.includes("gpt") || normalizedModel.includes("openai")) {
// Format GPT model names: handle special cases first, then capitalize
// Note: We don't replace hyphens globally because special cases preserve them
const formatted = modelId
.replace(/^gpt-4-turbo$/i, "GPT-4 Turbo")
.replace(/^gpt-4o-mini$/i, "GPT-4o Mini")
.replace(/^gpt-4o$/i, "GPT-4o")
.replace(/^gpt-4$/i, "GPT-4")
.replace(/^gpt-o1-preview$/i, "GPT-o1 Preview")
.replace(/^gpt-o1-mini$/i, "GPT-o1 Mini")
.replace(/^gpt-o1$/i, "GPT-o1")
.replace(/^gpt/i, "GPT") // Capitalize remaining GPT prefix
.trim();
return formatted.length > 30 ? formatted.slice(0, 30) + "…" : formatted;
}
// Gemini models: "gemini-2.5-pro" -> "Gemini 2.5 Pro"
if (normalizedModel.includes("gemini")) {
const formatted = modelId
.replace(/^gemini[- ]/i, "Gemini ")
.replace(/pro[- ](\d+)[- ](\d+)/i, "Pro $1.$2")
.replace(/pro[- ](\d+)/i, "Pro $1")
.replace(/-/g, " ")
.replace(/\s+/g, " ")
.trim();
return formatted.length > 30 ? formatted.slice(0, 30) + "…" : formatted;
}
// Generic fallback: capitalize first letter, replace hyphens with spaces
const formatted = modelId
.replace(/-/g, " ")
.replace(/^\w/, (c) => c.toUpperCase())
.replace(/\s+/g, " ")
.trim();
return formatted.length > 30 ? formatted.slice(0, 30) + "…" : formatted;
}
function renderToolCalls(toolCalls?: ToolCallInfo[]): ReactNode {
return ;
}
const chatMarkdownComponents: Components = {
pre: ({ children, ...props }) => (
{children}
),
table: ({ children, ...props }) => (
),
};
/**
* Constant agent ID for the built-in fn agent.
* The chat system always uses createFnAgent with CHAT_SYSTEM_PROMPT regardless
* of the agentId stored on the session. This ID serves as metadata only.
*/
const FN_AGENT_ID = "__fn_agent__";
interface PendingAttachment {
file: File;
previewUrl: string;
}
const ALLOWED_ATTACHMENT_TYPES = [
"image/png",
"image/jpeg",
"image/gif",
"image/webp",
"text/plain",
"application/json",
"text/yaml",
"text/markdown",
"text/csv",
"application/xml",
"text/x-log",
];
function getSkillTriggerMatch(value: string): { filter: string; start: number; end: number } | null {
const triggerMatch = /(^|[\s])\/([^\s]*)$/.exec(value);
if (!triggerMatch) {
return null;
}
const prefix = triggerMatch[1] ?? "";
const filter = triggerMatch[2] ?? "";
const start = triggerMatch.index + prefix.length;
return {
filter,
start,
end: value.length,
};
}
function getMentionTriggerMatch(
value: string,
cursorPos: number,
): { filter: string; start: number; end: number } | null {
const textBeforeCursor = value.slice(0, cursorPos);
const triggerMatch = /(^|[\s\n])@([\w-]*)$/.exec(textBeforeCursor);
if (!triggerMatch) {
return null;
}
const filter = triggerMatch[2] ?? "";
const start = textBeforeCursor.length - filter.length - 1;
return {
filter,
start,
end: cursorPos,
};
}
interface NewChatDialogProps {
projectId?: string;
onClose: () => void;
onCreate: (input: { agentId: string; modelProvider?: string; modelId?: string }) => void;
}
function NewChatDialog({ projectId, onClose, onCreate }: NewChatDialogProps) {
const [chatMode, setChatMode] = useState<"agent" | "model">("agent");
const [agents, setAgents] = useState([]);
const [agentsLoading, setAgentsLoading] = useState(true);
const [selectedAgentId, setSelectedAgentId] = useState("");
const [models, setModels] = useState([]);
const [modelsLoading, setModelsLoading] = useState(true);
const [selectedModel, setSelectedModel] = useState("");
const [favoriteProviders, setFavoriteProviders] = useState([]);
const [favoriteModels, setFavoriteModels] = useState([]);
// Load agents on mount (project-scoped)
useEffect(() => {
let cancelled = false;
setAgentsLoading(true);
fetchAgents(undefined, projectId)
.then((response) => {
if (!cancelled) {
setAgents(response);
}
})
.catch(() => {
if (!cancelled) {
// Silently fail - show empty list
setAgents([]);
}
})
.finally(() => {
if (!cancelled) {
setAgentsLoading(false);
}
});
return () => {
cancelled = true;
};
}, [projectId]);
// Load models on mount
useEffect(() => {
setModelsLoading(true);
fetchModels()
.then((response) => {
setModels(response.models);
setFavoriteProviders(response.favoriteProviders);
setFavoriteModels(response.favoriteModels);
})
.catch(() => {
// Silently fail - show empty list
setModels([]);
setFavoriteProviders([]);
setFavoriteModels([]);
})
.finally(() => {
setModelsLoading(false);
});
}, []);
const handleToggleFavorite = useCallback(async (provider: string) => {
const currentFavorites = favoriteProviders;
const isFavorite = currentFavorites.includes(provider);
const newFavorites = isFavorite
? currentFavorites.filter((value) => value !== provider)
: [provider, ...currentFavorites];
setFavoriteProviders(newFavorites);
try {
await updateGlobalSettings({ favoriteProviders: newFavorites, favoriteModels });
} catch {
setFavoriteProviders(currentFavorites);
}
}, [favoriteProviders, favoriteModels]);
const handleToggleModelFavorite = useCallback(async (modelId: string) => {
const currentFavorites = favoriteModels;
const isFavorite = currentFavorites.includes(modelId);
const newFavorites = isFavorite
? currentFavorites.filter((value) => value !== modelId)
: [modelId, ...currentFavorites];
setFavoriteModels(newFavorites);
try {
await updateGlobalSettings({ favoriteProviders, favoriteModels: newFavorites });
} catch {
setFavoriteModels(currentFavorites);
}
}, [favoriteModels, favoriteProviders]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (chatMode === "agent") {
if (!selectedAgentId) return;
onCreate({ agentId: selectedAgentId });
return;
}
// model mode
if (!selectedModel) return;
const slashIdx = selectedModel.indexOf("/");
if (slashIdx <= 0) return;
const modelProvider = selectedModel.slice(0, slashIdx);
const modelId = selectedModel.slice(slashIdx + 1);
onCreate({ agentId: FN_AGENT_ID, modelProvider, modelId });
};
const isSubmitDisabled =
chatMode === "agent" ? !selectedAgentId : !selectedModel;
return (
e.stopPropagation()}>
New Chat
);
}
export function ChatView({ projectId, addToast }: ChatViewProps) {
const {
activeSession,
sessionsLoading,
messages,
messagesLoading,
isStreaming,
streamingText,
streamingThinking,
streamingToolCalls,
selectSession,
createSession,
archiveSession,
deleteSession,
sendMessage,
stopStreaming,
pendingMessage,
clearPendingMessage,
searchQuery,
setSearchQuery,
filteredSessions,
} = useChat(projectId);
const [showNewDialog, setShowNewDialog] = useState(false);
const [messageInput, setMessageInput] = useState("");
const [contextMenu, setContextMenu] = useState<{ sessionId: string; x: number; y: number } | null>(null);
const [confirmDelete, setConfirmDelete] = useState(null);
const [sidebarVisible, setSidebarVisible] = useState(true);
const [agentsMap, setAgentsMap] = useState