repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/index.jsx
import { useState, useEffect, useContext } from "react"; import ChatHistory from "./ChatHistory"; import { CLEAR_ATTACHMENTS_EVENT, DndUploaderContext } from "./DnDWrapper"; import PromptInput, { PROMPT_INPUT_EVENT, PROMPT_INPUT_ID, } from "./PromptInput"; import Workspace from "@/models/workspace"; import handleChat, { ABORT_STREAM_EVENT } from "@/utils/chat"; import { isMobile } from "react-device-detect"; import { SidebarMobileHeader } from "../../Sidebar"; import { useParams } from "react-router-dom"; import { v4 } from "uuid"; import handleSocketResponse, { websocketURI, AGENT_SESSION_END, AGENT_SESSION_START, } from "@/utils/chat/agent"; import DnDFileUploaderWrapper from "./DnDWrapper"; import SpeechRecognition, { useSpeechRecognition, } from "react-speech-recognition"; import { ChatTooltips } from "./ChatTooltips"; import { MetricsProvider } from "./ChatHistory/HistoricalMessage/Actions/RenderMetrics"; export default function ChatContainer({ workspace, knownHistory = [] }) { const { threadSlug = null } = useParams(); const [message, setMessage] = useState(""); const [loadingResponse, setLoadingResponse] = useState(false); const [chatHistory, setChatHistory] = useState(knownHistory); const [socketId, setSocketId] = useState(null); const [websocket, setWebsocket] = useState(null); const { files, parseAttachments } = useContext(DndUploaderContext); // Maintain state of message from whatever is in PromptInput const handleMessageChange = (event) => { setMessage(event.target.value); }; const { listening, resetTranscript } = useSpeechRecognition({ clearTranscriptOnListen: true, }); /** * Emit an update to the state of the prompt input without directly * passing a prop in so that it does not re-render constantly. * @param {string} messageContent - The message content to set * @param {'replace' | 'append'} writeMode - Replace current text or append to existing text (default: replace) */ function setMessageEmit(messageContent = "", writeMode = "replace") { if (writeMode === "append") setMessage((prev) => prev + messageContent); else setMessage(messageContent ?? ""); // Push the update to the PromptInput component (same logic as above to keep in sync) window.dispatchEvent( new CustomEvent(PROMPT_INPUT_EVENT, { detail: { messageContent, writeMode }, }) ); } const handleSubmit = async (event) => { event.preventDefault(); if (!message || message === "") return false; const prevChatHistory = [ ...chatHistory, { content: message, role: "user", attachments: parseAttachments(), }, { content: "", role: "assistant", pending: true, userMessage: message, animate: true, }, ]; if (listening) { // Stop the mic if the send button is clicked endSTTSession(); } setChatHistory(prevChatHistory); setMessageEmit(""); setLoadingResponse(true); }; function endSTTSession() { SpeechRecognition.stopListening(); resetTranscript(); } const regenerateAssistantMessage = (chatId) => { const updatedHistory = chatHistory.slice(0, -1); const lastUserMessage = updatedHistory.slice(-1)[0]; Workspace.deleteChats(workspace.slug, [chatId]) .then(() => sendCommand({ text: lastUserMessage.content, autoSubmit: true, history: updatedHistory, attachments: lastUserMessage?.attachments, }) ) .catch((e) => console.error(e)); }; /** * Send a command to the LLM prompt input. * @param {Object} options - Arguments to send to the LLM * @param {string} options.text - The text to send to the LLM * @param {boolean} options.autoSubmit - Determines if the text should be sent immediately or if it should be added to the message state (default: false) * @param {Object[]} options.history - The history of the chat prior to this message for overriding the current chat history * @param {Object[import("./DnDWrapper").Attachment]} options.attachments - The attachments to send to the LLM for this message * @param {'replace' | 'append'} options.writeMode - Replace current text or append to existing text (default: replace) * @returns {void} */ const sendCommand = async ({ text = "", autoSubmit = false, history = [], attachments = [], writeMode = "replace", } = {}) => { // If we are not auto-submitting, we can just emit the text to the prompt input. if (!autoSubmit) { setMessageEmit(text, writeMode); return; } // If we are auto-submitting in append mode // than we need to update text with whatever is in the prompt input + the text we are sending. // @note: `message` will not work here since it is not updated yet. // If text is still empty, after this, then we should just return. if (writeMode === "append") { const currentText = document.getElementById(PROMPT_INPUT_ID)?.value; text = currentText + text; } if (!text || text === "") return false; // If we are auto-submitting // Then we can replace the current text since this is not accumulating. let prevChatHistory; if (history.length > 0) { // use pre-determined history chain. prevChatHistory = [ ...history, { content: "", role: "assistant", pending: true, userMessage: text, attachments, animate: true, }, ]; } else { prevChatHistory = [ ...chatHistory, { content: text, role: "user", attachments, }, { content: "", role: "assistant", pending: true, userMessage: text, animate: true, }, ]; } setChatHistory(prevChatHistory); setMessageEmit(""); setLoadingResponse(true); }; useEffect(() => { async function fetchReply() { const promptMessage = chatHistory.length > 0 ? chatHistory[chatHistory.length - 1] : null; const remHistory = chatHistory.length > 0 ? chatHistory.slice(0, -1) : []; var _chatHistory = [...remHistory]; // Override hook for new messages to now go to agents until the connection closes if (!!websocket) { if (!promptMessage || !promptMessage?.userMessage) return false; window.dispatchEvent(new CustomEvent(CLEAR_ATTACHMENTS_EVENT)); websocket.send( JSON.stringify({ type: "awaitingFeedback", feedback: promptMessage?.userMessage, }) ); return; } if (!promptMessage || !promptMessage?.userMessage) return false; // If running and edit or regeneration, this history will already have attachments // so no need to parse the current state. const attachments = promptMessage?.attachments ?? parseAttachments(); window.dispatchEvent(new CustomEvent(CLEAR_ATTACHMENTS_EVENT)); await Workspace.multiplexStream({ workspaceSlug: workspace.slug, threadSlug, prompt: promptMessage.userMessage, chatHandler: (chatResult) => handleChat( chatResult, setLoadingResponse, setChatHistory, remHistory, _chatHistory, setSocketId ), attachments, }); return; } loadingResponse === true && fetchReply(); }, [loadingResponse, chatHistory, workspace]); // TODO: Simplify this WSS stuff useEffect(() => { function handleWSS() { try { if (!socketId || !!websocket) return; const socket = new WebSocket( `${websocketURI()}/api/agent-invocation/${socketId}` ); socket.supportsAgentStreaming = false; window.addEventListener(ABORT_STREAM_EVENT, () => { window.dispatchEvent(new CustomEvent(AGENT_SESSION_END)); websocket.close(); }); socket.addEventListener("message", (event) => { setLoadingResponse(true); try { handleSocketResponse(socket, event, setChatHistory); } catch (e) { console.error("Failed to parse data"); window.dispatchEvent(new CustomEvent(AGENT_SESSION_END)); socket.close(); } setLoadingResponse(false); }); socket.addEventListener("close", (_event) => { window.dispatchEvent(new CustomEvent(AGENT_SESSION_END)); setChatHistory((prev) => [ ...prev.filter((msg) => !!msg.content), { uuid: v4(), type: "statusResponse", content: "Agent session complete.", role: "assistant", sources: [], closed: true, error: null, animate: false, pending: false, }, ]); setLoadingResponse(false); setWebsocket(null); setSocketId(null); }); setWebsocket(socket); window.dispatchEvent(new CustomEvent(AGENT_SESSION_START)); window.dispatchEvent(new CustomEvent(CLEAR_ATTACHMENTS_EVENT)); } catch (e) { setChatHistory((prev) => [ ...prev.filter((msg) => !!msg.content), { uuid: v4(), type: "abort", content: e.message, role: "assistant", sources: [], closed: true, error: e.message, animate: false, pending: false, }, ]); setLoadingResponse(false); setWebsocket(null); setSocketId(null); } } handleWSS(); }, [socketId]); return ( <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="transition-all duration-500 relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] bg-theme-bg-secondary w-full h-full overflow-y-scroll no-scroll z-[2]" > {isMobile && <SidebarMobileHeader />} <DnDFileUploaderWrapper> <MetricsProvider> <ChatHistory history={chatHistory} workspace={workspace} sendCommand={sendCommand} updateHistory={setChatHistory} regenerateAssistantMessage={regenerateAssistantMessage} hasAttachments={files.length > 0} /> </MetricsProvider> <PromptInput submit={handleSubmit} onChange={handleMessageChange} isStreaming={loadingResponse} sendCommand={sendCommand} attachments={files} /> </DnDFileUploaderWrapper> <ChatTooltips /> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/index.jsx
import React, { useState, useRef, useEffect } from "react"; import SlashCommandsButton, { SlashCommands, useSlashCommands, } from "./SlashCommands"; import debounce from "lodash.debounce"; import { PaperPlaneRight } from "@phosphor-icons/react"; import StopGenerationButton from "./StopGenerationButton"; import AvailableAgentsButton, { AvailableAgents, useAvailableAgents, } from "./AgentMenu"; import TextSizeButton from "./TextSizeMenu"; import LLMSelectorAction from "./LLMSelector/action"; import SpeechToText from "./SpeechToText"; import { Tooltip } from "react-tooltip"; import AttachmentManager from "./Attachments"; import AttachItem from "./AttachItem"; import { ATTACHMENTS_PROCESSED_EVENT, ATTACHMENTS_PROCESSING_EVENT, PASTE_ATTACHMENT_EVENT, } from "../DnDWrapper"; import useTextSize from "@/hooks/useTextSize"; import { useTranslation } from "react-i18next"; import Appearance from "@/models/appearance"; import usePromptInputStorage from "@/hooks/usePromptInputStorage"; export const PROMPT_INPUT_ID = "primary-prompt-input"; export const PROMPT_INPUT_EVENT = "set_prompt_input"; const MAX_EDIT_STACK_SIZE = 100; export default function PromptInput({ submit, onChange, isStreaming, sendCommand, attachments = [], }) { const { t } = useTranslation(); const { isDisabled } = useIsDisabled(); const [promptInput, setPromptInput] = useState(""); const { showAgents, setShowAgents } = useAvailableAgents(); const { showSlashCommand, setShowSlashCommand } = useSlashCommands(); const formRef = useRef(null); const textareaRef = useRef(null); const [_, setFocused] = useState(false); const undoStack = useRef([]); const redoStack = useRef([]); const { textSizeClass } = useTextSize(); // Synchronizes prompt input value with localStorage, scoped to the current thread. usePromptInputStorage({ onChange, promptInput, setPromptInput, }); /** * To prevent too many re-renders we remotely listen for updates from the parent * via an event cycle. Otherwise, using message as a prop leads to a re-render every * change on the input. * @param {{detail: {messageContent: string, writeMode: 'replace' | 'append'}}} e */ function handlePromptUpdate(e) { const { messageContent, writeMode = "replace" } = e?.detail ?? {}; if (writeMode === "append") setPromptInput((prev) => prev + messageContent); else setPromptInput(messageContent ?? ""); } useEffect(() => { if (!!window) window.addEventListener(PROMPT_INPUT_EVENT, handlePromptUpdate); return () => window?.removeEventListener(PROMPT_INPUT_EVENT, handlePromptUpdate); }, []); useEffect(() => { if (!isStreaming && textareaRef.current) textareaRef.current.focus(); resetTextAreaHeight(); }, [isStreaming]); /** * Save the current state before changes * @param {number} adjustment */ function saveCurrentState(adjustment = 0) { if (undoStack.current.length >= MAX_EDIT_STACK_SIZE) undoStack.current.shift(); undoStack.current.push({ value: promptInput, cursorPositionStart: textareaRef.current.selectionStart + adjustment, cursorPositionEnd: textareaRef.current.selectionEnd + adjustment, }); } const debouncedSaveState = debounce(saveCurrentState, 250); function handleSubmit(e) { setFocused(false); submit(e); } function resetTextAreaHeight() { if (!textareaRef.current) return; textareaRef.current.style.height = "auto"; } function checkForSlash(e) { const input = e.target.value; if (input === "/") setShowSlashCommand(true); if (showSlashCommand) setShowSlashCommand(false); return; } const watchForSlash = debounce(checkForSlash, 300); function checkForAt(e) { const input = e.target.value; if (input === "@") return setShowAgents(true); if (showAgents) return setShowAgents(false); } const watchForAt = debounce(checkForAt, 300); /** * Capture enter key press to handle submission, redo, or undo * via keyboard shortcuts * @param {KeyboardEvent} event */ function captureEnterOrUndo(event) { // Is simple enter key press w/o shift key if (event.keyCode === 13 && !event.shiftKey) { event.preventDefault(); if (isStreaming || isDisabled) return; // Prevent submission if streaming or disabled return submit(event); } // Is undo with Ctrl+Z or Cmd+Z + Shift key = Redo if ( (event.ctrlKey || event.metaKey) && event.key === "z" && event.shiftKey ) { event.preventDefault(); if (redoStack.current.length === 0) return; const nextState = redoStack.current.pop(); if (!nextState) return; undoStack.current.push({ value: promptInput, cursorPositionStart: textareaRef.current.selectionStart, cursorPositionEnd: textareaRef.current.selectionEnd, }); setPromptInput(nextState.value); setTimeout(() => { textareaRef.current.setSelectionRange( nextState.cursorPositionStart, nextState.cursorPositionEnd ); }, 0); } // Undo with Ctrl+Z or Cmd+Z if ( (event.ctrlKey || event.metaKey) && event.key === "z" && !event.shiftKey ) { if (undoStack.current.length === 0) return; const lastState = undoStack.current.pop(); if (!lastState) return; redoStack.current.push({ value: promptInput, cursorPositionStart: textareaRef.current.selectionStart, cursorPositionEnd: textareaRef.current.selectionEnd, }); setPromptInput(lastState.value); setTimeout(() => { textareaRef.current.setSelectionRange( lastState.cursorPositionStart, lastState.cursorPositionEnd ); }, 0); } } function adjustTextArea(event) { const element = event.target; element.style.height = "auto"; element.style.height = `${element.scrollHeight}px`; } function handlePasteEvent(e) { e.preventDefault(); if (e.clipboardData.items.length === 0) return false; // paste any clipboard items that are images. for (const item of e.clipboardData.items) { if (item.type.startsWith("image/")) { const file = item.getAsFile(); window.dispatchEvent( new CustomEvent(PASTE_ATTACHMENT_EVENT, { detail: { files: [file] }, }) ); continue; } // handle files specifically that are not images as uploads if (item.kind === "file") { const file = item.getAsFile(); window.dispatchEvent( new CustomEvent(PASTE_ATTACHMENT_EVENT, { detail: { files: [file] }, }) ); continue; } } const pasteText = e.clipboardData.getData("text/plain"); if (pasteText) { const textarea = textareaRef.current; const start = textarea.selectionStart; const end = textarea.selectionEnd; const newPromptInput = promptInput.substring(0, start) + pasteText + promptInput.substring(end); setPromptInput(newPromptInput); onChange({ target: { value: newPromptInput } }); // Set the cursor position after the pasted text // we need to use setTimeout to prevent the cursor from being set to the end of the text setTimeout(() => { textarea.selectionStart = textarea.selectionEnd = start + pasteText.length; adjustTextArea({ target: textarea }); }, 0); } return; } function handleChange(e) { debouncedSaveState(-1); onChange(e); watchForSlash(e); watchForAt(e); adjustTextArea(e); setPromptInput(e.target.value); } return ( <div className="w-full fixed md:absolute bottom-0 left-0 z-10 md:z-0 flex justify-center items-center pwa:pb-5"> <SlashCommands showing={showSlashCommand} setShowing={setShowSlashCommand} sendCommand={sendCommand} promptRef={textareaRef} /> <AvailableAgents showing={showAgents} setShowing={setShowAgents} sendCommand={sendCommand} promptRef={textareaRef} /> <form onSubmit={handleSubmit} className="flex flex-col gap-y-1 rounded-t-lg md:w-3/4 w-full mx-auto max-w-xl items-center" > <div className="flex items-center rounded-lg md:mb-4 md:w-full"> <div className="w-[95vw] md:w-[635px] bg-theme-bg-chat-input light:bg-white light:border-solid light:border-[1px] light:border-theme-chat-input-border shadow-sm rounded-2xl pwa:rounded-3xl flex flex-col px-2 overflow-hidden"> <AttachmentManager attachments={attachments} /> <div className="flex items-center border-b border-theme-chat-input-border mx-3"> <textarea id={PROMPT_INPUT_ID} ref={textareaRef} onChange={handleChange} onKeyDown={captureEnterOrUndo} onPaste={(e) => { saveCurrentState(); handlePasteEvent(e); }} required={true} onFocus={() => setFocused(true)} onBlur={(e) => { setFocused(false); adjustTextArea(e); }} value={promptInput} spellCheck={Appearance.get("enableSpellCheck")} className={`border-none cursor-text max-h-[50vh] md:max-h-[350px] md:min-h-[40px] mx-2 md:mx-0 pt-[12px] w-full leading-5 text-white bg-transparent placeholder:text-white/60 light:placeholder:text-theme-text-primary resize-none active:outline-none focus:outline-none flex-grow mb-1 pwa:!text-[16px] ${textSizeClass}`} placeholder={t("chat_window.send_message")} /> {isStreaming ? ( <StopGenerationButton /> ) : ( <> <button ref={formRef} type="submit" disabled={isDisabled} className="border-none inline-flex justify-center rounded-2xl cursor-pointer opacity-60 hover:opacity-100 light:opacity-100 light:hover:opacity-60 ml-4 disabled:cursor-not-allowed group" data-tooltip-id="send-prompt" data-tooltip-content={ isDisabled ? t("chat_window.attachments_processing") : t("chat_window.send") } aria-label={t("chat_window.send")} > <PaperPlaneRight color="var(--theme-sidebar-footer-icon-fill)" className="w-[22px] h-[22px] pointer-events-none text-theme-text-primary group-disabled:opacity-[25%]" weight="fill" /> <span className="sr-only">Send message</span> </button> <Tooltip id="send-prompt" place="bottom" delayShow={300} className="tooltip !text-xs z-99" /> </> )} </div> <div className="flex justify-between py-3.5 mx-3 mb-1"> <div className="flex gap-x-2"> <AttachItem /> <SlashCommandsButton showing={showSlashCommand} setShowSlashCommand={setShowSlashCommand} /> <AvailableAgentsButton showing={showAgents} setShowAgents={setShowAgents} /> <TextSizeButton /> <LLMSelectorAction /> </div> <div className="flex gap-x-2"> <SpeechToText sendCommand={sendCommand} /> </div> </div> </div> </div> </form> </div> ); } /** * Handle event listeners to prevent the send button from being used * for whatever reason that may we may want to prevent the user from sending a message. */ function useIsDisabled() { const [isDisabled, setIsDisabled] = useState(false); /** * Handle attachments processing and processed events * to prevent the send button from being clicked when attachments are processing * or else the query may not have relevant context since RAG is not yet ready. */ useEffect(() => { if (!window) return; window.addEventListener(ATTACHMENTS_PROCESSING_EVENT, () => setIsDisabled(true) ); window.addEventListener(ATTACHMENTS_PROCESSED_EVENT, () => setIsDisabled(false) ); return () => { window?.removeEventListener(ATTACHMENTS_PROCESSING_EVENT, () => setIsDisabled(true) ); window?.removeEventListener(ATTACHMENTS_PROCESSED_EVENT, () => setIsDisabled(false) ); }; }, []); return { isDisabled }; }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/AgentMenu/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/AgentMenu/index.jsx
import { useEffect, useRef, useState } from "react"; import { Tooltip } from "react-tooltip"; import { At } from "@phosphor-icons/react"; import { useIsAgentSessionActive } from "@/utils/chat/agent"; import { useTranslation } from "react-i18next"; import { useSearchParams } from "react-router-dom"; export default function AvailableAgentsButton({ showing, setShowAgents }) { const { t } = useTranslation(); const agentSessionActive = useIsAgentSessionActive(); if (agentSessionActive) return null; return ( <div id="agent-list-btn" data-tooltip-id="tooltip-agent-list-btn" data-tooltip-content={t("chat_window.agents")} aria-label={t("chat_window.agents")} onClick={() => setShowAgents(!showing)} className={`flex justify-center items-center cursor-pointer ${ showing ? "!opacity-100" : "" }`} > <At color="var(--theme-sidebar-footer-icon-fill)" className={`w-[22px] h-[22px] pointer-events-none text-theme-text-primary opacity-60 hover:opacity-100 light:opacity-100 light:hover:opacity-60`} /> <Tooltip id="tooltip-agent-list-btn" place="top" delayShow={300} className="tooltip !text-xs z-99" /> </div> ); } function AbilityTag({ text }) { return ( <div className="px-2 bg-theme-action-menu-item-hover text-theme-text-secondary text-xs w-fit rounded-sm"> <p>{text}</p> </div> ); } export function AvailableAgents({ showing, setShowing, sendCommand, promptRef, }) { const formRef = useRef(null); const agentSessionActive = useIsAgentSessionActive(); const [searchParams] = useSearchParams(); const { t } = useTranslation(); /* * @checklist-item * If the URL has the agent param, open the agent menu for the user * automatically when the component mounts. */ useEffect(() => { if (searchParams.get("action") === "set-agent-chat" && !showing) handleAgentClick(); }, [promptRef.current]); useEffect(() => { function listenForOutsideClick() { if (!showing || !formRef.current) return false; document.addEventListener("click", closeIfOutside); } listenForOutsideClick(); }, [showing, formRef.current]); const closeIfOutside = ({ target }) => { if (target.id === "agent-list-btn") return; const isOutside = !formRef?.current?.contains(target); if (!isOutside) return; setShowing(false); }; const handleAgentClick = () => { setShowing(false); sendCommand({ text: "@agent " }); promptRef?.current?.focus(); }; if (agentSessionActive) return null; return ( <> <div hidden={!showing}> <div className="w-full flex justify-center absolute bottom-[130px] md:bottom-[150px] left-0 z-10 px-4"> <div ref={formRef} className="w-[600px] p-2 bg-theme-action-menu-bg rounded-2xl shadow flex-col justify-center items-start gap-2.5 inline-flex" > <button onClick={handleAgentClick} className="border-none w-full hover:cursor-pointer hover:bg-theme-action-menu-item-hover px-2 py-2 rounded-xl flex flex-col justify-start group" > <div className="w-full flex-col text-left flex pointer-events-none"> <div className="text-theme-text-primary text-sm"> <b>{t("chat_window.at_agent")}</b> {t("chat_window.default_agent_description")} </div> <div className="flex flex-wrap gap-2 mt-2"> <AbilityTag text="rag-search" /> <AbilityTag text="web-scraping" /> <AbilityTag text="web-browsing" /> <AbilityTag text="save-file-to-browser" /> <AbilityTag text="list-documents" /> <AbilityTag text="summarize-document" /> <AbilityTag text="chart-generation" /> </div> </div> </button> <button type="button" disabled={true} className="w-full rounded-xl flex flex-col justify-start group" > <div className="w-full flex-col text-center flex pointer-events-none"> <div className="text-theme-text-secondary text-xs italic"> {t("chat_window.custom_agents_coming_soon")} </div> </div> </button> </div> </div> </div> </> ); } export function useAvailableAgents() { const [showAgents, setShowAgents] = useState(false); return { showAgents, setShowAgents }; }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/AttachItem/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/AttachItem/index.jsx
import { PaperclipHorizontal } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; import { useTranslation } from "react-i18next"; import { useRef, useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import Workspace from "@/models/workspace"; import { ATTACHMENTS_PROCESSED_EVENT, REMOVE_ATTACHMENT_EVENT, } from "../../DnDWrapper"; import { useTheme } from "@/hooks/useTheme"; import ParsedFilesMenu from "./ParsedFilesMenu"; /** * This is a simple proxy component that clicks on the DnD file uploader for the user. * @returns */ export default function AttachItem() { const { t } = useTranslation(); const { theme } = useTheme(); const { slug, threadSlug = null } = useParams(); const tooltipRef = useRef(null); const [isEmbedding, setIsEmbedding] = useState(false); const [files, setFiles] = useState([]); const [currentTokens, setCurrentTokens] = useState(0); const [contextWindow, setContextWindow] = useState(Infinity); const [showTooltip, setShowTooltip] = useState(false); const [isLoading, setIsLoading] = useState(true); const fetchFiles = () => { if (!slug) return; if (isEmbedding) return; setIsLoading(true); Workspace.getParsedFiles(slug, threadSlug) .then(({ files, contextWindow, currentContextTokenCount }) => { setFiles(files); setShowTooltip(files.length > 0); setContextWindow(contextWindow); setCurrentTokens(currentContextTokenCount); }) .finally(() => { setIsLoading(false); }); }; /** * Handles the removal of an attachment from the parsed files * and triggers a re-fetch of the parsed files. * This function handles when the user clicks the X on an Attachment via the AttachmentManager * so we need to sync the state in the ParsedFilesMenu picker here. */ async function handleRemoveAttachment(e) { const { document } = e.detail; await Workspace.deleteParsedFiles(slug, [document.id]); fetchFiles(); } /** * Handles the click event for the attach item button. * @param {MouseEvent} e - The click event. * @returns {void} */ function handleClick(e) { e?.target?.blur(); document?.getElementById("dnd-chat-file-uploader")?.click(); return; } useEffect(() => { fetchFiles(); window.addEventListener(ATTACHMENTS_PROCESSED_EVENT, fetchFiles); window.addEventListener(REMOVE_ATTACHMENT_EVENT, handleRemoveAttachment); return () => { window.removeEventListener(ATTACHMENTS_PROCESSED_EVENT, fetchFiles); window.removeEventListener( REMOVE_ATTACHMENT_EVENT, handleRemoveAttachment ); }; }, [slug, threadSlug]); return ( <> <button id="attach-item-btn" data-tooltip-id="tooltip-attach-item-btn" aria-label={t("chat_window.attach_file")} type="button" onClick={handleClick} onPointerEnter={fetchFiles} className={`border-none relative flex justify-center items-center opacity-60 hover:opacity-100 light:opacity-100 light:hover:opacity-60 cursor-pointer`} > <div className="relative"> <PaperclipHorizontal color="var(--theme-sidebar-footer-icon-fill)" className="w-[22px] h-[22px] pointer-events-none text-white rotate-90 -scale-y-100" /> {files.length > 0 && ( <div className="absolute -top-2 right-[1%] bg-white text-black light:invert text-[8px] rounded-full px-1 flex items-center justify-center"> {files.length} </div> )} </div> </button> {showTooltip && ( <Tooltip ref={tooltipRef} id="tooltip-attach-item-btn" place="top" opacity={1} clickable={!isEmbedding} delayShow={300} delayHide={isEmbedding ? 999999 : 800} // Prevent tooltip from hiding during embedding arrowColor={ theme === "light" ? "var(--theme-modal-border)" : "var(--theme-bg-primary)" } className="z-99 !w-[400px] !bg-theme-bg-primary !px-[5px] !rounded-lg !pointer-events-auto light:border-2 light:border-theme-modal-border" > <ParsedFilesMenu onEmbeddingChange={setIsEmbedding} tooltipRef={tooltipRef} isLoading={isLoading} files={files} setFiles={setFiles} currentTokens={currentTokens} setCurrentTokens={setCurrentTokens} contextWindow={contextWindow} /> </Tooltip> )} </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/AttachItem/ParsedFilesMenu/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/AttachItem/ParsedFilesMenu/index.jsx
import { useState } from "react"; import { X, CircleNotch, Warning } from "@phosphor-icons/react"; import Workspace from "@/models/workspace"; import { useParams } from "react-router-dom"; import { nFormatter } from "@/utils/numbers"; import showToast from "@/utils/toast"; import pluralize from "pluralize"; import { PARSED_FILE_ATTACHMENT_REMOVED_EVENT } from "../../../DnDWrapper"; import useUser from "@/hooks/useUser"; export default function ParsedFilesMenu({ onEmbeddingChange, tooltipRef, files, setFiles, currentTokens, setCurrentTokens, contextWindow, isLoading, }) { const { user } = useUser(); const canEmbed = !user || user.role !== "default"; const initialContextWindowLimitExceeded = contextWindow && currentTokens >= contextWindow * Workspace.maxContextWindowLimit; const { slug, threadSlug = null } = useParams(); const [isEmbedding, setIsEmbedding] = useState(false); const [embedProgress, setEmbedProgress] = useState(1); const [contextWindowLimitExceeded, setContextWindowLimitExceeded] = useState( initialContextWindowLimitExceeded ); async function handleRemove(e, file) { e.preventDefault(); e.stopPropagation(); if (!file?.id) return; const success = await Workspace.deleteParsedFiles(slug, [file.id]); if (!success) return; // Update the local files list and current tokens setFiles((prev) => prev.filter((f) => f.id !== file.id)); // Dispatch an event to the DnDFileUploaderWrapper to update the files list in attachment manager if it exists window.dispatchEvent( new CustomEvent(PARSED_FILE_ATTACHMENT_REMOVED_EVENT, { detail: { document: file }, }) ); const { currentContextTokenCount } = await Workspace.getParsedFiles( slug, threadSlug ); const newContextWindowLimitExceeded = contextWindow && currentContextTokenCount >= contextWindow * Workspace.maxContextWindowLimit; setCurrentTokens(currentContextTokenCount); setContextWindowLimitExceeded(newContextWindowLimitExceeded); } /** * Handles the embedding of the files when the user exceeds the context window limit * and opts to embed the files into the workspace instead. * @returns {Promise<void>} */ async function handleEmbed() { if (!files.length) return; setIsEmbedding(true); onEmbeddingChange?.(true); setEmbedProgress(1); try { let completed = 0; await Promise.all( files.map((file) => Workspace.embedParsedFile(slug, file.id).then(() => { completed++; setEmbedProgress(completed + 1); }) ) ); setFiles([]); const { currentContextTokenCount } = await Workspace.getParsedFiles( slug, threadSlug ); setCurrentTokens(currentContextTokenCount); setContextWindowLimitExceeded( currentContextTokenCount >= contextWindow * Workspace.maxContextWindowLimit ); showToast( `${files.length} ${pluralize("file", files.length)} embedded successfully`, "success" ); tooltipRef?.current?.close(); } catch (error) { console.error("Failed to embed files:", error); showToast("Failed to embed files", "error"); } setIsEmbedding(false); onEmbeddingChange?.(false); setEmbedProgress(1); } return ( <div className="flex flex-col gap-2 p-2"> <div className="flex items-center justify-between"> <div className="text-sm font-medium text-theme-text-primary"> Current Context ({files.length} files) </div> <div // If the user cannot see the embed CTA, show a tooltip {...(contextWindowLimitExceeded && !canEmbed && { "data-tooltip-id": "context-window-limit-exceeded", "data-tooltip-content": "You have exceeded the context window limit. Some files may be truncated or excluded from chat responses. Responses may hallucinate or lack relevant information.", })} className={`flex items-center gap-x-1 ${contextWindowLimitExceeded && !canEmbed ? "cursor-pointer" : ""}`} > {contextWindowLimitExceeded && ( <Warning size={14} className="text-orange-600" /> )} <div className={`text-xs ${contextWindowLimitExceeded ? "text-orange-600" : "text-theme-text-secondary"}`} > {nFormatter(currentTokens)} /{" "} {contextWindow ? nFormatter(contextWindow) : "--"} tokens </div> </div> </div> {contextWindowLimitExceeded && canEmbed && ( <div className="flex flex-col gap-2 p-2 bg-theme-bg-secondary light:bg-theme-bg-primary rounded"> <div className="flex items-start gap-2"> <Warning className="flex-shrink-0 mt-1 text-yellow-500 light:text-yellow-600" size={16} /> <div className="text-xs text-theme-text-primary"> Your context window is getting full. Some files may be truncated or excluded from chat responses. We recommend embedding these files directly into your workspace for better results. </div> </div> <button onClick={handleEmbed} disabled={isEmbedding} className="border-none disabled:opacity-50 flex items-center justify-center gap-2 px-3 py-2 text-xs bg-primary-button hover:bg-theme-button-primary-hover text-white font-medium rounded transition-colors shadow-sm" > {isEmbedding ? ( <> <CircleNotch size={14} className="animate-spin" /> Embedding {embedProgress} of {files.length} files... </> ) : ( "Embed Files into Workspace" )} </button> </div> )} <div className="flex flex-col gap-1 max-h-[300px] overflow-y-auto"> {files.length > 0 && files.map((file, i) => ( <div key={i} className={ "flex items-center justify-between gap-2 p-2 text-xs bg-theme-bg-secondary rounded" } > <div className="truncate flex-1 text-theme-text-primary"> {file.title} </div> <button onClick={(e) => handleRemove(e, file)} className="border-none text-theme-text-secondary hover:text-theme-text-primary" disabled={isEmbedding} > <X size={16} /> </button> </div> ))} {isLoading && ( <div className="flex items-center justify-center gap-2 text-xs text-theme-text-secondary text-center py-2"> <CircleNotch size={16} className="animate-spin" /> Loading... </div> )} {!isLoading && files.length === 0 && ( <div className="text-xs text-theme-text-secondary text-center py-2"> No files found </div> )} </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/index.jsx
import { useEffect, useRef, useState } from "react"; import SlashCommandIcon from "./icons/SlashCommandIcon"; import { Tooltip } from "react-tooltip"; import ResetCommand from "./reset"; import EndAgentSession from "./endAgentSession"; import SlashPresets from "./SlashPresets"; import { useTranslation } from "react-i18next"; import { useSlashCommandKeyboardNavigation } from "@/hooks/useSlashCommandKeyboardNavigation"; export default function SlashCommandsButton({ showing, setShowSlashCommand }) { const { t } = useTranslation(); return ( <div id="slash-cmd-btn" data-tooltip-id="tooltip-slash-cmd-btn" data-tooltip-content={t("chat_window.slash")} onClick={() => setShowSlashCommand(!showing)} className={`flex justify-center items-center cursor-pointer ${ showing ? "!opacity-100" : "" }`} > <SlashCommandIcon color="var(--theme-sidebar-footer-icon-fill)" className={`w-[20px] h-[20px] pointer-events-none opacity-60 hover:opacity-100 light:opacity-100 light:hover:opacity-60`} /> <Tooltip id="tooltip-slash-cmd-btn" place="top" delayShow={300} className="tooltip !text-xs z-99" /> </div> ); } export function SlashCommands({ showing, setShowing, sendCommand, promptRef }) { const cmdRef = useRef(null); useSlashCommandKeyboardNavigation({ showing }); useEffect(() => { function listenForOutsideClick() { if (!showing || !cmdRef.current) return false; document.addEventListener("click", closeIfOutside); } listenForOutsideClick(); }, [showing, cmdRef.current]); const closeIfOutside = ({ target }) => { if (target.id === "slash-cmd-btn") return; const isOutside = !cmdRef?.current?.contains(target); if (!isOutside) return; setShowing(false); }; return ( <div hidden={!showing}> <div className="w-full flex justify-center absolute bottom-[130px] md:bottom-[150px] left-0 z-10 px-4"> <div ref={cmdRef} className="w-[600px] bg-theme-action-menu-bg rounded-2xl flex shadow flex-col justify-start items-start gap-2.5 p-2 overflow-y-auto max-h-[300px] no-scroll" > <ResetCommand sendCommand={sendCommand} setShowing={setShowing} /> <EndAgentSession sendCommand={sendCommand} setShowing={setShowing} /> <SlashPresets sendCommand={sendCommand} setShowing={setShowing} promptRef={promptRef} /> </div> </div> </div> ); } export function useSlashCommands() { const [showSlashCommand, setShowSlashCommand] = useState(false); return { showSlashCommand, setShowSlashCommand }; }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/endAgentSession.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/endAgentSession.jsx
import { useIsAgentSessionActive } from "@/utils/chat/agent"; export default function EndAgentSession({ setShowing, sendCommand }) { const isActiveAgentSession = useIsAgentSessionActive(); if (!isActiveAgentSession) return null; return ( <button type="button" data-slash-command="/exit" onClick={() => { setShowing(false); sendCommand({ text: "/exit", autoSubmit: true }); }} className="border-none w-full hover:cursor-pointer hover:bg-theme-action-menu-item-hover px-2 py-2 rounded-xl flex flex-col justify-start" > <div className="w-full flex-col text-left flex pointer-events-none"> <div className="text-white text-sm font-bold">/exit</div> <div className="text-white text-opacity-60 text-sm"> Halt the current agent session. </div> </div> </button> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/reset.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/reset.jsx
import { useIsAgentSessionActive } from "@/utils/chat/agent"; import { useTranslation } from "react-i18next"; export default function ResetCommand({ setShowing, sendCommand }) { const { t } = useTranslation(); const isActiveAgentSession = useIsAgentSessionActive(); if (isActiveAgentSession) return null; // cannot reset during active agent chat return ( <button type="button" data-slash-command="/reset" onClick={() => { setShowing(false); sendCommand({ text: "/reset", autoSubmit: true }); }} className="border-none w-full hover:cursor-pointer hover:bg-theme-action-menu-item-hover px-2 py-2 rounded-xl flex flex-col justify-start" > <div className="w-full flex-col text-left flex pointer-events-none"> <div className="text-white text-sm font-bold"> {t("chat_window.slash_reset")} </div> <div className="text-white text-opacity-60 text-sm"> {t("chat_window.preset_reset_description")} </div> </div> </button> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/icons/SlashCommandIcon.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/icons/SlashCommandIcon.jsx
export default function SlashCommandIcon(props) { return ( <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props} > <rect x="1.02539" y="1.43799" width="17.252" height="17.252" rx="2" stroke="currentColor" strokeWidth="1.5" /> <path d="M6.70312 14.5408L12.5996 5.8056" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /> </svg> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/SlashPresets/EditPresetModal.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/SlashPresets/EditPresetModal.jsx
import { useState, useEffect } from "react"; import { X } from "@phosphor-icons/react"; import ModalWrapper from "@/components/ModalWrapper"; import { CMD_REGEX } from "."; export default function EditPresetModal({ isOpen, onClose, onSave, onDelete, preset, }) { const [command, setCommand] = useState(""); const [deleting, setDeleting] = useState(false); useEffect(() => { if (preset && isOpen) { setCommand(preset.command?.slice(1) || ""); } }, [preset, isOpen]); const handleSubmit = (e) => { e.preventDefault(); const form = new FormData(e.target); const sanitizedCommand = command.replace(CMD_REGEX, ""); onSave({ id: preset.id, command: `/${sanitizedCommand}`, prompt: form.get("prompt"), description: form.get("description"), }); }; const handleCommandChange = (e) => { const value = e.target.value.replace(CMD_REGEX, ""); setCommand(value); }; const handleDelete = async () => { if (!window.confirm("Are you sure you want to delete this preset?")) return; setDeleting(true); await onDelete(preset.id); setDeleting(false); onClose(); }; return ( <ModalWrapper isOpen={isOpen}> <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> Edit Preset </h3> </div> <button onClick={onClose} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={24} weight="bold" className="text-white" /> </button> </div> <div className="h-full w-full overflow-y-auto" style={{ maxHeight: "calc(100vh - 200px)" }} > <form onSubmit={handleSubmit}> <div className="py-7 px-9 space-y-2 flex-col"> <div className="w-full flex flex-col gap-y-4"> <div> <label htmlFor="command" className="block mb-2 text-sm font-medium text-white" > Command </label> <div className="flex items-center"> <span className="text-white text-sm mr-2 font-bold">/</span> <input type="text" name="command" placeholder="your-command" value={command} onChange={handleCommandChange} required={true} className="border-none bg-theme-settings-input-bg w-full text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" /> </div> </div> <div> <label htmlFor="prompt" className="block mb-2 text-sm font-medium text-white" > Prompt </label> <textarea name="prompt" placeholder="This is a test prompt. Please respond with a poem about LLMs." defaultValue={preset.prompt} required={true} className="border-none bg-theme-settings-input-bg w-full text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" ></textarea> </div> <div> <label htmlFor="description" className="block mb-2 text-sm font-medium text-white" > Description </label> <input type="text" name="description" defaultValue={preset.description} placeholder="Responds with a poem about LLMs." required={true} className="border-none bg-theme-settings-input-bg w-full text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" /> </div> </div> </div> <div className="flex w-full justify-between items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button disabled={deleting} onClick={handleDelete} type="button" className="border-none transition-all duration-300 bg-transparent text-red-500 hover:bg-red-500/25 px-4 py-2 rounded-lg text-sm disabled:opacity-50" > {deleting ? "Deleting..." : "Delete Preset"} </button> <div className="flex space-x-2"> <button onClick={onClose} type="button" className="border-none transition-all duration-300 bg-transparent text-white hover:opacity-60 px-4 py-2 rounded-lg text-sm" > Cancel </button> <button type="submit" className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > Save </button> </div> </div> </form> </div> </div> </ModalWrapper> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/SlashPresets/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/SlashPresets/index.jsx
import { useEffect, useState, useRef } from "react"; import { useIsAgentSessionActive } from "@/utils/chat/agent"; import AddPresetModal from "./AddPresetModal"; import EditPresetModal from "./EditPresetModal"; import { useModal } from "@/hooks/useModal"; import System from "@/models/system"; import { DotsThree, Plus } from "@phosphor-icons/react"; import showToast from "@/utils/toast"; import { useSearchParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; import PublishEntityModal from "@/components/CommunityHub/PublishEntityModal"; export const CMD_REGEX = new RegExp(/[^a-zA-Z0-9_-]/g); export default function SlashPresets({ setShowing, sendCommand, promptRef }) { const { t } = useTranslation(); const isActiveAgentSession = useIsAgentSessionActive(); const { isOpen: isAddModalOpen, openModal: openAddModal, closeModal: closeAddModal, } = useModal(); const { isOpen: isEditModalOpen, openModal: openEditModal, closeModal: closeEditModal, } = useModal(); const { isOpen: isPublishModalOpen, openModal: openPublishModal, closeModal: closePublishModal, } = useModal(); const [presets, setPresets] = useState([]); const [selectedPreset, setSelectedPreset] = useState(null); const [presetToPublish, setPresetToPublish] = useState(null); const [searchParams] = useSearchParams(); useEffect(() => { fetchPresets(); }, []); /* * @checklist-item * If the URL has the slash-commands param, open the add modal for the user * automatically when the component mounts. */ useEffect(() => { if ( searchParams.get("action") === "open-new-slash-command-modal" && !isAddModalOpen ) openAddModal(); }, []); if (isActiveAgentSession) return null; const fetchPresets = async () => { const presets = await System.getSlashCommandPresets(); setPresets(presets); }; const handleSavePreset = async (preset) => { const { error } = await System.createSlashCommandPreset(preset); if (!!error) { showToast(error, "error"); return false; } fetchPresets(); closeAddModal(); return true; }; const handleEditPreset = (preset) => { setSelectedPreset(preset); openEditModal(); }; const handleUpdatePreset = async (updatedPreset) => { const { error } = await System.updateSlashCommandPreset( updatedPreset.id, updatedPreset ); if (!!error) { showToast(error, "error"); return; } fetchPresets(); closeEditModalAndResetPreset(); }; const handleDeletePreset = async (presetId) => { await System.deleteSlashCommandPreset(presetId); fetchPresets(); closeEditModalAndResetPreset(); }; const closeEditModalAndResetPreset = () => { closeEditModal(); setSelectedPreset(null); }; const handlePublishPreset = (preset) => { setPresetToPublish({ name: preset.command.slice(1), description: preset.description, command: preset.command, prompt: preset.prompt, }); openPublishModal(); }; return ( <> {presets.map((preset) => ( <PresetItem key={preset.id} preset={preset} onUse={() => { setShowing(false); sendCommand({ text: `${preset.command} ` }); promptRef?.current?.focus(); }} onEdit={handleEditPreset} onPublish={handlePublishPreset} /> ))} <button onClick={openAddModal} className="border-none w-full hover:cursor-pointer hover:bg-theme-action-menu-item-hover px-2 py-1 rounded-xl flex flex-col justify-start" > <div className="w-full flex-row flex pointer-events-none items-center gap-2"> <Plus size={24} weight="fill" className="text-theme-text-primary" /> <div className="text-theme-text-primary text-sm font-medium"> {t("chat_window.add_new_preset")} </div> </div> </button> <AddPresetModal isOpen={isAddModalOpen} onClose={closeAddModal} onSave={handleSavePreset} /> {selectedPreset && ( <EditPresetModal isOpen={isEditModalOpen} onClose={closeEditModalAndResetPreset} onSave={handleUpdatePreset} onDelete={handleDeletePreset} preset={selectedPreset} /> )} <PublishEntityModal show={isPublishModalOpen} onClose={closePublishModal} entityType="slash-command" entity={presetToPublish} /> </> ); } function PresetItem({ preset, onUse, onEdit, onPublish }) { const [showMenu, setShowMenu] = useState(false); const menuRef = useRef(null); const menuButtonRef = useRef(null); useEffect(() => { const handleClickOutside = (event) => { if ( showMenu && menuRef.current && !menuRef.current.contains(event.target) && menuButtonRef.current && !menuButtonRef.current.contains(event.target) ) { setShowMenu(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [showMenu]); return ( <button type="button" data-slash-command={preset.command} onClick={onUse} className="border-none w-full hover:cursor-pointer hover:bg-theme-action-menu-item-hover px-2 py-2 rounded-xl flex flex-row justify-start items-center relative" > <div className="flex-col text-left flex pointer-events-none flex-1 min-w-0"> <div className="text-theme-text-primary text-sm font-bold truncate"> {preset.command} </div> <div className="text-theme-text-secondary text-sm truncate"> {preset.description} </div> </div> <button ref={menuButtonRef} type="button" tabIndex={-1} onClick={(e) => { e.stopPropagation(); setShowMenu(!showMenu); }} className="border-none text-theme-text-primary text-sm p-1 hover:cursor-pointer hover:bg-theme-action-menu-item-hover rounded-full ml-2 flex-shrink-0 z-20" aria-label="More actions" > <DotsThree size={24} weight="bold" /> </button> {showMenu && ( <div ref={menuRef} className="absolute right-0 top-10 bg-theme-bg-popup-menu rounded-lg z-50 min-w-[160px] shadow-lg border border-theme-modal-border flex flex-col" > <button type="button" className="px-[10px] py-[6px] text-sm text-white hover:bg-theme-sidebar-item-hover rounded-t-lg cursor-pointer border-none w-full text-left whitespace-nowrap" onClick={(e) => { e.stopPropagation(); setShowMenu(false); onEdit(preset); }} > Edit </button> <button type="button" className="px-[10px] py-[6px] text-sm text-white hover:bg-theme-sidebar-item-hover rounded-b-lg cursor-pointer border-none w-full text-left whitespace-nowrap" onClick={(e) => { e.stopPropagation(); setShowMenu(false); onPublish(preset); }} > Publish </button> </div> )} </button> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/SlashPresets/AddPresetModal.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SlashCommands/SlashPresets/AddPresetModal.jsx
import { useState } from "react"; import { X } from "@phosphor-icons/react"; import ModalWrapper from "@/components/ModalWrapper"; import { CMD_REGEX } from "."; import { useTranslation } from "react-i18next"; export default function AddPresetModal({ isOpen, onClose, onSave }) { const [command, setCommand] = useState(""); const { t } = useTranslation(); const handleSubmit = async (e) => { e.preventDefault(); const form = new FormData(e.target); const sanitizedCommand = command.replace(CMD_REGEX, ""); const saved = await onSave({ command: `/${sanitizedCommand}`, prompt: form.get("prompt"), description: form.get("description"), }); if (saved) setCommand(""); }; const handleCommandChange = (e) => { const value = e.target.value.replace(CMD_REGEX, ""); setCommand(value); }; return ( <ModalWrapper isOpen={isOpen}> <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> {t("chat_window.add_new_preset")} </h3> </div> <button onClick={onClose} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={24} weight="bold" className="text-white" /> </button> </div> <div className="h-full w-full overflow-y-auto" style={{ maxHeight: "calc(100vh - 200px)" }} > <form onSubmit={handleSubmit}> <div className="py-7 px-9 space-y-2 flex-col"> <div className="w-full flex flex-col gap-y-4"> <div> <label htmlFor="command" className="block mb-2 text-sm font-medium text-white" > {t("chat_window.command")} </label> <div className="flex items-center"> <span className="text-white text-sm mr-2 font-bold">/</span> <input name="command" type="text" id="command" placeholder={t("chat_window.your_command")} value={command} onChange={handleCommandChange} maxLength={25} autoComplete="off" required={true} className="border-none bg-theme-settings-input-bg w-full text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" /> </div> </div> <div> <label htmlFor="prompt" className="block mb-2 text-sm font-medium text-white" > Prompt </label> <textarea name="prompt" id="prompt" autoComplete="off" placeholder={t("chat_window.placeholder_prompt")} required={true} className="border-none bg-theme-settings-input-bg w-full text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" ></textarea> </div> <div> <label htmlFor="description" className="block mb-2 text-sm font-medium text-white" > {t("chat_window.description")} </label> <input type="text" name="description" id="description" placeholder={t("chat_window.placeholder_description")} maxLength={80} autoComplete="off" required={true} className="border-none bg-theme-settings-input-bg w-full text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" /> </div> </div> </div> <div className="flex w-full justify-end items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button onClick={onClose} type="button" className="transition-all duration-300 bg-transparent text-white hover:opacity-60 px-4 py-2 rounded-lg text-sm" > {t("chat_window.cancel")} </button> <button type="submit" className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > {t("chat_window.save")} </button> </div> </form> </div> </div> </ModalWrapper> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/Attachments/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/Attachments/index.jsx
import { CircleNotch, FileCode, FileCsv, FileDoc, FileHtml, FileText, FileImage, FilePdf, WarningOctagon, X, } from "@phosphor-icons/react"; import { REMOVE_ATTACHMENT_EVENT } from "../../DnDWrapper"; import { Tooltip } from "react-tooltip"; /** * @param {{attachments: import("../../DnDWrapper").Attachment[]}} * @returns */ export default function AttachmentManager({ attachments }) { if (attachments.length === 0) return null; return ( <div className="flex flex-wrap gap-2 mt-2 mb-4"> {attachments.map((attachment) => ( <AttachmentItem key={attachment.uid} attachment={attachment} /> ))} </div> ); } /** * @param {{attachment: import("../../DnDWrapper").Attachment}} */ function AttachmentItem({ attachment }) { const { uid, file, status, error, document, type, contentString } = attachment; const { iconBgColor, Icon } = displayFromFile(file); function removeFileFromQueue() { window.dispatchEvent( new CustomEvent(REMOVE_ATTACHMENT_EVENT, { detail: { uid, document } }) ); } if (status === "in_progress") { return ( <div className="relative flex items-center gap-x-1 rounded-lg bg-theme-attachment-bg border-none w-[180px] group"> <div className={`bg-theme-attachment-icon-spinner-bg rounded-md flex items-center justify-center flex-shrink-0 h-[32px] w-[32px] m-1`} > <CircleNotch size={18} weight="bold" className="text-theme-attachment-icon-spinner animate-spin" /> </div> <div className="flex flex-col w-[125px]"> <p className="text-theme-attachment-text text-xs font-semibold truncate"> {file.name} </p> <p className="text-theme-attachment-text-secondary text-[10px] leading-[14px] font-medium"> Uploading... </p> </div> </div> ); } if (status === "failed") { return ( <> <div data-tooltip-id={`attachment-uid-${uid}-error`} data-tooltip-content={error} className={`relative flex items-center gap-x-1 rounded-lg bg-theme-attachment-error-bg border-none w-[180px] group`} > <div className="invisible group-hover:visible absolute -top-[5px] -right-[5px] w-fit h-fit z-[10]"> <button onClick={removeFileFromQueue} type="button" className="bg-white hover:bg-error hover:text-theme-attachment-text rounded-full p-1 flex items-center justify-center hover:border-transparent border border-theme-attachment-bg" > <X size={10} className="flex-shrink-0" /> </button> </div> <div className={`bg-error rounded-md flex items-center justify-center flex-shrink-0 h-[32px] w-[32px] m-1`} > <WarningOctagon size={24} className="text-theme-attachment-icon" /> </div> <div className="flex flex-col w-[125px]"> <p className="text-theme-attachment-text text-xs font-semibold truncate"> {file.name} </p> <p className="text-theme-attachment-text-secondary text-[10px] leading-[14px] font-medium truncate"> {error ?? "File not embedded!"} </p> </div> </div> <Tooltip id={`attachment-uid-${uid}-error`} place="top" delayShow={300} className="allm-tooltip !allm-text-xs" /> </> ); } if (type === "attachment") { return ( <> <div data-tooltip-id={`attachment-uid-${uid}-success`} data-tooltip-content={`${file.name} will be attached to this prompt. It will not be embedded into the workspace permanently.`} className={`relative flex items-center gap-x-1 rounded-lg bg-theme-attachment-success-bg border-none w-[180px] group`} > <div className="invisible group-hover:visible absolute -top-[5px] -right-[5px] w-fit h-fit z-[10]"> <button onClick={removeFileFromQueue} type="button" className="bg-white hover:bg-error hover:text-theme-attachment-text rounded-full p-1 flex items-center justify-center hover:border-transparent border border-theme-attachment-bg" > <X size={10} className="flex-shrink-0" /> </button> </div> {contentString ? ( <img alt={`Preview of ${file.name}`} src={contentString} className={`${iconBgColor} w-[30px] h-[30px] rounded-lg flex items-center justify-center m-1`} /> ) : ( <div className={`${iconBgColor} rounded-md flex items-center justify-center flex-shrink-0 h-[32px] w-[32px] m-1`} > <Icon size={24} className="text-theme-attachment-icon" /> </div> )} <div className="flex flex-col w-[125px]"> <p className="text-theme-attachment-text text-xs font-semibold truncate"> {file.name} </p> <p className="text-theme-attachment-text-secondary text-[10px] leading-[14px] font-medium"> Image attached! </p> </div> </div> <Tooltip id={`attachment-uid-${uid}-success`} place="top" delayShow={300} className="allm-tooltip !allm-text-xs" /> </> ); } return ( <> <div data-tooltip-id={`attachment-uid-${uid}-success`} data-tooltip-content={ status === "embedded" ? `${file.name} was uploaded and embedded into this workspace. It will be available for RAG chat now.` : `${file.name} will be used as context for this chat only.` } className={`relative flex items-center gap-x-1 rounded-lg bg-theme-attachment-bg border-none w-[180px] group`} > <div className="invisible group-hover:visible absolute -top-[5px] -right-[5px] w-fit h-fit z-[10]"> <button onClick={removeFileFromQueue} type="button" className="bg-white hover:bg-error hover:text-theme-attachment-text rounded-full p-1 flex items-center justify-center hover:border-transparent border border-theme-attachment-bg" > <X size={10} className="flex-shrink-0" /> </button> </div> <div className={`${iconBgColor} rounded-md flex items-center justify-center flex-shrink-0 h-[32px] w-[32px] m-1`} > <Icon size={24} weight="light" className="text-theme-attachment-icon" /> </div> <div className="flex flex-col w-[125px]"> <p className="text-white text-xs font-semibold truncate"> {file.name} </p> <p className="text-theme-attachment-text-secondary text-[10px] leading-[14px] font-medium"> {status === "embedded" ? "File embedded!" : "Added as context!"} </p> </div> </div> <Tooltip id={`attachment-uid-${uid}-success`} place="top" delayShow={300} className="allm-tooltip !allm-text-xs" /> </> ); } /** * @param {File} file * @returns {{iconBgColor:string, Icon: React.Component}} */ function displayFromFile(file) { const extension = file?.name?.split(".")?.pop()?.toLowerCase() ?? "txt"; switch (extension) { case "pdf": return { iconBgColor: "bg-magenta", Icon: FilePdf }; case "doc": case "docx": return { iconBgColor: "bg-royalblue", Icon: FileDoc }; case "html": return { iconBgColor: "bg-purple", Icon: FileHtml }; case "csv": case "xlsx": return { iconBgColor: "bg-success", Icon: FileCsv }; case "json": case "sql": case "js": case "jsx": case "cpp": case "c": return { iconBgColor: "bg-warn", Icon: FileCode }; case "png": case "jpg": case "jpeg": return { iconBgColor: "bg-royalblue", Icon: FileImage }; default: return { iconBgColor: "bg-royalblue", Icon: FileText }; } }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/StopGenerationButton/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/StopGenerationButton/index.jsx
import { ABORT_STREAM_EVENT } from "@/utils/chat"; import { Tooltip } from "react-tooltip"; export default function StopGenerationButton() { function emitHaltEvent() { window.dispatchEvent(new CustomEvent(ABORT_STREAM_EVENT)); } return ( <> <button type="button" onClick={emitHaltEvent} data-tooltip-id="stop-generation-button" data-tooltip-content="Stop generating response" className="border-none text-white/60 cursor-pointer group -mr-1.5 mt-1.5" aria-label="Stop generating" > <svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ transform: "scale(1.3)" }} className="opacity-60 group-hover:opacity-100 light:opacity-100 light:group-hover:opacity-60" > <circle cx="10" cy="10.562" r="9" strokeWidth="2" className="group-hover:stroke-primary-button stroke-white light:stroke-theme-text-secondary" /> <rect x="6.3999" y="6.96204" width="7.2" height="7.2" rx="2" className="group-hover:fill-primary-button fill-white light:fill-theme-text-secondary" /> </svg> </button> <Tooltip id="stop-generation-button" place="bottom" delayShow={300} className="tooltip !text-xs z-99 -ml-1" /> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/TextSizeMenu/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/TextSizeMenu/index.jsx
import { useState, useRef } from "react"; import { TextT } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; import { useTranslation } from "react-i18next"; import { useTheme } from "@/hooks/useTheme"; export default function TextSizeButton() { const tooltipRef = useRef(null); const { t } = useTranslation(); const { theme } = useTheme(); const toggleTooltip = () => { if (!tooltipRef.current) return; tooltipRef.current.isOpen ? tooltipRef.current.close() : tooltipRef.current.open(); }; return ( <> <div id="text-size-btn" data-tooltip-id="tooltip-text-size-btn" aria-label={t("chat_window.text_size")} onClick={toggleTooltip} className="border-none flex justify-center items-center opacity-60 hover:opacity-100 light:opacity-100 light:hover:opacity-60 cursor-pointer" > <TextT color="var(--theme-sidebar-footer-icon-fill)" weight="fill" className="w-[22px] h-[22px] pointer-events-none text-white" /> </div> <Tooltip ref={tooltipRef} id="tooltip-text-size-btn" place="top" opacity={1} clickable={true} delayShow={300} delayHide={800} arrowColor={ theme === "light" ? "var(--theme-modal-border)" : "var(--theme-bg-primary)" } className="z-99 !w-[140px] !bg-theme-bg-primary !px-[5px] !rounded-lg !pointer-events-auto light:border-2 light:border-theme-modal-border" > <TextSizeMenu tooltipRef={tooltipRef} /> </Tooltip> </> ); } function TextSizeMenu({ tooltipRef }) { const { t } = useTranslation(); const [selectedSize, setSelectedSize] = useState( window.localStorage.getItem("anythingllm_text_size") || "normal" ); const handleTextSizeChange = (size) => { setSelectedSize(size); window.localStorage.setItem("anythingllm_text_size", size); window.dispatchEvent(new CustomEvent("textSizeChange", { detail: size })); tooltipRef.current?.close(); }; return ( <div className="flex flex-col justify-start items-stretch gap-1 p-2"> <button onClick={(e) => { e.preventDefault(); handleTextSizeChange("small"); }} className={`border-none w-full hover:cursor-pointer px-2 py-2 rounded-md flex items-center group ${ selectedSize === "small" ? "bg-theme-action-menu-item-hover" : "hover:bg-theme-action-menu-item-hover" }`} > <div className="text-theme-text-primary text-xs"> {t("chat_window.small")} </div> </button> <button onClick={(e) => { e.preventDefault(); handleTextSizeChange("normal"); }} className={`border-none w-full hover:cursor-pointer px-2 py-2 rounded-md flex items-center group ${ selectedSize === "normal" ? "bg-theme-action-menu-item-hover" : "hover:bg-theme-action-menu-item-hover" }`} > <div className="text-theme-text-primary text-sm"> {t("chat_window.normal")} </div> </button> <button onClick={(e) => { e.preventDefault(); handleTextSizeChange("large"); }} className={`border-none w-full hover:cursor-pointer px-2 py-2 rounded-md flex items-center group ${ selectedSize === "large" ? "bg-theme-action-menu-item-hover" : "hover:bg-theme-action-menu-item-hover" }`} > <div className="text-theme-text-primary text-[16px]"> {t("chat_window.large")} </div> </button> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/index.jsx
import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import PreLoader from "@/components/Preloader"; import ChatModelSelection from "./ChatModelSelection"; import { useTranslation } from "react-i18next"; import { PROVIDER_SETUP_EVENT, SAVE_LLM_SELECTOR_EVENT } from "./action"; import { WORKSPACE_LLM_PROVIDERS, autoScrollToSelectedLLMProvider, hasMissingCredentials, validatedModelSelection, } from "./utils"; import LLMSelectorSidePanel from "./LLMSelector"; import { NoSetupWarning } from "./SetupProvider"; import showToast from "@/utils/toast"; import Workspace from "@/models/workspace"; import System from "@/models/system"; export default function LLMSelectorModal() { const { slug } = useParams(); const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [settings, setSettings] = useState(null); const [selectedLLMProvider, setSelectedLLMProvider] = useState(null); const [selectedLLMModel, setSelectedLLMModel] = useState(""); const [availableProviders, setAvailableProviders] = useState( WORKSPACE_LLM_PROVIDERS ); const [hasChanges, setHasChanges] = useState(false); const [saving, setSaving] = useState(false); const [missingCredentials, setMissingCredentials] = useState(false); useEffect(() => { if (!slug) return; setLoading(true); Promise.all([Workspace.bySlug(slug), System.keys()]) .then(([workspace, systemSettings]) => { const selectedLLMProvider = workspace.chatProvider ?? systemSettings.LLMProvider; const selectedLLMModel = workspace.chatModel ?? systemSettings.LLMModel; setSettings(systemSettings); setSelectedLLMProvider(selectedLLMProvider); autoScrollToSelectedLLMProvider(selectedLLMProvider); setSelectedLLMModel(selectedLLMModel); }) .finally(() => setLoading(false)); }, [slug]); function handleSearch(e) { const searchTerm = e.target.value.toLowerCase(); const filteredProviders = WORKSPACE_LLM_PROVIDERS.filter((provider) => provider.name.toLowerCase().includes(searchTerm) ); setAvailableProviders(filteredProviders); } function handleProviderSelection(provider) { setSelectedLLMProvider(provider); setAvailableProviders(WORKSPACE_LLM_PROVIDERS); autoScrollToSelectedLLMProvider(provider, 50); document.getElementById("llm-search-input").value = ""; setHasChanges(true); setMissingCredentials(hasMissingCredentials(settings, provider)); } async function handleSave() { setSaving(true); try { setHasChanges(false); const validatedModel = validatedModelSelection(selectedLLMModel); if (!validatedModel) throw new Error("Invalid model selection"); const { message } = await Workspace.update(slug, { chatProvider: selectedLLMProvider, chatModel: validatedModel, }); if (!!message) throw new Error(message); window.dispatchEvent(new Event(SAVE_LLM_SELECTOR_EVENT)); } catch (error) { console.error(error); showToast(error.message, "error", { clear: true }); } finally { setSaving(false); } } if (loading) { return ( <div id="llm-selector-modal" className="w-full h-[500px] p-0 overflow-y-scroll flex flex-col items-center justify-center" > <PreLoader size={12} /> <p className="text-theme-text-secondary text-sm mt-2"> {t("chat_window.workspace_llm_manager.loading_workspace_settings")} </p> </div> ); } return ( <div id="llm-selector-modal" className="w-full h-[500px] p-0 overflow-y-scroll flex" > <LLMSelectorSidePanel availableProviders={availableProviders} selectedLLMProvider={selectedLLMProvider} onSearchChange={handleSearch} onProviderClick={handleProviderSelection} /> <div className="w-[60%] h-full px-2 flex flex-col gap-y-2"> <NoSetupWarning showing={missingCredentials} onSetupClick={() => { window.dispatchEvent( new CustomEvent(PROVIDER_SETUP_EVENT, { detail: { provider: WORKSPACE_LLM_PROVIDERS.find( (p) => p.value === selectedLLMProvider ), settings, }, }) ); }} /> <ChatModelSelection provider={selectedLLMProvider} setHasChanges={setHasChanges} selectedLLMModel={selectedLLMModel} setSelectedLLMModel={setSelectedLLMModel} /> {hasChanges && ( <button type="button" disabled={saving} onClick={handleSave} className={`border-none text-xs px-4 py-1 font-semibold light:text-[#ffffff] rounded-lg bg-primary-button hover:bg-secondary hover:text-white h-[34px] whitespace-nowrap w-full`} > {saving ? t("chat_window.workspace_llm_manager.saving") : t("chat_window.workspace_llm_manager.save")} </button> )} </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/action.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/action.jsx
import { Tooltip } from "react-tooltip"; import { Brain, CheckCircle } from "@phosphor-icons/react"; import LLMSelectorModal from "./index"; import { useTheme } from "@/hooks/useTheme"; import { useRef, useEffect, useState } from "react"; import useUser from "@/hooks/useUser"; import { useModal } from "@/hooks/useModal"; import SetupProvider from "./SetupProvider"; export const TOGGLE_LLM_SELECTOR_EVENT = "toggle_llm_selector"; export const SAVE_LLM_SELECTOR_EVENT = "save_llm_selector"; export const PROVIDER_SETUP_EVENT = "provider_setup_requested"; export default function LLMSelectorAction() { const tooltipRef = useRef(null); const { theme } = useTheme(); const { user } = useUser(); const [saved, setSaved] = useState(false); const { isOpen: isSetupProviderOpen, openModal: openSetupProviderModal, closeModal: closeSetupProviderModal, } = useModal(); const [config, setConfig] = useState({ settings: {}, provider: null, }); function toggleLLMSelectorTooltip() { if (!tooltipRef.current) return; tooltipRef.current.isOpen ? tooltipRef.current.close() : tooltipRef.current.open(); } function handleSaveLLMSelector() { if (!tooltipRef.current) return; tooltipRef.current.close(); setSaved(true); } useEffect(() => { window.addEventListener( TOGGLE_LLM_SELECTOR_EVENT, toggleLLMSelectorTooltip ); window.addEventListener(SAVE_LLM_SELECTOR_EVENT, handleSaveLLMSelector); return () => { window.removeEventListener( TOGGLE_LLM_SELECTOR_EVENT, toggleLLMSelectorTooltip ); window.removeEventListener( SAVE_LLM_SELECTOR_EVENT, handleSaveLLMSelector ); }; }, []); useEffect(() => { if (!saved) return; setTimeout(() => { setSaved(false); }, 1500); }, [saved]); useEffect(() => { function handleProviderSetupEvent(e) { const { provider, settings } = e.detail; setConfig({ settings, provider, }); setTimeout(() => { openSetupProviderModal(); }, 300); } window.addEventListener(PROVIDER_SETUP_EVENT, handleProviderSetupEvent); return () => window.removeEventListener( PROVIDER_SETUP_EVENT, handleProviderSetupEvent ); }, []); // This feature is disabled for multi-user instances where the user is not an admin // This is because of the limitations of model selection currently and other nuances in controls. if (!!user && user.role !== "admin") return null; return ( <> <div id="llm-selector-btn" data-tooltip-id="tooltip-llm-selector-btn" aria-label="LLM Selector" className={`border-none relative flex justify-center items-center opacity-60 hover:opacity-100 light:opacity-100 light:hover:opacity-60 cursor-pointer`} > {saved ? ( <CheckCircle className="w-[22px] h-[22px] pointer-events-none text-green-400" /> ) : ( <Brain className="w-[22px] h-[22px] pointer-events-none text-[var(--theme-sidebar-footer-icon-fill)]" /> )} </div> <Tooltip ref={tooltipRef} id="tooltip-llm-selector-btn" place="top" opacity={1} clickable={true} delayShow={300} // dont trigger tooltip instantly to not spam the UI delayHide={800} // Prevent the travel time from icon to window hiding tooltip arrowColor={ theme === "light" ? "var(--theme-modal-border)" : "var(--theme-bg-primary)" } className="z-99 !w-[500px] !bg-theme-bg-primary !px-[5px] !rounded-lg !pointer-events-auto light:border-2 light:border-theme-modal-border" > <LLMSelectorModal tooltipRef={tooltipRef} /> </Tooltip> <SetupProvider isOpen={isSetupProviderOpen} closeModal={closeSetupProviderModal} postSubmit={() => closeSetupProviderModal()} settings={config.settings} llmProvider={config.provider} /> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/utils.js
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/utils.js
import { AVAILABLE_LLM_PROVIDERS } from "@/pages/GeneralSettings/LLMPreference"; import { DISABLED_PROVIDERS } from "@/hooks/useGetProvidersModels"; export function autoScrollToSelectedLLMProvider( selectedLLMProvider, timeout = 500 ) { setTimeout(() => { const selectedButton = document.querySelector( `[data-llm-value="${selectedLLMProvider}"]` ); if (!selectedButton) return; selectedButton.scrollIntoView({ behavior: "smooth", block: "nearest" }); }, timeout); } /** * Validates the model selection by checking if the model is in the select option in the available models * dropdown. If the model is not in the dropdown, it will return the first model in the dropdown. * * This exists when the user swaps providers, but did not select a model in the new provider's dropdown * and assumed the first model in the picker was OK. This prevents invalid provider<>model selection issues * @param {string} model - The model to validate * @returns {string} - The validated model */ export function validatedModelSelection(model) { try { // If the entire select element is not found, return the model as is and cross our fingers const selectOption = document.getElementById(`workspace-llm-model-select`); if (!selectOption) return model; // If the model is not in the dropdown, return the first model in the dropdown // to prevent invalid provider<>model selection issues const selectedOption = selectOption.querySelector( `option[value="${model}"]` ); if (!selectedOption) return selectOption.querySelector(`option`).value; // If the model is in the dropdown, return the model as is return model; } catch (error) { return null; // If the dropdown was empty or something else went wrong, return null to abort the save } } export function hasMissingCredentials(settings, provider) { const providerEntry = AVAILABLE_LLM_PROVIDERS.find( (p) => p.value === provider ); if (!providerEntry) return false; for (const requiredKey of providerEntry.requiredConfig) { if (!settings.hasOwnProperty(requiredKey)) return true; if (!settings[requiredKey]) return true; } return false; } export const WORKSPACE_LLM_PROVIDERS = AVAILABLE_LLM_PROVIDERS.filter( (provider) => !DISABLED_PROVIDERS.includes(provider.value) );
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/SetupProvider/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/SetupProvider/index.jsx
import { createPortal } from "react-dom"; import ModalWrapper from "@/components/ModalWrapper"; import { X } from "@phosphor-icons/react"; import System from "@/models/system"; import showToast from "@/utils/toast"; import { useTranslation } from "react-i18next"; export default function SetupProvider({ isOpen, closeModal, postSubmit, settings, llmProvider, }) { if (!isOpen) return null; async function handleUpdate(e) { e.preventDefault(); e.stopPropagation(); const data = {}; const form = new FormData(e.target); for (var [key, value] of form.entries()) data[key] = value; const { error } = await System.updateSystem(data); if (error) { showToast( `Failed to save ${llmProvider.name} settings: ${error}`, "error" ); return; } closeModal(); postSubmit(); return false; } return createPortal( <ModalWrapper isOpen={isOpen}> <div className="fixed inset-0 z-50 overflow-auto bg-black bg-opacity-50 flex items-center justify-center"> <div className="relative w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> {llmProvider.name} Settings </h3> </div> <button onClick={closeModal} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={24} weight="bold" className="text-white" /> </button> </div> <form id="provider-form" onSubmit={handleUpdate}> <div className="px-7 py-6"> <div className="space-y-6 max-h-[60vh] overflow-y-auto p-1"> <p className="text-sm text-white/60"> To use {llmProvider.name} as this workspace's LLM you need to set it up first. </p> <div> {llmProvider.options(settings, { credentialsOnly: true })} </div> </div> </div> <div className="flex justify-between items-center mt-6 pt-6 border-t border-theme-modal-border px-7 pb-6"> <button type="button" onClick={closeModal} className="transition-all duration-300 text-white hover:bg-zinc-700 px-4 py-2 rounded-lg text-sm" > Cancel </button> <button type="submit" form="provider-form" className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > Save settings </button> </div> </form> </div> </div> </ModalWrapper>, document.body ); } export function NoSetupWarning({ showing, onSetupClick }) { const { t } = useTranslation(); if (!showing) return null; return ( <button type="button" onClick={onSetupClick} className="border border-blue-500 rounded-lg p-2 flex flex-col items-center gap-y-2 bg-blue-600/10 text-blue-600 hover:bg-blue-600/20 transition-all duration-300" > <p className="text-sm text-center"> <b>{t("chat_window.workspace_llm_manager.missing_credentials")}</b> </p> <p className="text-xs text-center"> {t("chat_window.workspace_llm_manager.missing_credentials_description")} </p> </button> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/ChatModelSelection/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/ChatModelSelection/index.jsx
import useGetProviderModels, { DISABLED_PROVIDERS, } from "@/hooks/useGetProvidersModels"; import { useTranslation } from "react-i18next"; export default function ChatModelSelection({ provider, setHasChanges, selectedLLMModel, setSelectedLLMModel, }) { const { defaultModels, customModels, loading } = useGetProviderModels(provider); const { t } = useTranslation(); if (DISABLED_PROVIDERS.includes(provider)) return null; if (loading) { return ( <div> <div className="flex flex-col"> <label htmlFor="name" className="block input-label"> {t("chat_window.workspace_llm_manager.available_models", { provider, })} </label> <p className="text-white text-opacity-60 text-xs font-medium py-1.5"> {t( "chat_window.workspace_llm_manager.available_models_description" )} </p> </div> <select required={true} disabled={true} className="border-theme-modal-border border border-solid bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" > <option disabled={true} selected={true}> -- waiting for models -- </option> </select> </div> ); } return ( <div> <div className="flex flex-col"> <label htmlFor="name" className="block input-label"> {t("chat_window.workspace_llm_manager.available_models", { provider, })} </label> <p className="text-white text-opacity-60 text-xs font-medium py-1.5"> {t("chat_window.workspace_llm_manager.available_models_description")} </p> </div> <select id="workspace-llm-model-select" required={true} value={selectedLLMModel} onChange={(e) => { setHasChanges(true); setSelectedLLMModel(e.target.value); }} className="border-theme-modal-border border border-solid bg-theme-settings-input-bg text-white text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" > {defaultModels.length > 0 && ( <optgroup label="General models"> {defaultModels.map((model) => { return ( <option key={model} value={model} selected={selectedLLMModel === model} > {model} </option> ); })} </optgroup> )} {Array.isArray(customModels) && customModels.length > 0 && ( <optgroup label="Discovered models"> {customModels.map((model) => { return ( <option key={model.id} value={model.id} selected={selectedLLMModel === model.id} > {model.id} </option> ); })} </optgroup> )} {/* For providers like TogetherAi where we partition model by creator entity. */} {!Array.isArray(customModels) && Object.keys(customModels).length > 0 && ( <> {Object.entries(customModels).map(([organization, models]) => ( <optgroup key={organization} label={organization}> {models.map((model) => ( <option key={model.id} value={model.id} selected={selectedLLMModel === model.id} > {model.name} </option> ))} </optgroup> ))} </> )} </select> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/LLMSelector/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/LLMSelector/index.jsx
import { useTranslation } from "react-i18next"; export default function LLMSelectorSidePanel({ availableProviders, selectedLLMProvider, onSearchChange, onProviderClick, }) { const { t } = useTranslation(); return ( <div className="w-[40%] h-full flex flex-col gap-y-1 border-r-2 border-theme-modal-border py-2 px-[5px]"> <input id="llm-search-input" type="search" placeholder={t("chat_window.workspace_llm_manager.search")} onChange={onSearchChange} className="search-input bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder outline-none text-sm rounded-lg px-2 py-2 w-full h-[32px] border-theme-modal-border border border-solid" /> <div className="flex flex-col gap-y-2 overflow-y-scroll "> {availableProviders.map((llm) => ( <button key={llm.value} type="button" data-llm-value={llm.value} className={`border-none hover:cursor-pointer hover:bg-theme-checklist-item-bg-hover flex gap-x-2 items-center p-2 rounded-md ${selectedLLMProvider === llm.value ? "bg-theme-checklist-item-bg" : ""}`} onClick={() => onProviderClick(llm.value)} > <img src={llm.logo} alt={`${llm.name} logo`} className="w-6 h-6 rounded-md" /> <div className="flex flex-col"> <div className="text-xs text-theme-text-primary">{llm.name}</div> </div> </button> ))} </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SpeechToText/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/SpeechToText/index.jsx
import { useEffect, useCallback, useRef } from "react"; import { Microphone } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; import _regeneratorRuntime from "regenerator-runtime"; import SpeechRecognition, { useSpeechRecognition, } from "react-speech-recognition"; import { PROMPT_INPUT_EVENT } from "../../PromptInput"; import { useTranslation } from "react-i18next"; import Appearance from "@/models/appearance"; let timeout; const SILENCE_INTERVAL = 3_200; // wait in seconds of silence before closing. /** * Speech-to-text input component for the chat window. * @param {Object} props - The component props * @param {(textToAppend: string, autoSubmit: boolean) => void} props.sendCommand - The function to send the command * @returns {React.ReactElement} The SpeechToText component */ export default function SpeechToText({ sendCommand }) { const previousTranscriptRef = useRef(""); const { transcript, listening, resetTranscript, browserSupportsSpeechRecognition, browserSupportsContinuousListening, isMicrophoneAvailable, } = useSpeechRecognition({ clearTranscriptOnListen: true, }); const { t } = useTranslation(); function startSTTSession() { if (!isMicrophoneAvailable) { alert( "AnythingLLM does not have access to microphone. Please enable for this site to use this feature." ); return; } resetTranscript(); previousTranscriptRef.current = ""; SpeechRecognition.startListening({ continuous: browserSupportsContinuousListening, language: window?.navigator?.language ?? "en-US", }); } function endSTTSession() { SpeechRecognition.stopListening(); // If auto submit is enabled, send an empty string to the chat window to submit the current transcript // since every chunk of text should have been streamed to the chat window by now. if (Appearance.get("autoSubmitSttInput")) { sendCommand({ text: "", autoSubmit: true, writeMode: "append", }); } resetTranscript(); previousTranscriptRef.current = ""; clearTimeout(timeout); } const handleKeyPress = useCallback( (event) => { // CTRL + m on Mac and Windows to toggle STT listening if (event.ctrlKey && event.keyCode === 77) { if (listening) { endSTTSession(); } else { startSTTSession(); } } }, [listening, endSTTSession, startSTTSession] ); function handlePromptUpdate(e) { if (!e?.detail && timeout) { endSTTSession(); clearTimeout(timeout); } } useEffect(() => { document.addEventListener("keydown", handleKeyPress); return () => { document.removeEventListener("keydown", handleKeyPress); }; }, [handleKeyPress]); useEffect(() => { if (!!window) window.addEventListener(PROMPT_INPUT_EVENT, handlePromptUpdate); return () => window?.removeEventListener(PROMPT_INPUT_EVENT, handlePromptUpdate); }, []); useEffect(() => { if (transcript?.length > 0 && listening) { const previousTranscript = previousTranscriptRef.current; const newContent = transcript.slice(previousTranscript.length); // Stream just the diff of the new content since transcript is an accumulating string. // and not just the new content transcribed. if (newContent.length > 0) sendCommand({ text: newContent, writeMode: "append" }); previousTranscriptRef.current = transcript; clearTimeout(timeout); timeout = setTimeout(() => { endSTTSession(); }, SILENCE_INTERVAL); } }, [transcript, listening]); if (!browserSupportsSpeechRecognition) return null; return ( <div data-tooltip-id="tooltip-microphone-btn" data-tooltip-content={`${t("chat_window.microphone")} (CTRL + M)`} aria-label={t("chat_window.microphone")} onClick={listening ? endSTTSession : startSTTSession} className={`border-none relative flex justify-center items-center opacity-60 hover:opacity-100 light:opacity-100 light:hover:opacity-60 cursor-pointer ${ !!listening ? "!opacity-100" : "" }`} > <Microphone weight="fill" color="var(--theme-sidebar-footer-icon-fill)" className={`w-[22px] h-[22px] pointer-events-none text-theme-text-primary ${ listening ? "animate-pulse-glow" : "" }`} /> <Tooltip id="tooltip-microphone-btn" place="top" delayShow={300} className="tooltip !text-xs z-99" /> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/index.jsx
import { useEffect, useRef, useState, useMemo, useCallback } from "react"; import HistoricalMessage from "./HistoricalMessage"; import PromptReply from "./PromptReply"; import StatusResponse from "./StatusResponse"; import { useManageWorkspaceModal } from "../../../Modals/ManageWorkspace"; import ManageWorkspace from "../../../Modals/ManageWorkspace"; import { ArrowDown } from "@phosphor-icons/react"; import debounce from "lodash.debounce"; import useUser from "@/hooks/useUser"; import Chartable from "./Chartable"; import Workspace from "@/models/workspace"; import { useParams } from "react-router-dom"; import paths from "@/utils/paths"; import Appearance from "@/models/appearance"; import useTextSize from "@/hooks/useTextSize"; import { v4 } from "uuid"; import { useTranslation } from "react-i18next"; import { useChatMessageAlignment } from "@/hooks/useChatMessageAlignment"; export default function ChatHistory({ history = [], workspace, sendCommand, updateHistory, regenerateAssistantMessage, hasAttachments = false, }) { const { t } = useTranslation(); const lastScrollTopRef = useRef(0); const { user } = useUser(); const { threadSlug = null } = useParams(); const { showing, showModal, hideModal } = useManageWorkspaceModal(); const [isAtBottom, setIsAtBottom] = useState(true); const chatHistoryRef = useRef(null); const [isUserScrolling, setIsUserScrolling] = useState(false); const isStreaming = history[history.length - 1]?.animate; const { showScrollbar } = Appearance.getSettings(); const { textSizeClass } = useTextSize(); const { getMessageAlignment } = useChatMessageAlignment(); useEffect(() => { if (!isUserScrolling && (isAtBottom || isStreaming)) { scrollToBottom(false); // Use instant scroll for auto-scrolling } }, [history, isAtBottom, isStreaming, isUserScrolling]); const handleScroll = (e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; const isBottom = scrollHeight - scrollTop === clientHeight; // Detect if this is a user-initiated scroll if (Math.abs(scrollTop - lastScrollTopRef.current) > 10) { setIsUserScrolling(!isBottom); } setIsAtBottom(isBottom); lastScrollTopRef.current = scrollTop; }; const debouncedScroll = debounce(handleScroll, 100); useEffect(() => { const chatHistoryElement = chatHistoryRef.current; if (chatHistoryElement) { chatHistoryElement.addEventListener("scroll", debouncedScroll); return () => chatHistoryElement.removeEventListener("scroll", debouncedScroll); } }, []); const scrollToBottom = (smooth = false) => { if (chatHistoryRef.current) { chatHistoryRef.current.scrollTo({ top: chatHistoryRef.current.scrollHeight, // Smooth is on when user clicks the button but disabled during auto scroll // We must disable this during auto scroll because it causes issues with // detecting when we are at the bottom of the chat. ...(smooth ? { behavior: "smooth" } : {}), }); } }; const handleSendSuggestedMessage = (heading, message) => { sendCommand({ text: `${heading} ${message}`, autoSubmit: true }); }; const saveEditedMessage = async ({ editedMessage, chatId, role, attachments = [], }) => { if (!editedMessage) return; // Don't save empty edits. // if the edit was a user message, we will auto-regenerate the response and delete all // messages post modified message if (role === "user") { // remove all messages after the edited message // technically there are two chatIds per-message pair, this will split the first. const updatedHistory = history.slice( 0, history.findIndex((msg) => msg.chatId === chatId) + 1 ); // update last message in history to edited message updatedHistory[updatedHistory.length - 1].content = editedMessage; // remove all edited messages after the edited message in backend await Workspace.deleteEditedChats(workspace.slug, threadSlug, chatId); sendCommand({ text: editedMessage, autoSubmit: true, history: updatedHistory, attachments, }); return; } // If role is an assistant we simply want to update the comment and save on the backend as an edit. if (role === "assistant") { const updatedHistory = [...history]; const targetIdx = history.findIndex( (msg) => msg.chatId === chatId && msg.role === role ); if (targetIdx < 0) return; updatedHistory[targetIdx].content = editedMessage; updateHistory(updatedHistory); await Workspace.updateChatResponse( workspace.slug, threadSlug, chatId, editedMessage ); return; } }; const forkThread = async (chatId) => { const newThreadSlug = await Workspace.forkThread( workspace.slug, threadSlug, chatId ); window.location.href = paths.workspace.thread( workspace.slug, newThreadSlug ); }; const compiledHistory = useMemo( () => buildMessages({ workspace, history, regenerateAssistantMessage, saveEditedMessage, forkThread, getMessageAlignment, }), [ workspace, history, regenerateAssistantMessage, saveEditedMessage, forkThread, ] ); const lastMessageInfo = useMemo(() => getLastMessageInfo(history), [history]); const renderStatusResponse = useCallback( (item, index) => { const hasSubsequentMessages = index < compiledHistory.length - 1; return ( <StatusResponse key={`status-group-${index}`} messages={item} isThinking={!hasSubsequentMessages && lastMessageInfo.isAnimating} /> ); }, [compiledHistory.length, lastMessageInfo] ); if (history.length === 0 && !hasAttachments) { return ( <div className="flex flex-col h-full md:mt-0 pb-44 md:pb-40 w-full justify-end items-center"> <div className="flex flex-col items-center md:items-start md:max-w-[600px] w-full px-4"> <p className="text-white/60 text-lg font-base py-4"> {t("chat_window.welcome")} </p> {!user || user.role !== "default" ? ( <p className="w-full items-center text-white/60 text-lg font-base flex flex-col md:flex-row gap-x-1"> {t("chat_window.get_started")} <span className="underline font-medium cursor-pointer" onClick={showModal} > {t("chat_window.upload")} </span> {t("chat_window.or")}{" "} <b className="font-medium italic">{t("chat_window.send_chat")}</b> </p> ) : ( <p className="w-full items-center text-white/60 text-lg font-base flex flex-col md:flex-row gap-x-1"> {t("chat_window.get_started_default")}{" "} <b className="font-medium italic">{t("chat_window.send_chat")}</b> </p> )} <WorkspaceChatSuggestions suggestions={workspace?.suggestedMessages ?? []} sendSuggestion={handleSendSuggestedMessage} /> </div> {showing && ( <ManageWorkspace hideModal={hideModal} providedSlug={workspace.slug} /> )} </div> ); } return ( <div className={`markdown text-white/80 light:text-theme-text-primary font-light ${textSizeClass} h-full md:h-[83%] pb-[100px] pt-6 md:pt-0 md:pb-20 md:mx-0 overflow-y-scroll flex flex-col justify-start ${showScrollbar ? "show-scrollbar" : "no-scroll"}`} id="chat-history" ref={chatHistoryRef} onScroll={handleScroll} > {compiledHistory.map((item, index) => Array.isArray(item) ? renderStatusResponse(item, index) : item )} {showing && ( <ManageWorkspace hideModal={hideModal} providedSlug={workspace.slug} /> )} {!isAtBottom && ( <div className="fixed bottom-40 right-10 md:right-20 z-50 cursor-pointer animate-pulse"> <div className="flex flex-col items-center"> <div className="p-1 rounded-full border border-white/10 bg-white/10 hover:bg-white/20 hover:text-white" onClick={() => { scrollToBottom(true); setIsUserScrolling(false); }} > <ArrowDown weight="bold" className="text-white/60 w-5 h-5" /> </div> </div> </div> )} </div> ); } const getLastMessageInfo = (history) => { const lastMessage = history?.[history.length - 1] || {}; return { isAnimating: lastMessage?.animate, isStatusResponse: lastMessage?.type === "statusResponse", }; }; function WorkspaceChatSuggestions({ suggestions = [], sendSuggestion }) { if (suggestions.length === 0) return null; return ( <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-theme-text-primary text-xs mt-10 w-full justify-center"> {suggestions.map((suggestion, index) => ( <button key={index} className="text-left p-2.5 rounded-xl bg-theme-sidebar-footer-icon hover:bg-theme-sidebar-footer-icon-hover border border-theme-border" onClick={() => sendSuggestion(suggestion.heading, suggestion.message)} > <p className="font-semibold">{suggestion.heading}</p> <p>{suggestion.message}</p> </button> ))} </div> ); } /** * Builds the history of messages for the chat. * This is mostly useful for rendering the history in a way that is easy to understand. * as well as compensating for agent thinking and other messages that are not part of the history, but * are still part of the chat. * * @param {Object} param0 - The parameters for building the messages. * @param {Array} param0.history - The history of messages. * @param {Object} param0.workspace - The workspace object. * @param {Function} param0.regenerateAssistantMessage - The function to regenerate the assistant message. * @param {Function} param0.saveEditedMessage - The function to save the edited message. * @param {Function} param0.forkThread - The function to fork the thread. * @param {Function} param0.getMessageAlignment - The function to get the alignment of the message (returns class). * @returns {Array} The compiled history of messages. */ function buildMessages({ history, workspace, regenerateAssistantMessage, saveEditedMessage, forkThread, getMessageAlignment, }) { return history.reduce((acc, props, index) => { const isLastBotReply = index === history.length - 1 && props.role === "assistant"; if (props?.type === "statusResponse" && !!props.content) { if (acc.length > 0 && Array.isArray(acc[acc.length - 1])) { acc[acc.length - 1].push(props); } else { acc.push([props]); } return acc; } if (props.type === "rechartVisualize" && !!props.content) { acc.push( <Chartable key={props.uuid} workspace={workspace} props={props} /> ); } else if (isLastBotReply && props.animate) { acc.push( <PromptReply key={props.uuid || v4()} uuid={props.uuid} reply={props.content} pending={props.pending} sources={props.sources} error={props.error} workspace={workspace} closed={props.closed} /> ); } else { acc.push( <HistoricalMessage key={index} message={props.content} role={props.role} workspace={workspace} sources={props.sources} feedbackScore={props.feedbackScore} chatId={props.chatId} error={props.error} attachments={props.attachments} regenerateMessage={regenerateAssistantMessage} isLastMessage={isLastBotReply} saveEditedMessage={saveEditedMessage} forkThread={forkThread} metrics={props.metrics} alignmentCls={getMessageAlignment?.(props.role)} /> ); } return acc; }, []); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/ThoughtContainer/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/ThoughtContainer/index.jsx
import { useState, forwardRef, useImperativeHandle } from "react"; import renderMarkdown from "@/utils/chat/markdown"; import { CaretDown } from "@phosphor-icons/react"; import DOMPurify from "dompurify"; import { isMobile } from "react-device-detect"; import ThinkingAnimation from "@/media/animations/thinking-animation.webm"; import ThinkingStatic from "@/media/animations/thinking-static.png"; const THOUGHT_KEYWORDS = ["thought", "thinking", "think", "thought_chain"]; const CLOSING_TAGS = [...THOUGHT_KEYWORDS, "response", "answer"]; export const THOUGHT_REGEX_OPEN = new RegExp( THOUGHT_KEYWORDS.map((keyword) => `<${keyword}\\s*(?:[^>]*?)?\\s*>`).join("|") ); export const THOUGHT_REGEX_CLOSE = new RegExp( CLOSING_TAGS.map((keyword) => `</${keyword}\\s*(?:[^>]*?)?>`).join("|") ); export const THOUGHT_REGEX_COMPLETE = new RegExp( THOUGHT_KEYWORDS.map( (keyword) => `<${keyword}\\s*(?:[^>]*?)?\\s*>[\\s\\S]*?<\\/${keyword}\\s*(?:[^>]*?)?>` ).join("|") ); const THOUGHT_PREVIEW_LENGTH = isMobile ? 25 : 50; /** * Checks if the content has readable content. * @param {string} content - The content to check. * @returns {boolean} - Whether the content has readable content. */ function contentIsNotEmpty(content = "") { return ( content ?.trim() ?.replace(THOUGHT_REGEX_OPEN, "") ?.replace(THOUGHT_REGEX_CLOSE, "") ?.replace(/[\n\s]/g, "")?.length > 0 ); } /** * Component to render a thought chain. * @param {string} content - The content of the thought chain. * @param {boolean} expanded - Whether the thought chain is expanded. * @returns {JSX.Element} */ export const ThoughtChainComponent = forwardRef( ({ content: initialContent, expanded }, ref) => { const [content, setContent] = useState(initialContent); const [hasReadableContent, setHasReadableContent] = useState( contentIsNotEmpty(initialContent) ); const [isExpanded, setIsExpanded] = useState(expanded); useImperativeHandle(ref, () => ({ updateContent: (newContent) => { setContent(newContent); setHasReadableContent(contentIsNotEmpty(newContent)); }, })); const isThinking = content.match(THOUGHT_REGEX_OPEN) && !content.match(THOUGHT_REGEX_CLOSE); const isComplete = content.match(THOUGHT_REGEX_COMPLETE) || content.match(THOUGHT_REGEX_CLOSE); const tagStrippedContent = content .replace(THOUGHT_REGEX_OPEN, "") .replace(THOUGHT_REGEX_CLOSE, ""); const autoExpand = isThinking && tagStrippedContent.length > THOUGHT_PREVIEW_LENGTH; const canExpand = tagStrippedContent.length > THOUGHT_PREVIEW_LENGTH; if (!content || !content.length || !hasReadableContent) return null; function handleExpandClick() { if (!canExpand) return; setIsExpanded(!isExpanded); } return ( <div className="flex justify-start items-end transition-all duration-200 w-full md:max-w-[800px]"> <div className="pb-2 w-full flex gap-x-5 flex-col relative"> <div style={{ transition: "all 0.1s ease-in-out", borderRadius: "6px", }} className={`${isExpanded || autoExpand ? "" : `${canExpand ? "hover:bg-theme-sidebar-item-hover" : ""}`} items-start bg-theme-bg-chat-input py-2 px-4 flex gap-x-2`} > <div className={`w-7 h-7 flex justify-center flex-shrink-0 ${!isExpanded && !autoExpand ? "items-center" : "items-start pt-[2px]"}`} > {isThinking || isComplete ? ( <> <video autoPlay loop muted playsInline className={`w-7 h-7 transition-opacity duration-200 light:invert light:opacity-50 ${isThinking ? "opacity-100" : "opacity-0 hidden"}`} data-tooltip-id="cot-thinking" data-tooltip-content="Model is thinking..." aria-label="Model is thinking..." > <source src={ThinkingAnimation} type="video/webm" /> </video> <img src={ThinkingStatic} alt="Thinking complete" className={`w-6 h-6 transition-opacity duration-200 light:invert light:opacity-50 ${!isThinking && isComplete ? "opacity-100" : "opacity-0 hidden"}`} data-tooltip-id="cot-thinking" data-tooltip-content="Model has finished thinking" aria-label="Model has finished thinking" /> </> ) : null} </div> <div className="flex-1 min-w-0"> <div className={`overflow-hidden transition-all transform duration-300 ease-in-out origin-top ${isExpanded || autoExpand ? "" : "max-h-6"}`} > <div className={`text-theme-text-secondary font-mono leading-6 ${isExpanded || autoExpand ? "-ml-[5.5px] -mt-[4px]" : "mt-[2px]"}`} > <span className={`block w-full ${!isExpanded && !autoExpand ? "truncate" : ""}`} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize( isExpanded || autoExpand ? renderMarkdown(tagStrippedContent) : tagStrippedContent ), }} /> </div> </div> </div> <div className="flex items-center gap-x-2"> {!autoExpand && canExpand ? ( <button onClick={handleExpandClick} data-tooltip-id="expand-cot" data-tooltip-content={ isExpanded ? "Hide thought chain" : "Show thought chain" } className="border-none text-theme-text-secondary hover:text-theme-text-primary transition-colors p-1 rounded-full hover:bg-theme-sidebar-item-hover" aria-label={ isExpanded ? "Hide thought chain" : "Show thought chain" } > <CaretDown className={`w-4 h-4 transform transition-transform duration-200 ${isExpanded ? "rotate-180" : ""}`} /> </button> ) : null} </div> </div> </div> </div> ); } ); ThoughtChainComponent.displayName = "ThoughtChainComponent";
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/PromptReply/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/PromptReply/index.jsx
import { memo, useRef, useEffect } from "react"; import { Warning } from "@phosphor-icons/react"; import UserIcon from "../../../../UserIcon"; import renderMarkdown from "@/utils/chat/markdown"; import Citations from "../Citation"; import { THOUGHT_REGEX_CLOSE, THOUGHT_REGEX_COMPLETE, THOUGHT_REGEX_OPEN, ThoughtChainComponent, } from "../ThoughtContainer"; const PromptReply = ({ uuid, reply, pending, error, workspace, sources = [], closed = true, }) => { const assistantBackgroundColor = "bg-theme-bg-chat"; if (!reply && sources.length === 0 && !pending && !error) return null; if (pending) { return ( <div className={`flex justify-center items-end w-full ${assistantBackgroundColor}`} > <div className="py-6 px-4 w-full flex gap-x-5 md:max-w-[80%] flex-col"> <div className="flex gap-x-5"> <WorkspaceProfileImage workspace={workspace} /> <div className="mt-3 ml-5 dot-falling light:invert"></div> </div> </div> </div> ); } if (error) { return ( <div className={`flex justify-center items-end w-full ${assistantBackgroundColor}`} > <div className="py-6 px-4 w-full flex gap-x-5 md:max-w-[80%] flex-col"> <div className="flex gap-x-5"> <WorkspaceProfileImage workspace={workspace} /> <span className={`inline-block p-2 rounded-lg bg-red-50 text-red-500`} > <Warning className="h-4 w-4 mb-1 inline-block" /> Could not respond to message. <span className="text-xs">Reason: {error || "unknown"}</span> </span> </div> </div> </div> ); } return ( <div key={uuid} className={`flex justify-center items-end w-full ${assistantBackgroundColor}`} > <div className="py-8 px-4 w-full flex gap-x-5 md:max-w-[80%] flex-col"> <div className="flex gap-x-5"> <WorkspaceProfileImage workspace={workspace} /> <RenderAssistantChatContent key={`${uuid}-prompt-reply-content`} message={reply} /> </div> <Citations sources={sources} /> </div> </div> ); }; export function WorkspaceProfileImage({ workspace }) { if (!!workspace.pfpUrl) { return ( <div className="relative w-[35px] h-[35px] rounded-full flex-shrink-0 overflow-hidden"> <img src={workspace.pfpUrl} alt="Workspace profile picture" className="absolute top-0 left-0 w-full h-full object-cover rounded-full bg-white" /> </div> ); } return <UserIcon user={{ uid: workspace.slug }} role="assistant" />; } function RenderAssistantChatContent({ message }) { const contentRef = useRef(""); const thoughtChainRef = useRef(null); useEffect(() => { const thinking = message.match(THOUGHT_REGEX_OPEN) && !message.match(THOUGHT_REGEX_CLOSE); if (thinking && thoughtChainRef.current) { thoughtChainRef.current.updateContent(message); return; } const completeThoughtChain = message.match(THOUGHT_REGEX_COMPLETE)?.[0]; const msgToRender = message.replace(THOUGHT_REGEX_COMPLETE, ""); if (completeThoughtChain && thoughtChainRef.current) { thoughtChainRef.current.updateContent(completeThoughtChain); } contentRef.current = msgToRender; }, [message]); const thinking = message.match(THOUGHT_REGEX_OPEN) && !message.match(THOUGHT_REGEX_CLOSE); if (thinking) return ( <ThoughtChainComponent ref={thoughtChainRef} content="" expanded={true} /> ); return ( <div className="flex flex-col gap-y-1"> {message.match(THOUGHT_REGEX_COMPLETE) && ( <ThoughtChainComponent ref={thoughtChainRef} content="" expanded={true} /> )} <span className="break-words" dangerouslySetInnerHTML={{ __html: renderMarkdown(contentRef.current) }} /> </div> ); } export default memo(PromptReply);
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/index.jsx
import React, { memo } from "react"; import { Info, Warning } from "@phosphor-icons/react"; import UserIcon from "../../../../UserIcon"; import Actions from "./Actions"; import renderMarkdown from "@/utils/chat/markdown"; import { userFromStorage } from "@/utils/request"; import Citations from "../Citation"; import { v4 } from "uuid"; import DOMPurify from "@/utils/chat/purify"; import { EditMessageForm, useEditMessage } from "./Actions/EditMessage"; import { useWatchDeleteMessage } from "./Actions/DeleteMessage"; import TTSMessage from "./Actions/TTSButton"; import { THOUGHT_REGEX_CLOSE, THOUGHT_REGEX_COMPLETE, THOUGHT_REGEX_OPEN, ThoughtChainComponent, } from "../ThoughtContainer"; import paths from "@/utils/paths"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import { chatQueryRefusalResponse } from "@/utils/chat"; const HistoricalMessage = ({ uuid = v4(), message, role, workspace, sources = [], attachments = [], error = false, feedbackScore = null, chatId = null, isLastMessage = false, regenerateMessage, saveEditedMessage, forkThread, metrics = {}, alignmentCls = "", }) => { const { t } = useTranslation(); const { isEditing } = useEditMessage({ chatId, role }); const { isDeleted, completeDelete, onEndAnimation } = useWatchDeleteMessage({ chatId, role, }); const adjustTextArea = (event) => { const element = event.target; element.style.height = "auto"; element.style.height = element.scrollHeight + "px"; }; const isRefusalMessage = role === "assistant" && message === chatQueryRefusalResponse(workspace); if (!!error) { return ( <div key={uuid} className={`flex justify-center items-end w-full bg-theme-bg-chat`} > <div className="py-8 px-4 w-full flex gap-x-5 md:max-w-[80%] flex-col"> <div className={`flex gap-x-5 ${alignmentCls}`}> <ProfileImage role={role} workspace={workspace} /> <div className="p-2 rounded-lg bg-red-50 text-red-500"> <span className="inline-block"> <Warning className="h-4 w-4 mb-1 inline-block" /> Could not respond to message. </span> <p className="text-xs font-mono mt-2 border-l-2 border-red-300 pl-2 bg-red-200 p-2 rounded-sm"> {error} </p> </div> </div> </div> </div> ); } if (completeDelete) return null; return ( <div key={uuid} onAnimationEnd={onEndAnimation} className={`${ isDeleted ? "animate-remove" : "" } flex justify-center items-end w-full group bg-theme-bg-chat`} > <div className="py-8 px-4 w-full flex gap-x-5 md:max-w-[80%] flex-col"> <div className={`flex gap-x-5 ${alignmentCls}`}> <div className="flex flex-col items-center"> <ProfileImage role={role} workspace={workspace} /> <div className="mt-1 -mb-10"> {role === "assistant" && ( <TTSMessage slug={workspace?.slug} chatId={chatId} message={message} /> )} </div> </div> {isEditing ? ( <EditMessageForm role={role} chatId={chatId} message={message} attachments={attachments} adjustTextArea={adjustTextArea} saveChanges={saveEditedMessage} /> ) : ( <div className="break-words"> <RenderChatContent role={role} message={message} expanded={isLastMessage} /> {isRefusalMessage && ( <Link data-tooltip-id="query-refusal-info" data-tooltip-content={`${t("chat.refusal.tooltip-description")}`} className="!no-underline group !flex w-fit" to={paths.chatModes()} target="_blank" > <div className="flex flex-row items-center gap-x-1 group-hover:opacity-100 opacity-60 w-fit"> <Info className="text-theme-text-secondary" /> <p className="!m-0 !p-0 text-theme-text-secondary !no-underline text-xs cursor-pointer"> {t("chat.refusal.tooltip-title")} </p> </div> </Link> )} <ChatAttachments attachments={attachments} /> </div> )} </div> <div className="flex gap-x-5 ml-14"> <Actions message={message} feedbackScore={feedbackScore} chatId={chatId} slug={workspace?.slug} isLastMessage={isLastMessage} regenerateMessage={regenerateMessage} isEditing={isEditing} role={role} forkThread={forkThread} metrics={metrics} alignmentCls={alignmentCls} /> </div> {role === "assistant" && <Citations sources={sources} />} </div> </div> ); }; function ProfileImage({ role, workspace }) { if (role === "assistant" && workspace.pfpUrl) { return ( <div className="relative w-[35px] h-[35px] rounded-full flex-shrink-0 overflow-hidden"> <img src={workspace.pfpUrl} alt="Workspace profile picture" className="absolute top-0 left-0 w-full h-full object-cover rounded-full bg-white" /> </div> ); } return ( <UserIcon user={{ uid: role === "user" ? userFromStorage()?.username : workspace.slug, }} role={role} /> ); } export default memo( HistoricalMessage, // Skip re-render the historical message: // if the content is the exact same AND (not streaming) // the lastMessage status is the same (regen icon) // and the chatID matches between renders. (feedback icons) (prevProps, nextProps) => { return ( prevProps.message === nextProps.message && prevProps.isLastMessage === nextProps.isLastMessage && prevProps.chatId === nextProps.chatId ); } ); function ChatAttachments({ attachments = [] }) { if (!attachments.length) return null; return ( <div className="flex flex-wrap gap-2"> {attachments.map((item) => ( <img key={item.name} src={item.contentString} className="max-w-[300px] rounded-md" /> ))} </div> ); } const RenderChatContent = memo( ({ role, message, expanded = false }) => { // If the message is not from the assistant, we can render it directly // as normal since the user cannot think (lol) if (role !== "assistant") return ( <span className="flex flex-col gap-y-1" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(renderMarkdown(message)), }} /> ); let thoughtChain = null; let msgToRender = message; if (!message) return null; // If the message is a perfect thought chain, we can render it directly // Complete == open and close tags match perfectly. if (message.match(THOUGHT_REGEX_COMPLETE)) { thoughtChain = message.match(THOUGHT_REGEX_COMPLETE)?.[0]; msgToRender = message.replace(THOUGHT_REGEX_COMPLETE, ""); } // If the message is a thought chain but not a complete thought chain (matching opening tags but not closing tags), // we can render it as a thought chain if we can at least find a closing tag // This can occur when the assistant starts with <thinking> and then <response>'s later. if ( message.match(THOUGHT_REGEX_OPEN) && message.match(THOUGHT_REGEX_CLOSE) ) { const closingTag = message.match(THOUGHT_REGEX_CLOSE)?.[0]; const splitMessage = message.split(closingTag); thoughtChain = splitMessage[0] + closingTag; msgToRender = splitMessage[1]; } return ( <> {thoughtChain && ( <ThoughtChainComponent content={thoughtChain} expanded={expanded} /> )} <span className="flex flex-col gap-y-1" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(renderMarkdown(msgToRender)), }} /> </> ); }, (prevProps, nextProps) => { return ( prevProps.role === nextProps.role && prevProps.message === nextProps.message && prevProps.expanded === nextProps.expanded ); } );
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/index.jsx
import React, { memo, useState } from "react"; import useCopyText from "@/hooks/useCopyText"; import { Check, ThumbsUp, ArrowsClockwise, Copy } from "@phosphor-icons/react"; import Workspace from "@/models/workspace"; import { EditMessageAction } from "./EditMessage"; import RenderMetrics from "./RenderMetrics"; import ActionMenu from "./ActionMenu"; import { useTranslation } from "react-i18next"; const Actions = ({ message, feedbackScore, chatId, slug, isLastMessage, regenerateMessage, forkThread, isEditing, role, metrics = {}, alignmentCls = "", }) => { const { t } = useTranslation(); const [selectedFeedback, setSelectedFeedback] = useState(feedbackScore); const handleFeedback = async (newFeedback) => { const updatedFeedback = selectedFeedback === newFeedback ? null : newFeedback; await Workspace.updateChatFeedback(chatId, slug, updatedFeedback); setSelectedFeedback(updatedFeedback); }; return ( <div className={`flex w-full justify-between items-center ${alignmentCls}`}> <div className="flex justify-start items-center gap-x-[8px]"> <CopyMessage message={message} /> <div className="md:group-hover:opacity-100 transition-all duration-300 md:opacity-0 flex justify-start items-center gap-x-[8px]"> <EditMessageAction chatId={chatId} role={role} isEditing={isEditing} /> {isLastMessage && !isEditing && ( <RegenerateMessage regenerateMessage={regenerateMessage} slug={slug} chatId={chatId} /> )} {chatId && role !== "user" && !isEditing && ( <FeedbackButton isSelected={selectedFeedback === true} handleFeedback={() => handleFeedback(true)} tooltipId="feedback-button" tooltipContent={t("chat_window.good_response")} IconComponent={ThumbsUp} /> )} <ActionMenu chatId={chatId} forkThread={forkThread} isEditing={isEditing} role={role} /> </div> </div> <RenderMetrics metrics={metrics} /> </div> ); }; function FeedbackButton({ isSelected, handleFeedback, tooltipContent, IconComponent, }) { return ( <div className="mt-3 relative"> <button onClick={handleFeedback} data-tooltip-id="feedback-button" data-tooltip-content={tooltipContent} className="text-zinc-300" aria-label={tooltipContent} > <IconComponent color="var(--theme-sidebar-footer-icon-fill)" size={20} className="mb-1" weight={isSelected ? "fill" : "regular"} /> </button> </div> ); } function CopyMessage({ message }) { const { copied, copyText } = useCopyText(); const { t } = useTranslation(); return ( <> <div className="mt-3 relative"> <button onClick={() => copyText(message)} data-tooltip-id="copy-assistant-text" data-tooltip-content={t("chat_window.copy")} className="text-zinc-300" aria-label={t("chat_window.copy")} > {copied ? ( <Check color="var(--theme-sidebar-footer-icon-fill)" size={20} className="mb-1" /> ) : ( <Copy color="var(--theme-sidebar-footer-icon-fill)" size={20} className="mb-1" /> )} </button> </div> </> ); } function RegenerateMessage({ regenerateMessage, chatId }) { if (!chatId) return null; const { t } = useTranslation(); return ( <div className="mt-3 relative"> <button onClick={() => regenerateMessage(chatId)} data-tooltip-id="regenerate-assistant-text" data-tooltip-content={t("chat_window.regenerate_response")} className="border-none text-zinc-300" aria-label={t("chat_window.regenerate")} > <ArrowsClockwise color="var(--theme-sidebar-footer-icon-fill)" size={20} className="mb-1" weight="fill" /> </button> </div> ); } export default memo(Actions);
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/ActionMenu/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/ActionMenu/index.jsx
import React, { useState, useEffect, useRef } from "react"; import { Trash, DotsThreeVertical, TreeView } from "@phosphor-icons/react"; import { useTranslation } from "react-i18next"; function ActionMenu({ chatId, forkThread, isEditing, role }) { const { t } = useTranslation(); const [open, setOpen] = useState(false); const menuRef = useRef(null); const toggleMenu = () => setOpen(!open); const handleFork = () => { forkThread(chatId); setOpen(false); }; const handleDelete = () => { window.dispatchEvent( new CustomEvent("delete-message", { detail: { chatId } }) ); setOpen(false); }; useEffect(() => { const handleClickOutside = (event) => { if (menuRef.current && !menuRef.current.contains(event.target)) { setOpen(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); if (!chatId || isEditing || role === "user") return null; return ( <div className="mt-2 -ml-0.5 relative" ref={menuRef}> <button onClick={toggleMenu} className="border-none text-[var(--theme-sidebar-footer-icon-fill)] hover:text-[var(--theme-sidebar-footer-icon-fill)] transition-colors duration-200" data-tooltip-id="action-menu" data-tooltip-content={t("chat_window.more_actions")} aria-label={t("chat_window.more_actions")} > <DotsThreeVertical size={24} weight="bold" /> </button> {open && ( <div className="absolute -top-1 left-7 mt-1 border-[1.5px] border-white/40 rounded-lg bg-theme-action-menu-bg flex flex-col shadow-[0_4px_14px_rgba(0,0,0,0.25)] text-white z-99 md:z-10"> <button onClick={handleFork} className="border-none rounded-t-lg flex items-center text-white gap-x-2 hover:bg-theme-action-menu-item-hover py-1.5 px-2 transition-colors duration-200 w-full text-left" > <TreeView size={18} /> <span className="text-sm">{t("chat_window.fork")}</span> </button> <button onClick={handleDelete} className="border-none flex rounded-b-lg items-center text-white gap-x-2 hover:bg-theme-action-menu-item-hover py-1.5 px-2 transition-colors duration-200 w-full text-left" > <Trash size={18} /> <span className="text-sm">{t("chat_window.delete")}</span> </button> </div> )} </div> ); } export default ActionMenu;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/RenderMetrics/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/RenderMetrics/index.jsx
import { formatDateTimeAsMoment } from "@/utils/directories"; import { numberWithCommas } from "@/utils/numbers"; import React, { useEffect, useState, useContext } from "react"; const MetricsContext = React.createContext(); const SHOW_METRICS_KEY = "anythingllm_show_chat_metrics"; const SHOW_METRICS_EVENT = "anythingllm_show_metrics_change"; /** * @param {number} duration - duration in milliseconds * @returns {string} */ function formatDuration(duration) { try { return duration < 1 ? `${(duration * 1000).toFixed(0)}ms` : `${duration.toFixed(3)}s`; } catch { return ""; } } /** * Format the output TPS to a string * @param {number} outputTps - output TPS * @returns {string} */ function formatTps(outputTps) { try { return outputTps < 1000 ? outputTps.toFixed(2) : numberWithCommas(outputTps.toFixed(0)); } catch { return ""; } } /** * Get the show metrics setting from localStorage `anythingllm_show_chat_metrics` key * @returns {boolean} */ function getAutoShowMetrics() { return window?.localStorage?.getItem(SHOW_METRICS_KEY) === "true"; } /** * Build the metrics string for a given metrics object * - Model name * - Duration and output TPS * - Timestamp * @param {metrics: {duration:number, outputTps: number, model?: string, timestamp?: number}} metrics * @returns {string} */ function buildMetricsString(metrics = {}) { return [ metrics?.model ? metrics.model : "", `${formatDuration(metrics.duration)} (${formatTps(metrics.outputTps)} tok/s)`, metrics?.timestamp ? formatDateTimeAsMoment(metrics.timestamp, "MMM D, h:mm A") : "", ] .filter(Boolean) .join(" · "); } /** * Toggle the show metrics setting in localStorage `anythingllm_show_chat_metrics` key * @returns {void} */ function toggleAutoShowMetrics() { const currentValue = getAutoShowMetrics() || false; window?.localStorage?.setItem(SHOW_METRICS_KEY, !currentValue); window.dispatchEvent( new CustomEvent(SHOW_METRICS_EVENT, { detail: { showMetricsAutomatically: !currentValue }, }) ); return !currentValue; } /** * Provider for the metrics context that controls the visibility of the metrics * per-chat based on the user's preference. * @param {React.ReactNode} children * @returns {React.ReactNode} */ export function MetricsProvider({ children }) { const [showMetricsAutomatically, setShowMetricsAutomatically] = useState(getAutoShowMetrics()); useEffect(() => { function handleShowingMetricsEvent(e) { if (!e?.detail?.hasOwnProperty("showMetricsAutomatically")) return; setShowMetricsAutomatically(e.detail.showMetricsAutomatically); } console.log("Adding event listener for metrics visibility"); window.addEventListener(SHOW_METRICS_EVENT, handleShowingMetricsEvent); return () => window.removeEventListener(SHOW_METRICS_EVENT, handleShowingMetricsEvent); }, []); return ( <MetricsContext.Provider value={{ showMetricsAutomatically, setShowMetricsAutomatically }} > {children} </MetricsContext.Provider> ); } /** * Render the metrics for a given chat, if available * @param {metrics: {duration:number, outputTps: number, model: string, timestamp: number}} props * @returns */ export default function RenderMetrics({ metrics = {} }) { // Inherit the showMetricsAutomatically state from the MetricsProvider so the state is shared across all chats const { showMetricsAutomatically, setShowMetricsAutomatically } = useContext(MetricsContext); if (!metrics?.duration || !metrics?.outputTps) return null; return ( <button type="button" onClick={() => setShowMetricsAutomatically(toggleAutoShowMetrics())} data-tooltip-id="metrics-visibility" data-tooltip-content={ showMetricsAutomatically ? "Click to only show metrics when hovering" : "Click to show metrics as soon as they are available" } className={`border-none flex justify-end items-center gap-x-[8px] ${showMetricsAutomatically ? "opacity-100" : "opacity-0"} md:group-hover:opacity-100 transition-all duration-300`} > <p className="cursor-pointer text-xs font-mono text-theme-text-secondary opacity-50"> {buildMetricsString(metrics)} </p> </button> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/TTSButton/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/TTSButton/index.jsx
import { useTTSProvider } from "@/components/contexts/TTSProvider"; import NativeTTSMessage from "./native"; import AsyncTTSMessage from "./asyncTts"; import PiperTTSMessage from "./piperTTS"; export default function TTSMessage({ slug, chatId, message }) { const { settings, provider, loading } = useTTSProvider(); if (!chatId || loading) return null; switch (provider) { case "openai": case "generic-openai": case "elevenlabs": return <AsyncTTSMessage chatId={chatId} slug={slug} />; case "piper_local": return ( <PiperTTSMessage chatId={chatId} voiceId={settings?.TTSPiperTTSVoiceModel} message={message} /> ); default: return <NativeTTSMessage chatId={chatId} message={message} />; } }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/TTSButton/piperTTS.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/TTSButton/piperTTS.jsx
import { useEffect, useState, useRef } from "react"; import { SpeakerHigh, PauseCircle, CircleNotch } from "@phosphor-icons/react"; import PiperTTSClient from "@/utils/piperTTS"; export default function PiperTTS({ chatId, voiceId = null, message }) { const playerRef = useRef(null); const [speaking, setSpeaking] = useState(false); const [loading, setLoading] = useState(false); const [audioSrc, setAudioSrc] = useState(null); async function speakMessage(e) { e.preventDefault(); if (speaking) { playerRef?.current?.pause(); return; } try { if (!audioSrc) { setLoading(true); const client = new PiperTTSClient({ voiceId }); const blobUrl = await client.getAudioBlobForText(message); setAudioSrc(blobUrl); setLoading(false); } else { playerRef.current.play(); } } catch (e) { console.error(e); setLoading(false); setSpeaking(false); } } useEffect(() => { function setupPlayer() { if (!playerRef?.current) return; playerRef.current.addEventListener("play", () => { setSpeaking(true); }); playerRef.current.addEventListener("pause", () => { playerRef.current.currentTime = 0; setSpeaking(false); }); } setupPlayer(); }, []); return ( <div className="mt-3 relative"> <button type="button" onClick={speakMessage} disabled={loading} data-auto-play-chat-id={chatId} data-tooltip-id="message-to-speech" data-tooltip-content={ speaking ? "Pause TTS speech of message" : "TTS Speak message" } className="border-none text-[var(--theme-sidebar-footer-icon-fill)]" aria-label={speaking ? "Pause speech" : "Speak message"} > {speaking ? ( <PauseCircle size={18} className="mb-1" /> ) : ( <> {loading ? ( <CircleNotch size={18} className="mb-1 animate-spin" /> ) : ( <SpeakerHigh size={18} className="mb-1" /> )} </> )} <audio ref={playerRef} hidden={true} src={audioSrc} autoPlay={true} controls={false} /> </button> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/TTSButton/asyncTts.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/TTSButton/asyncTts.jsx
import { useEffect, useState, useRef } from "react"; import { SpeakerHigh, PauseCircle, CircleNotch } from "@phosphor-icons/react"; import Workspace from "@/models/workspace"; import showToast from "@/utils/toast"; import { useTranslation } from "react-i18next"; export default function AsyncTTSMessage({ slug, chatId }) { const playerRef = useRef(null); const [speaking, setSpeaking] = useState(false); const [loading, setLoading] = useState(false); const [audioSrc, setAudioSrc] = useState(null); const { t } = useTranslation(); function speakMessage() { if (speaking) { playerRef?.current?.pause(); return; } try { if (!audioSrc) { setLoading(true); Workspace.ttsMessage(slug, chatId) .then((audioBlob) => { if (!audioBlob) throw new Error("Failed to load or play TTS message response."); setAudioSrc(audioBlob); }) .catch((e) => showToast(e.message, "error", { clear: true })) .finally(() => setLoading(false)); } else { playerRef.current.play(); } } catch (e) { console.error(e); setLoading(false); setSpeaking(false); } } useEffect(() => { function setupPlayer() { if (!playerRef?.current) return; playerRef.current.addEventListener("play", () => { setSpeaking(true); }); playerRef.current.addEventListener("pause", () => { playerRef.current.currentTime = 0; setSpeaking(false); }); } setupPlayer(); }, []); if (!chatId) return null; return ( <div className="mt-3 relative"> <button onClick={speakMessage} data-auto-play-chat-id={chatId} data-tooltip-id="message-to-speech" data-tooltip-content={ speaking ? t("pause_tts_speech_message") : t("chat_window.tts_speak_message") } className="border-none text-[var(--theme-sidebar-footer-icon-fill)]" aria-label={speaking ? "Pause speech" : "Speak message"} > {speaking ? ( <PauseCircle size={18} className="mb-1" /> ) : ( <> {loading ? ( <CircleNotch size={18} className="mb-1 animate-spin" /> ) : ( <SpeakerHigh size={18} className="mb-1" /> )} </> )} <audio ref={playerRef} hidden={true} src={audioSrc} autoPlay={true} controls={false} /> </button> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/TTSButton/native.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/TTSButton/native.jsx
import React, { useEffect, useState } from "react"; import { SpeakerHigh, PauseCircle } from "@phosphor-icons/react"; export default function NativeTTSMessage({ chatId, message }) { const [speaking, setSpeaking] = useState(false); const [supported, setSupported] = useState(false); useEffect(() => { setSupported("speechSynthesis" in window); }, []); function endSpeechUtterance() { window.speechSynthesis?.cancel(); setSpeaking(false); return; } function speakMessage() { // if the user is pausing this particular message // while the synth is speaking we can end it. // If they are clicking another message's TTS // we need to ignore that until they pause the one that is playing. if (window.speechSynthesis.speaking && speaking) { endSpeechUtterance(); return; } if (window.speechSynthesis.speaking && !speaking) return; const utterance = new SpeechSynthesisUtterance(message); utterance.addEventListener("end", endSpeechUtterance); window.speechSynthesis.speak(utterance); setSpeaking(true); } if (!supported) return null; return ( <div className="mt-3 relative"> <button onClick={speakMessage} data-auto-play-chat-id={chatId} data-tooltip-id="message-to-speech" data-tooltip-content={ speaking ? "Pause TTS speech of message" : "TTS Speak message" } className="border-none text-[var(--theme-sidebar-footer-icon-fill)]" aria-label={speaking ? "Pause speech" : "Speak message"} > {speaking ? ( <PauseCircle size={18} className="mb-1" /> ) : ( <SpeakerHigh size={18} className="mb-1" /> )} </button> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/EditMessage/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/EditMessage/index.jsx
import { Pencil } from "@phosphor-icons/react"; import { useState, useEffect, useRef } from "react"; import Appearance from "@/models/appearance"; import { useTranslation } from "react-i18next"; const EDIT_EVENT = "toggle-message-edit"; export function useEditMessage({ chatId, role }) { const [isEditing, setIsEditing] = useState(false); function onEditEvent(e) { if (e.detail.chatId !== chatId || e.detail.role !== role) { setIsEditing(false); return false; } setIsEditing((prev) => !prev); } useEffect(() => { function listenForEdits() { if (!chatId || !role) return; window.addEventListener(EDIT_EVENT, onEditEvent); } listenForEdits(); return () => { window.removeEventListener(EDIT_EVENT, onEditEvent); }; }, [chatId, role]); return { isEditing, setIsEditing }; } export function EditMessageAction({ chatId = null, role, isEditing }) { const { t } = useTranslation(); function handleEditClick() { window.dispatchEvent( new CustomEvent(EDIT_EVENT, { detail: { chatId, role } }) ); } if (!chatId || isEditing) return null; return ( <div className={`mt-3 relative ${ role === "user" && !isEditing ? "" : "!opacity-100" }`} > <button onClick={handleEditClick} data-tooltip-id="edit-input-text" data-tooltip-content={`${ role === "user" ? t("chat_window.edit_prompt") : t("chat_window.edit_response") } `} className="border-none text-zinc-300" aria-label={`Edit ${role === "user" ? t("chat_window.edit_prompt") : t("chat_window.edit_response")}`} > <Pencil color="var(--theme-sidebar-footer-icon-fill)" size={21} className="mb-1" /> </button> </div> ); } export function EditMessageForm({ role, chatId, message, attachments = [], adjustTextArea, saveChanges, }) { const formRef = useRef(null); const { t } = useTranslation(); function handleSaveMessage(e) { e.preventDefault(); const form = new FormData(e.target); const editedMessage = form.get("editedMessage"); saveChanges({ editedMessage, chatId, role, attachments }); window.dispatchEvent( new CustomEvent(EDIT_EVENT, { detail: { chatId, role, attachments } }) ); } function cancelEdits() { window.dispatchEvent( new CustomEvent(EDIT_EVENT, { detail: { chatId, role, attachments } }) ); return false; } useEffect(() => { if (!formRef || !formRef.current) return; formRef.current.focus(); adjustTextArea({ target: formRef.current }); }, [formRef]); return ( <form onSubmit={handleSaveMessage} className="flex flex-col w-full"> <textarea ref={formRef} name="editedMessage" spellCheck={Appearance.get("enableSpellCheck")} className="text-white w-full rounded bg-theme-bg-secondary border border-white/20 active:outline-none focus:outline-none focus:ring-0 pr-16 pl-1.5 pt-1.5 resize-y" defaultValue={message} onChange={adjustTextArea} /> <div className="mt-3 flex justify-center"> <button type="submit" className="border-none px-2 py-1 bg-gray-200 text-gray-700 font-medium rounded-md mr-2 hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2" > {t("chat_window.save_submit")} </button> <button type="button" className="border-none px-2 py-1 bg-historical-msg-system text-white font-medium rounded-md hover:bg-historical-msg-user/90 light:hover:text-white focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2" onClick={cancelEdits} > {t("chat_window.cancel")} </button> </div> </form> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/DeleteMessage/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/HistoricalMessage/Actions/DeleteMessage/index.jsx
import { useState, useEffect } from "react"; import { Trash } from "@phosphor-icons/react"; import Workspace from "@/models/workspace"; const DELETE_EVENT = "delete-message"; export function useWatchDeleteMessage({ chatId = null, role = "user" }) { const [isDeleted, setIsDeleted] = useState(false); const [completeDelete, setCompleteDelete] = useState(false); useEffect(() => { function listenForEvent() { if (!chatId) return; window.addEventListener(DELETE_EVENT, onDeleteEvent); } listenForEvent(); return () => { window.removeEventListener(DELETE_EVENT, onDeleteEvent); }; }, [chatId]); function onEndAnimation() { if (!isDeleted) return; setCompleteDelete(true); } async function onDeleteEvent(e) { if (e.detail.chatId === chatId) { setIsDeleted(true); // Do this to prevent double-emission of the PUT/DELETE api call // because then there will be a race condition and it will make an error log for nothing // as one call will complete and the other will fail. if (role === "assistant") await Workspace.deleteChat(chatId); return false; } } return { isDeleted, completeDelete, onEndAnimation }; } export function DeleteMessage({ chatId, isEditing, role }) { if (!chatId || isEditing || role === "user") return null; function emitDeleteEvent() { window.dispatchEvent(new CustomEvent(DELETE_EVENT, { detail: { chatId } })); } return ( <button onClick={emitDeleteEvent} className="border-none flex items-center gap-x-1 w-full" role="menuitem" > <Trash size={21} weight="fill" /> <p>Delete</p> </button> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Citation/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Citation/index.jsx
import { memo, useState } from "react"; import { v4 } from "uuid"; import { decode as HTMLDecode } from "he"; import truncate from "truncate"; import ModalWrapper from "@/components/ModalWrapper"; import { middleTruncate } from "@/utils/directories"; import { CaretRight, FileText, Info, ArrowSquareOut, GithubLogo, X, YoutubeLogo, LinkSimple, GitlabLogo, } from "@phosphor-icons/react"; import ConfluenceLogo from "@/media/dataConnectors/confluence.png"; import DrupalWikiLogo from "@/media/dataConnectors/drupalwiki.png"; import ObsidianLogo from "@/media/dataConnectors/obsidian.png"; import PaperlessNgxLogo from "@/media/dataConnectors/paperlessngx.png"; import { toPercentString } from "@/utils/numbers"; import { useTranslation } from "react-i18next"; import pluralize from "pluralize"; import useTextSize from "@/hooks/useTextSize"; function combineLikeSources(sources) { const combined = {}; sources.forEach((source) => { const { id, title, text, chunkSource = "", score = null } = source; if (combined.hasOwnProperty(title)) { combined[title].chunks.push({ id, text, chunkSource, score }); combined[title].references += 1; } else { combined[title] = { title, chunks: [{ id, text, chunkSource, score }], references: 1, }; } }); return Object.values(combined); } export default function Citations({ sources = [] }) { if (sources.length === 0) return null; const [open, setOpen] = useState(false); const [selectedSource, setSelectedSource] = useState(null); const { t } = useTranslation(); const { textSizeClass } = useTextSize(); return ( <div className="flex flex-col mt-4 justify-left"> <button onClick={() => setOpen(!open)} className={`border-none font-semibold text-white/50 light:text-black/50 font-medium italic ${textSizeClass} text-left ml-14 pt-2 ${ open ? "pb-2" : "" } hover:text-white/75 hover:light:text-black/75 transition-all duration-300`} > {open ? t("chat_window.hide_citations") : t("chat_window.show_citations")} <CaretRight weight="bold" size={14} className={`inline-block ml-1 transform transition-transform duration-300 ${ open ? "rotate-90" : "" }`} /> </button> {open && ( <div className="flex flex-wrap flex-col items-start overflow-x-scroll no-scroll mt-1 ml-14 gap-y-2"> {combineLikeSources(sources).map((source) => ( <Citation key={v4()} source={source} onClick={() => setSelectedSource(source)} textSizeClass={textSizeClass} /> ))} </div> )} {selectedSource && ( <CitationDetailModal source={selectedSource} onClose={() => setSelectedSource(null)} /> )} </div> ); } const Citation = memo(({ source, onClick, textSizeClass }) => { const { title, references = 1 } = source; if (!title) return null; const chunkSourceInfo = parseChunkSource(source); const truncatedTitle = chunkSourceInfo?.text ?? middleTruncate(title, 25); const CitationIcon = ICONS.hasOwnProperty(chunkSourceInfo?.icon) ? ICONS[chunkSourceInfo.icon] : ICONS.file; return ( <button className={`flex doc__source gap-x-1 ${textSizeClass}`} onClick={onClick} type="button" > <div className="flex items-start flex-1 pt-[4px]"> <CitationIcon size={16} /> </div> <div className="flex flex-col items-start gap-y-[0.2px] px-1"> <p className={`!m-0 font-semibold whitespace-nowrap text-theme-text-primary hover:opacity-55 ${textSizeClass}`} > {truncatedTitle} </p> <p className={`!m-0 text-[10px] font-medium text-theme-text-secondary ${textSizeClass}`} >{`${references} ${pluralize("Reference", Number(references) || 1)}`}</p> </div> </button> ); }); function omitChunkHeader(text) { if (!text.includes("<document_metadata>")) return text; return text.split("</document_metadata>")[1].trim(); } function CitationDetailModal({ source, onClose }) { const { references, title, chunks } = source; const { isUrl, text: webpageUrl, href: linkTo } = parseChunkSource(source); return ( <ModalWrapper isOpen={source}> <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> {isUrl ? ( <a href={linkTo} target="_blank" rel="noreferrer" className="text-xl w-[90%] font-semibold text-white whitespace-nowrap hover:underline hover:text-blue-300 flex items-center gap-x-1" > <div className="flex items-center gap-x-1 max-w-full overflow-hidden"> <h3 className="truncate text-ellipsis whitespace-nowrap overflow-hidden w-full"> {webpageUrl} </h3> <ArrowSquareOut className="flex-shrink-0" /> </div> </a> ) : ( <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> {truncate(title, 45)} </h3> )} </div> {references > 1 && ( <p className="text-xs text-gray-400 mt-2"> Referenced {references} times. </p> )} <button onClick={onClose} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={24} weight="bold" className="text-white" /> </button> </div> <div className="h-full w-full overflow-y-auto" style={{ maxHeight: "calc(100vh - 200px)" }} > <div className="py-7 px-9 space-y-2 flex-col"> {chunks.map(({ text, score }, idx) => ( <> <div key={idx} className="pt-6 text-white"> <div className="flex flex-col w-full justify-start pb-6 gap-y-1"> <p className="text-white whitespace-pre-line"> {HTMLDecode(omitChunkHeader(text))} </p> {!!score && ( <div className="w-full flex items-center text-xs text-white/60 gap-x-2 cursor-default"> <div data-tooltip-id="similarity-score" data-tooltip-content={`This is the semantic similarity score of this chunk of text compared to your query calculated by the vector database.`} className="flex items-center gap-x-1" > <Info size={14} /> <p>{toPercentString(score)} match</p> </div> </div> )} </div> </div> {idx !== chunks.length - 1 && ( <hr className="border-theme-modal-border" /> )} </> ))} <div className="mb-6"></div> </div> </div> </div> </ModalWrapper> ); } const supportedSources = [ "link://", "confluence://", "github://", "gitlab://", "drupalwiki://", "youtube://", "obsidian://", "paperless-ngx://", ]; /** * Parses the chunk source to get the correct title and/or display text for citations * which contain valid outbound links that can be clicked by the * user when viewing a citation. Optionally allows various icons * to show distinct types of sources. * @param {{title: string, chunks: {text: string, chunkSource: string}[]}} options * @returns {{isUrl: boolean, text: string, href: string, icon: string}} */ function parseChunkSource({ title = "", chunks = [] }) { const nullResponse = { isUrl: false, text: null, href: null, icon: "file", }; if ( !chunks.length || !supportedSources.some((source) => chunks[0].chunkSource?.startsWith(source) ) ) return nullResponse; try { const sourceID = supportedSources.find((source) => chunks[0].chunkSource?.startsWith(source) ); let url, text, icon; // Try to parse the URL from the chunk source // If it fails, we'll use the title as the text and the link icon // but the document will not be linkable try { url = new URL(chunks[0].chunkSource.split(sourceID)[1]); } catch {} switch (sourceID) { case "link://": text = url.host + url.pathname; icon = "link"; break; case "youtube://": text = title; icon = "youtube"; break; case "github://": text = title; icon = "github"; break; case "gitlab://": text = title; icon = "gitlab"; break; case "confluence://": text = title; icon = "confluence"; break; case "drupalwiki://": text = title; icon = "drupalwiki"; break; case "obsidian://": text = title; icon = "obsidian"; break; case "paperless-ngx://": text = title; icon = "paperlessNgx"; break; default: text = url.host + url.pathname; icon = "link"; break; } return { isUrl: !!url, href: url?.toString() ?? "#", text, icon, }; } catch (err) { console.warn(`Unsupported source identifier ${chunks[0].chunkSource}`, err); } return nullResponse; } const ConfluenceIcon = ({ size = 16, ...props }) => ( <img src={ConfluenceLogo} {...props} width={size} height={size} /> ); const DrupalWikiIcon = ({ size = 16, ...props }) => ( <img src={DrupalWikiLogo} {...props} width={size} height={size} /> ); const ObsidianIcon = ({ size = 16, ...props }) => ( <img src={ObsidianLogo} {...props} width={size} height={size} /> ); const PaperlessNgxIcon = ({ size = 16, ...props }) => ( <img src={PaperlessNgxLogo} {...props} width={size} height={size} className="rounded-sm bg-white" /> ); const ICONS = { file: FileText, link: LinkSimple, youtube: YoutubeLogo, github: GithubLogo, gitlab: GitlabLogo, confluence: ConfluenceIcon, drupalwiki: DrupalWikiIcon, obsidian: ObsidianIcon, paperlessNgx: PaperlessNgxIcon, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/StatusResponse/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/StatusResponse/index.jsx
import React, { useState } from "react"; import { CaretDown } from "@phosphor-icons/react"; import AgentAnimation from "@/media/animations/agent-animation.webm"; import AgentStatic from "@/media/animations/agent-static.png"; export default function StatusResponse({ messages = [], isThinking = false }) { const [isExpanded, setIsExpanded] = useState(false); const currentThought = messages[messages.length - 1]; const previousThoughts = messages.slice(0, -1); function handleExpandClick() { if (!previousThoughts.length > 0) return; setIsExpanded(!isExpanded); } return ( <div className="flex justify-center w-full"> <div className="w-full max-w-[80%] flex flex-col"> <div className=" w-full max-w-[800px]"> <div onClick={handleExpandClick} style={{ borderRadius: "6px" }} className={`${!previousThoughts?.length ? "" : `${previousThoughts?.length ? "hover:bg-theme-sidebar-item-hover" : ""}`} items-start bg-theme-bg-chat-input py-2 px-4 flex gap-x-2`} > <div className="w-7 h-7 flex justify-center flex-shrink-0 items-center"> {isThinking ? ( <video autoPlay loop muted playsInline className="w-8 h-8 scale-150 transition-opacity duration-200 light:invert light:opacity-50" data-tooltip-id="agent-thinking" data-tooltip-content="Agent is thinking..." aria-label="Agent is thinking..." > <source src={AgentAnimation} type="video/webm" /> </video> ) : ( <img src={AgentStatic} alt="Agent complete" className="w-6 h-6 transition-opacity duration-200 light:invert light:opacity-50" data-tooltip-id="agent-thinking" data-tooltip-content="Agent has finished thinking" aria-label="Agent has finished thinking" /> )} </div> <div className="flex-1 min-w-0"> <div className={`overflow-hidden transition-all duration-300 ease-in-out ${isExpanded ? "" : "max-h-6"}`} > <div className="text-theme-text-secondary font-mono leading-6"> {!isExpanded ? ( <span className="block w-full truncate mt-[2px]"> {currentThought.content} </span> ) : ( <> {previousThoughts.map((thought, index) => ( <div key={`cot-${thought.uuid || index}`} className="mb-2" > {thought.content} </div> ))} <div>{currentThought.content}</div> </> )} </div> </div> </div> <div className="flex items-center gap-x-2"> {previousThoughts?.length > 0 && ( <button onClick={handleExpandClick} data-tooltip-id="expand-cot" data-tooltip-content={ isExpanded ? "Hide thought chain" : "Show thought chain" } className="border-none text-theme-text-secondary hover:text-theme-text-primary transition-colors p-1 rounded-full hover:bg-theme-sidebar-item-hover" aria-label={ isExpanded ? "Hide thought chain" : "Show thought chain" } > <CaretDown className={`w-4 h-4 transform transition-transform duration-200 ${isExpanded ? "rotate-180" : ""}`} /> </button> )} </div> </div> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Chartable/CustomCell.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Chartable/CustomCell.jsx
export default function CustomCell({ ...props }) { const { root, depth, x, y, width, height, index, payload, colors, rank, name, } = props; return ( <g> <rect x={x} y={y} width={width} height={height} style={{ fill: depth < 2 ? colors[Math.floor((index / root.children.length) * 6)] : "#ffffff00", stroke: "#fff", strokeWidth: 2 / (depth + 1e-10), strokeOpacity: 1 / (depth + 1e-10), }} /> {depth === 1 ? ( <text x={x + width / 2} y={y + height / 2 + 7} textAnchor="middle" fill="#fff" fontSize={14} > {name} </text> ) : null} {depth === 1 ? ( <text x={x + 4} y={y + 18} fill="#fff" fontSize={16} fillOpacity={0.9}> {index + 1} </text> ) : null} </g> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Chartable/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Chartable/index.jsx
import { v4 } from "uuid"; import { AreaChart, BarChart, DonutChart, Legend, LineChart, } from "@tremor/react"; import { Bar, CartesianGrid, ComposedChart, Funnel, FunnelChart, Line, PolarAngleAxis, PolarGrid, PolarRadiusAxis, Radar, RadarChart, RadialBar, RadialBarChart, Scatter, ScatterChart, Treemap, XAxis, YAxis, } from "recharts"; import { Colors, getTremorColor } from "./chart-utils.js"; import CustomCell from "./CustomCell.jsx"; import Tooltip from "./CustomTooltip.jsx"; import { safeJsonParse } from "@/utils/request.js"; import renderMarkdown from "@/utils/chat/markdown.js"; import { WorkspaceProfileImage } from "../PromptReply/index.jsx"; import { memo, useCallback, useState } from "react"; import { saveAs } from "file-saver"; import { useGenerateImage } from "recharts-to-png"; import { CircleNotch, DownloadSimple } from "@phosphor-icons/react"; const dataFormatter = (number) => { return Intl.NumberFormat("us").format(number).toString(); }; export function Chartable({ props, workspace }) { const [getDivJpeg, { ref }] = useGenerateImage({ quality: 1, type: "image/jpeg", options: { backgroundColor: "#393d43", padding: 20, }, }); const handleDownload = useCallback(async () => { const jpeg = await getDivJpeg(); if (jpeg) saveAs(jpeg, `chart-${v4().split("-")[0]}.jpg`); }, []); const color = null; const showLegend = true; const content = typeof props.content === "string" ? safeJsonParse(props.content, null) : props.content; if (content === null) return null; const chartType = content?.type?.toLowerCase(); const data = typeof content.dataset === "string" ? safeJsonParse(content.dataset, []) : content.dataset; const value = data.length > 0 ? Object.keys(data[0])[1] : "value"; const title = content?.title; const renderChart = () => { switch (chartType) { case "area": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> <AreaChart className="h-[350px]" data={data} index="name" categories={[value]} colors={[color || "blue", "cyan"]} showLegend={showLegend} valueFormatter={dataFormatter} /> </div> ); case "bar": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> <BarChart className="h-[350px]" data={data} index="name" categories={[value]} colors={[color || "blue"]} showLegend={showLegend} valueFormatter={dataFormatter} layout={"vertical"} yAxisWidth={100} /> </div> ); case "line": return ( <div className="bg-theme-bg-primary p-8 pb-12 rounded-xl text-white h-[500px] w-full light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> <LineChart className="h-[400px]" data={data} index="name" categories={[value]} colors={[color || "blue"]} showLegend={showLegend} valueFormatter={dataFormatter} /> </div> ); case "composed": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> {showLegend && ( <Legend categories={[value]} colors={[color || "blue", color || "blue"]} className="mb-5 justify-end" /> )} <ComposedChart width={500} height={260} data={data}> <CartesianGrid strokeDasharray="3 3" horizontal vertical={false} /> <XAxis dataKey="name" tickLine={false} axisLine={false} interval="preserveStartEnd" tick={{ transform: "translate(0, 6)", fill: "white" }} style={{ fontSize: "12px", fontFamily: "Inter; Helvetica", }} padding={{ left: 10, right: 10 }} /> <YAxis tickLine={false} axisLine={false} type="number" tick={{ transform: "translate(-3, 0)", fill: "white" }} style={{ fontSize: "12px", fontFamily: "Inter; Helvetica", }} /> <Tooltip legendColor={getTremorColor(color || "blue")} /> <Line type="linear" dataKey={value} stroke={getTremorColor(color || "blue")} dot={false} strokeWidth={2} /> <Bar dataKey="value" name="value" type="linear" fill={getTremorColor(color || "blue")} /> </ComposedChart> </div> ); case "scatter": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> {showLegend && ( <div className="flex justify-end"> <Legend categories={[value]} colors={[color || "blue", color || "blue"]} className="mb-5" /> </div> )} <ScatterChart width={500} height={260} data={data}> <CartesianGrid strokeDasharray="3 3" horizontal vertical={false} /> <XAxis dataKey="name" tickLine={false} axisLine={false} interval="preserveStartEnd" tick={{ transform: "translate(0, 6)", fill: "white" }} style={{ fontSize: "12px", fontFamily: "Inter; Helvetica", }} padding={{ left: 10, right: 10 }} /> <YAxis tickLine={false} axisLine={false} type="number" tick={{ transform: "translate(-3, 0)", fill: "white" }} style={{ fontSize: "12px", fontFamily: "Inter; Helvetica", }} /> <Tooltip legendColor={getTremorColor(color || "blue")} /> <Scatter dataKey={value} fill={getTremorColor(color || "blue")} /> </ScatterChart> </div> ); case "pie": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> <DonutChart data={data} category={value} index="name" colors={[ color || "cyan", "violet", "rose", "amber", "emerald", "teal", "fuchsia", ]} // No actual legend for pie chart, but this will toggle the central text showLabel={showLegend} valueFormatter={dataFormatter} customTooltip={customTooltip} /> </div> ); case "radar": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> {showLegend && ( <div className="flex justify-end"> <Legend categories={[value]} colors={[color || "blue", color || "blue"]} className="mb-5" /> </div> )} <RadarChart cx={300} cy={250} outerRadius={150} width={600} height={500} data={data} > <PolarGrid /> <PolarAngleAxis dataKey="name" tick={{ fill: "white" }} /> <PolarRadiusAxis tick={{ fill: "white" }} /> <Tooltip legendColor={getTremorColor(color || "blue")} /> <Radar dataKey="value" stroke={getTremorColor(color || "blue")} fill={getTremorColor(color || "blue")} fillOpacity={0.6} /> </RadarChart> </div> ); case "radialbar": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> {showLegend && ( <div className="flex justify-end"> <Legend categories={[value]} colors={[color || "blue", color || "blue"]} className="mb-5" /> </div> )} <RadialBarChart width={500} height={300} cx={150} cy={150} innerRadius={20} outerRadius={140} barSize={10} data={data} > <RadialBar angleAxisId={15} label={{ position: "insideStart", fill: getTremorColor(color || "blue"), }} dataKey="value" /> <Tooltip legendColor={getTremorColor(color || "blue")} /> </RadialBarChart> </div> ); case "treemap": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> {showLegend && ( <div className="flex justify-end"> <Legend categories={[value]} colors={[color || "blue", color || "blue"]} className="mb-5" /> </div> )} <Treemap width={500} height={260} data={data} dataKey="value" stroke="#fff" fill={getTremorColor(color || "blue")} content={<CustomCell colors={Object.values(Colors)} />} > <Tooltip legendColor={getTremorColor(color || "blue")} /> </Treemap> </div> ); case "funnel": return ( <div className="bg-theme-bg-primary p-8 rounded-xl text-white light:border light:border-theme-border-primary"> <h3 className="text-lg text-theme-text-primary font-medium"> {title} </h3> {showLegend && ( <div className="flex justify-end"> <Legend categories={[value]} colors={[color || "blue", color || "blue"]} className="mb-5" /> </div> )} <FunnelChart width={500} height={300} data={data}> <Tooltip legendColor={getTremorColor(color || "blue")} /> <Funnel dataKey="value" color={getTremorColor(color || "blue")} /> </FunnelChart> </div> ); default: return <p>Unsupported chart type.</p>; } }; if (!!props.chatId) { return ( <div className="flex justify-center items-end w-full"> <div className="py-2 px-4 w-full flex gap-x-5 md:max-w-[80%] flex-col"> <div className="flex gap-x-5"> <WorkspaceProfileImage workspace={workspace} /> <div className="relative w-full"> <DownloadGraph onClick={handleDownload} /> <div ref={ref}>{renderChart()}</div> <span className={`flex flex-col gap-y-1 mt-2`} dangerouslySetInnerHTML={{ __html: renderMarkdown(content.caption), }} /> </div> </div> </div> </div> ); } return ( <div className="flex justify-center items-end w-full"> <div className="py-2 px-4 w-full flex gap-x-5 md:max-w-[80%] flex-col"> <div className="relative w-full"> <DownloadGraph onClick={handleDownload} /> <div ref={ref}>{renderChart()}</div> </div> <div className="flex gap-x-5"> <span className={`flex flex-col gap-y-1 mt-2`} dangerouslySetInnerHTML={{ __html: renderMarkdown(content.caption), }} /> </div> </div> </div> ); } const customTooltip = (props) => { const { payload, active } = props; if (!active || !payload) return null; const categoryPayload = payload?.[0]; if (!categoryPayload) return null; return ( <div className="w-56 bg-theme-bg-primary rounded-lg border p-2 text-white"> <div className="flex flex-1 space-x-2.5"> <div className={`flex w-1.5 flex-col bg-${categoryPayload?.color}-500 rounded`} /> <div className="w-full"> <div className="flex items-center justify-between space-x-8"> <p className="whitespace-nowrap text-right text-tremor-content"> {categoryPayload.name} </p> <p className="whitespace-nowrap text-right font-medium text-tremor-content-emphasis"> {categoryPayload.value} </p> </div> </div> </div> </div> ); }; function DownloadGraph({ onClick }) { const [loading, setLoading] = useState(false); const handleClick = async () => { setLoading(true); await onClick?.(); setLoading(false); }; return ( <div className="absolute top-3 right-3 z-50 cursor-pointer"> <div className="flex flex-col items-center"> <div className="p-1 rounded-full border-none"> {loading ? ( <CircleNotch className="text-theme-text-primary w-5 h-5 animate-spin" aria-label="Downloading image..." /> ) : ( <DownloadSimple weight="bold" className="text-theme-text-primary w-5 h-5 hover:text-theme-text-primary" onClick={handleClick} aria-label="Download graph image" /> )} </div> </div> </div> ); } export default memo(Chartable);
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Chartable/CustomTooltip.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Chartable/CustomTooltip.jsx
import { Tooltip as RechartsTooltip } from "recharts"; // Given a hex, convert to the opposite highest-contrast color // and if `bw` is enabled, force it to be black/white to normalize // interface. function invertColor(hex, bw) { if (hex.indexOf("#") === 0) { hex = hex.slice(1); } // convert 3-digit hex to 6-digits. if (hex.length === 3) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } if (hex.length !== 6) { throw new Error("Invalid HEX color."); } var r = parseInt(hex.slice(0, 2), 16), g = parseInt(hex.slice(2, 4), 16), b = parseInt(hex.slice(4, 6), 16); if (bw) { // https://stackoverflow.com/a/3943023/112731 return r * 0.299 + g * 0.587 + b * 0.114 > 186 ? "#FFFFFF" : "#000000"; // : '#FFFFFF'; } // invert color components r = (255 - r).toString(16); g = (255 - g).toString(16); b = (255 - b).toString(16); // pad each with zeros and return return "#" + padZero(r) + padZero(g) + padZero(b); } function padZero(str, len) { len = len || 2; var zeros = new Array(len).join("0"); return (zeros + str).slice(-len); } export default function Tooltip({ legendColor, ...props }) { return ( <RechartsTooltip wrapperStyle={{ outline: "none" }} isAnimationActive={false} cursor={{ fill: "#d1d5db", opacity: "0.15" }} position={{ y: 0 }} {...props} content={({ active, payload, label }) => { return active && payload ? ( <div className="bg-theme-bg-primary text-sm rounded-md border shadow-lg"> <div className="border-b py-2 px-4"> <p className="text-theme-bg-primary font-medium">{label}</p> </div> <div className="space-y-1 py-2 px-4"> {payload.map(({ value, name }, idx) => ( <div key={`id-${idx}`} className="flex items-center justify-between space-x-8" > <div className="flex items-center space-x-2"> <span className="shrink-0 h-3 w-3 border-theme-bg-primary rounded-md rounded-full border-2 shadow-md" style={{ backgroundColor: legendColor }} /> <p style={{ color: invertColor(legendColor, true), }} className="font-medium tabular-nums text-right whitespace-nowrap" > {value} </p> </div> <p style={{ color: invertColor(legendColor, true), }} className="whitespace-nowrap font-normal" > {name} </p> </div> ))} </div> </div> ) : null; }} /> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Chartable/chart-utils.js
frontend/src/components/WorkspaceChat/ChatContainer/ChatHistory/Chartable/chart-utils.js
export const Colors = { blue: "#3b82f6", sky: "#0ea5e9", cyan: "#06b6d4", teal: "#14b8a6", emerald: "#10b981", green: "#22c55e", lime: "#84cc16", yellow: "#eab308", amber: "#f59e0b", orange: "#f97316", red: "#ef4444", rose: "#f43f5e", pink: "#ec4899", fuchsia: "#d946ef", purple: "#a855f7", violet: "#8b5cf6", indigo: "#6366f1", neutral: "#737373", stone: "#78716c", gray: "#6b7280", slate: "#64748b", zinc: "#71717a", }; export function getTremorColor(color) { switch (color) { case "blue": return Colors.blue; case "sky": return Colors.sky; case "cyan": return Colors.cyan; case "teal": return Colors.teal; case "emerald": return Colors.emerald; case "green": return Colors.green; case "lime": return Colors.lime; case "yellow": return Colors.yellow; case "amber": return Colors.amber; case "orange": return Colors.orange; case "red": return Colors.red; case "rose": return Colors.rose; case "pink": return Colors.pink; case "fuchsia": return Colors.fuchsia; case "purple": return Colors.purple; case "violet": return Colors.violet; case "indigo": return Colors.indigo; case "neutral": return Colors.neutral; case "stone": return Colors.stone; case "gray": return Colors.gray; case "slate": return Colors.slate; case "zinc": return Colors.zinc; } } export const themeColorRange = [ "slate", "gray", "zinc", "neutral", "stone", "red", "orange", "amber", "yellow", "lime", "green", "emerald", "teal", "cyan", "sky", "blue", "indigo", "violet", "purple", "fuchsia", "pink", "rose", ];
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/DnDWrapper/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/DnDWrapper/index.jsx
import { useState, useEffect, createContext, useContext } from "react"; import { v4 } from "uuid"; import System from "@/models/system"; import { useDropzone } from "react-dropzone"; import DndIcon from "./dnd-icon.png"; import Workspace from "@/models/workspace"; import showToast from "@/utils/toast"; import FileUploadWarningModal from "./FileUploadWarningModal"; import pluralize from "pluralize"; export const DndUploaderContext = createContext(); export const REMOVE_ATTACHMENT_EVENT = "ATTACHMENT_REMOVE"; export const CLEAR_ATTACHMENTS_EVENT = "ATTACHMENT_CLEAR"; export const PASTE_ATTACHMENT_EVENT = "ATTACHMENT_PASTED"; export const ATTACHMENTS_PROCESSING_EVENT = "ATTACHMENTS_PROCESSING"; export const ATTACHMENTS_PROCESSED_EVENT = "ATTACHMENTS_PROCESSED"; export const PARSED_FILE_ATTACHMENT_REMOVED_EVENT = "PARSED_FILE_ATTACHMENT_REMOVED"; /** * File Attachment for automatic upload on the chat container page. * @typedef Attachment * @property {string} uid - unique file id. * @property {File} file - native File object * @property {string|null} contentString - base64 encoded string of file * @property {('in_progress'|'failed'|'embedded'|'added_context')} status - the automatic upload status. * @property {string|null} error - Error message * @property {{id:string, location:string}|null} document - uploaded document details * @property {('attachment'|'upload')} type - The type of upload. Attachments are chat-specific, uploads go to the workspace. */ /** * @typedef {Object} ParsedFile * @property {number} id - The id of the parsed file. * @property {string} filename - The name of the parsed file. * @property {number} workspaceId - The id of the workspace the parsed file belongs to. * @property {string|null} userId - The id of the user the parsed file belongs to. * @property {string|null} threadId - The id of the thread the parsed file belongs to. * @property {string} metadata - The metadata of the parsed file. * @property {number} tokenCountEstimate - The estimated token count of the parsed file. */ export function DnDFileUploaderProvider({ workspace, threadSlug = null, children, }) { const [files, setFiles] = useState([]); const [ready, setReady] = useState(false); const [dragging, setDragging] = useState(false); const [showWarningModal, setShowWarningModal] = useState(false); const [isEmbedding, setIsEmbedding] = useState(false); const [embedProgress, setEmbedProgress] = useState(0); const [pendingFiles, setPendingFiles] = useState([]); const [tokenCount, setTokenCount] = useState(0); const [maxTokens, setMaxTokens] = useState(Number.POSITIVE_INFINITY); useEffect(() => { System.checkDocumentProcessorOnline().then((status) => setReady(status)); }, []); useEffect(() => { window.addEventListener(REMOVE_ATTACHMENT_EVENT, handleRemove); window.addEventListener(CLEAR_ATTACHMENTS_EVENT, resetAttachments); window.addEventListener(PASTE_ATTACHMENT_EVENT, handlePastedAttachment); window.addEventListener( PARSED_FILE_ATTACHMENT_REMOVED_EVENT, handleRemoveParsedFile ); return () => { window.removeEventListener(REMOVE_ATTACHMENT_EVENT, handleRemove); window.removeEventListener(CLEAR_ATTACHMENTS_EVENT, resetAttachments); window.removeEventListener( PARSED_FILE_ATTACHMENT_REMOVED_EVENT, handleRemoveParsedFile ); window.removeEventListener( PASTE_ATTACHMENT_EVENT, handlePastedAttachment ); }; }, []); /** * Handles the removal of a parsed file attachment from the uploader queue. * Only uses the document id to remove the file from the queue * @param {CustomEvent<{document: ParsedFile}>} event */ async function handleRemoveParsedFile(event) { const { document } = event.detail; setFiles((prev) => prev.filter((prevFile) => prevFile.document.id !== document.id) ); } /** * Remove file from uploader queue. * @param {CustomEvent<{uid: string}>} event */ async function handleRemove(event) { /** @type {{uid: Attachment['uid'], document: Attachment['document']}} */ const { uid, document } = event.detail; setFiles((prev) => prev.filter((prevFile) => prevFile.uid !== uid)); if (!document?.location) return; await Workspace.deleteAndUnembedFile(workspace.slug, document.location); } /** * Clear queue of attached files currently in prompt box */ function resetAttachments() { setFiles([]); } /** * Turns files into attachments we can send as body request to backend * for a chat. * @returns {{name:string,mime:string,contentString:string}[]} */ function parseAttachments() { return ( files ?.filter((file) => file.type === "attachment") ?.map( ( /** @type {Attachment} */ attachment ) => { return { name: attachment.file.name, mime: attachment.file.type, contentString: attachment.contentString, }; } ) || [] ); } /** * Handle pasted attachments. * @param {CustomEvent<{files: File[]}>} event */ async function handlePastedAttachment(event) { const { files = [] } = event.detail; if (!files.length) return; const newAccepted = []; for (const file of files) { if (file.type.startsWith("image/")) { newAccepted.push({ uid: v4(), file, contentString: await toBase64(file), status: "success", error: null, type: "attachment", }); } else { newAccepted.push({ uid: v4(), file, contentString: null, status: "in_progress", error: null, type: "upload", }); } } setFiles((prev) => [...prev, ...newAccepted]); embedEligibleAttachments(newAccepted); } /** * Handle dropped files. * @param {Attachment[]} acceptedFiles * @param {any[]} _rejections */ async function onDrop(acceptedFiles, _rejections) { setDragging(false); /** @type {Attachment[]} */ const newAccepted = []; for (const file of acceptedFiles) { if (file.type.startsWith("image/")) { newAccepted.push({ uid: v4(), file, contentString: await toBase64(file), status: "success", error: null, type: "attachment", }); } else { newAccepted.push({ uid: v4(), file, contentString: null, status: "in_progress", error: null, type: "upload", }); } } setFiles((prev) => [...prev, ...newAccepted]); embedEligibleAttachments(newAccepted); } /** * Embeds attachments that are eligible for embedding - basically files that are not images. * @param {Attachment[]} newAttachments */ async function embedEligibleAttachments(newAttachments = []) { window.dispatchEvent(new CustomEvent(ATTACHMENTS_PROCESSING_EVENT)); const promises = []; const { currentContextTokenCount, contextWindow } = await Workspace.getParsedFiles(workspace.slug, threadSlug); const workspaceContextWindow = contextWindow ? Math.floor(contextWindow * Workspace.maxContextWindowLimit) : Number.POSITIVE_INFINITY; setMaxTokens(workspaceContextWindow); let totalTokenCount = currentContextTokenCount; let batchPendingFiles = []; for (const attachment of newAttachments) { // Images/attachments are chat specific. if (attachment.type === "attachment") continue; const formData = new FormData(); formData.append("file", attachment.file, attachment.file.name); formData.append("threadSlug", threadSlug || null); promises.push( Workspace.parseFile(workspace.slug, formData).then( async ({ response, data }) => { if (!response.ok) { const updates = { status: "failed", error: data?.error ?? null, }; setFiles((prev) => prev.map( ( /** @type {Attachment} */ prevFile ) => prevFile.uid !== attachment.uid ? prevFile : { ...prevFile, ...updates } ) ); return; } // Will always be one file in the array /** @type {ParsedFile} */ const file = data.files[0]; // Add token count for this file // and add it to the batch pending files totalTokenCount += file.tokenCountEstimate; batchPendingFiles.push({ attachment, parsedFileId: file.id, tokenCount: file.tokenCountEstimate, }); if (totalTokenCount > workspaceContextWindow) { setTokenCount(totalTokenCount); setPendingFiles(batchPendingFiles); setShowWarningModal(true); return; } // File is within limits, keep in parsed files const result = { success: true, document: file }; const updates = { status: result.success ? "added_context" : "failed", error: result.error ?? null, document: result.document, }; setFiles((prev) => prev.map( ( /** @type {Attachment} */ prevFile ) => prevFile.uid !== attachment.uid ? prevFile : { ...prevFile, ...updates } ) ); } ) ); } // Wait for all promises to resolve in some way before dispatching the event to unlock the send button Promise.all(promises).finally(() => window.dispatchEvent(new CustomEvent(ATTACHMENTS_PROCESSED_EVENT)) ); } // Handle modal actions const handleCloseModal = async () => { if (!pendingFiles.length) return; // Delete all files from this batch await Workspace.deleteParsedFiles( workspace.slug, pendingFiles.map((file) => file.parsedFileId) ); // Remove all files from this batch from the UI setFiles((prev) => prev.filter( (prevFile) => !pendingFiles.some((file) => file.attachment.uid === prevFile.uid) ) ); setShowWarningModal(false); setPendingFiles([]); setTokenCount(0); window.dispatchEvent(new CustomEvent(ATTACHMENTS_PROCESSED_EVENT)); }; const handleContinueAnyway = async () => { if (!pendingFiles.length) return; const results = pendingFiles.map((file) => ({ success: true, document: { id: file.parsedFileId }, })); const fileUpdates = pendingFiles.map((file, i) => ({ uid: file.attachment.uid, updates: { status: results[i].success ? "success" : "failed", error: results[i].error ?? null, document: results[i].document, }, })); setFiles((prev) => prev.map((prevFile) => { const update = fileUpdates.find((f) => f.uid === prevFile.uid); return update ? { ...prevFile, ...update.updates } : prevFile; }) ); setShowWarningModal(false); setPendingFiles([]); setTokenCount(0); }; const handleEmbed = async () => { if (!pendingFiles.length) return; setIsEmbedding(true); setEmbedProgress(0); // Embed all pending files let completed = 0; const results = await Promise.all( pendingFiles.map((file) => Workspace.embedParsedFile(workspace.slug, file.parsedFileId).then( (result) => { completed++; setEmbedProgress(completed); return result; } ) ) ); // Update status for all files const fileUpdates = pendingFiles.map((file, i) => ({ uid: file.attachment.uid, updates: { status: results[i].response.ok ? "embedded" : "failed", error: results[i].data?.error ?? null, document: results[i].data?.document, }, })); setFiles((prev) => prev.map((prevFile) => { const update = fileUpdates.find((f) => f.uid === prevFile.uid); return update ? { ...prevFile, ...update.updates } : prevFile; }) ); setShowWarningModal(false); setPendingFiles([]); setTokenCount(0); setIsEmbedding(false); window.dispatchEvent(new CustomEvent(ATTACHMENTS_PROCESSED_EVENT)); showToast( `${pendingFiles.length} ${pluralize("file", pendingFiles.length)} embedded successfully`, "success" ); }; return ( <DndUploaderContext.Provider value={{ files, ready, dragging, setDragging, onDrop, parseAttachments }} > <FileUploadWarningModal show={showWarningModal} onClose={handleCloseModal} onContinue={handleContinueAnyway} onEmbed={handleEmbed} tokenCount={tokenCount} maxTokens={maxTokens} fileCount={pendingFiles.length} isEmbedding={isEmbedding} embedProgress={embedProgress} /> {children} </DndUploaderContext.Provider> ); } export default function DnDFileUploaderWrapper({ children }) { const { onDrop, ready, dragging, setDragging } = useContext(DndUploaderContext); const { getRootProps, getInputProps } = useDropzone({ onDrop, disabled: !ready, noClick: true, noKeyboard: true, onDragEnter: () => setDragging(true), onDragLeave: () => setDragging(false), }); return ( <div className={`relative flex flex-col h-full w-full md:mt-0 mt-[40px] p-[1px]`} {...getRootProps()} > <div hidden={!dragging} className="absolute top-0 w-full h-full bg-dark-text/90 light:bg-[#C2E7FE]/90 rounded-2xl border-[4px] border-white z-[9999]" > <div className="w-full h-full flex justify-center items-center rounded-xl"> <div className="flex flex-col gap-y-[14px] justify-center items-center"> <img src={DndIcon} width={69} height={69} alt="Drag and drop icon" /> <p className="text-white text-[24px] font-semibold">Add anything</p> <p className="text-white text-[16px] text-center"> Drop a file or image here to attach it to your <br /> workspace auto-magically. </p> </div> </div> </div> <input id="dnd-chat-file-uploader" {...getInputProps()} /> {children} </div> ); } /** * Convert image types into Base64 strings for requests. * @param {File} file * @returns {Promise<string>} */ async function toBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { const base64String = reader.result.split(",")[1]; resolve(`data:${file.type};base64,${base64String}`); }; reader.onerror = (error) => reject(error); reader.readAsDataURL(file); }); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/DnDWrapper/FileUploadWarningModal/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/DnDWrapper/FileUploadWarningModal/index.jsx
import { CircleNotch } from "@phosphor-icons/react"; import ModalWrapper from "@/components/ModalWrapper"; import pluralize from "pluralize"; import { numberWithCommas } from "@/utils/numbers"; import useUser from "@/hooks/useUser"; import { Link } from "react-router-dom"; import Paths from "@/utils/paths"; import Workspace from "@/models/workspace"; export default function FileUploadWarningModal({ show, onClose, onContinue, onEmbed, tokenCount, maxTokens, fileCount = 1, isEmbedding = false, embedProgress = 0, }) { const { user } = useUser(); const canEmbed = !user || user.role !== "default"; if (!show) return null; if (isEmbedding) { return ( <ModalWrapper isOpen={show}> <div className="relative max-w-[600px] bg-theme-bg-primary rounded-lg shadow border border-theme-modal-border"> <div className="p-6 flex flex-col items-center justify-center"> <p className="text-white text-lg font-semibold mb-4"> Embedding {embedProgress + 1} of {fileCount}{" "} {pluralize("file", fileCount)} </p> <CircleNotch size={32} className="animate-spin text-white" /> <p className="text-white/60 text-sm mt-2"> Please wait while we embed your files... </p> </div> </div> </ModalWrapper> ); } return ( <ModalWrapper isOpen={show}> <div className="relative max-w-[600px] bg-theme-bg-primary rounded-lg shadow border border-theme-modal-border"> <div className="relative p-6 border-b border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> Context Window Warning </h3> </div> </div> <div className="py-7 px-9 space-y-4"> <p className="text-theme-text-primary text-sm"> Your workspace is using {numberWithCommas(tokenCount)} of{" "} {numberWithCommas(maxTokens)} available tokens. We recommend keeping usage below {(Workspace.maxContextWindowLimit * 100).toFixed(0)}% to ensure the best chat experience. Adding {fileCount} more{" "} {pluralize("file", fileCount)} would exceed this limit.{" "} <Link target="_blank" to={Paths.documentation.contextWindows()} className="text-theme-text-secondary text-sm underline" > Learn more about context windows &rarr; </Link> </p> <p className="text-theme-text-primary text-sm"> Choose how you would like to proceed with these uploads. </p> </div> <div className="flex w-full justify-between items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button onClick={onClose} type="button" className="border-none transition-all duration-300 bg-theme-modal-border text-white hover:opacity-60 px-4 py-2 rounded-lg text-sm" > Cancel </button> <div className="flex w-full justify-end items-center space-x-2"> <button onClick={onContinue} type="button" className="border-none transition-all duration-300 bg-theme-modal-border text-white hover:opacity-60 px-4 py-2 rounded-lg text-sm" > Continue Anyway </button> {canEmbed && ( <button onClick={onEmbed} disabled={isEmbedding || !canEmbed} type="button" className="border-none transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > Embed {pluralize("File", fileCount)} </button> )} </div> </div> </div> </ModalWrapper> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/ChatContainer/ChatTooltips/index.jsx
frontend/src/components/WorkspaceChat/ChatContainer/ChatTooltips/index.jsx
import { Tooltip } from "react-tooltip"; import { createPortal } from "react-dom"; /** * Set the tooltips for the chat container in bulk. * Why do this? * * React-tooltip rendering on _each_ chat will attach an event listener to the body. * This will add up if we have many chats open resulting in the browser crashing * so we batch them together in a single component that renders at the top most level with * a static id the content can change, but this prevents the React-tooltip library from adding * hundreds of event listeners to the DOM. * * In general, anywhere we have iterative rendering the Tooltip should be rendered at the highest level to prevent * hundreds of event listeners from being added to the DOM in the worst case scenario. * @returns */ export function ChatTooltips() { return ( <> <Tooltip id="message-to-speech" place="bottom" delayShow={300} className="tooltip !text-xs" /> <Tooltip id="regenerate-assistant-text" place="bottom" delayShow={300} className="tooltip !text-xs" /> <Tooltip id="copy-assistant-text" place="bottom" delayShow={300} className="tooltip !text-xs" /> <Tooltip id="feedback-button" place="bottom" delayShow={300} className="tooltip !text-xs" /> <Tooltip id="action-menu" place="top" delayShow={300} className="tooltip !text-xs" /> <Tooltip id="edit-input-text" place="bottom" delayShow={300} className="tooltip !text-xs" /> <Tooltip id="metrics-visibility" place="bottom" delayShow={300} className="tooltip !text-xs" /> <Tooltip id="expand-cot" place="bottom" delayShow={300} className="tooltip !text-xs" /> <Tooltip id="cot-thinking" place="bottom" delayShow={500} className="tooltip !text-xs" /> <Tooltip id="query-refusal-info" place="top" delayShow={500} className="tooltip !text-xs max-w-[350px]" /> <Tooltip id="context-window-limit-exceeded" place="top" delayShow={500} className="tooltip !text-xs max-w-[350px]" /> <DocumentLevelTooltip /> </> ); } /** * This is a document level tooltip that is rendered at the top most level of the document * to ensure it is rendered above the chat history and other elements. Anytime we have tooltips * in modals the z-indexing can be recalculated and we need to ensure it is rendered at the top most level * so it positions correctly. */ function DocumentLevelTooltip() { return createPortal( <> <Tooltip id="similarity-score" place="top" delayShow={100} // z-[100] to ensure it renders above the chat history // as the citation modal is z-indexed above the chat history className="tooltip !text-xs z-[100]" /> </>, document.body ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/WorkspaceChat/LoadingChat/index.jsx
frontend/src/components/WorkspaceChat/LoadingChat/index.jsx
import { isMobile } from "react-device-detect"; import * as Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; export default function LoadingChat() { const highlightColor = "var(--theme-bg-primary)"; const baseColor = "var(--theme-bg-secondary)"; return ( <div className="transition-all duration-500 relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] bg-theme-bg-secondary w-full h-full overflow-y-scroll no-scroll p-4" style={{ height: "calc(100% - 32px)" }} > <Skeleton.default height="100px" width="100%" highlightColor={highlightColor} baseColor={baseColor} count={1} className="max-w-full md:max-w-[80%] p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm mt-6" containerClassName="flex justify-start" /> <Skeleton.default height="100px" width={isMobile ? "70%" : "45%"} baseColor={baseColor} highlightColor={highlightColor} count={1} className="max-w-full md:max-w-[80%] p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm mt-6" containerClassName="flex justify-end" /> <Skeleton.default height="100px" width={isMobile ? "55%" : "30%"} baseColor={baseColor} highlightColor={highlightColor} count={1} className="max-w-full md:max-w-[80%] p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm mt-6" containerClassName="flex justify-start" /> <Skeleton.default height="100px" width={isMobile ? "88%" : "25%"} baseColor={baseColor} highlightColor={highlightColor} count={1} className="max-w-full md:max-w-[80%] p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm mt-6" containerClassName="flex justify-end" /> <Skeleton.default height="160px" width="100%" baseColor={baseColor} highlightColor={highlightColor} count={1} className="max-w-full md:max-w-[80%] p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm mt-6" containerClassName="flex justify-start" /> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/ChangeWarning/index.jsx
frontend/src/components/ChangeWarning/index.jsx
import { Warning, X } from "@phosphor-icons/react"; export default function ChangeWarningModal({ warningText = "", onClose, onConfirm, }) { return ( <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden z-9999"> <div className="relative px-6 py-5 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <Warning className="text-red-500 w-6 h-6" weight="fill" /> <h3 className="text-xl font-semibold text-red-500 overflow-hidden overflow-ellipsis whitespace-nowrap"> WARNING - This action is irreversible </h3> </div> <button onClick={onClose} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={24} weight="bold" className="text-white" /> </button> </div> <div className="h-full w-full overflow-y-auto" style={{ maxHeight: "calc(100vh - 200px)" }} > <div className="py-7 px-9 space-y-2 flex-col"> <p className="text-white"> {warningText.split("\\n").map((line, index) => ( <span key={index}> {line} <br /> </span> ))} <br /> <br /> Are you sure you want to proceed? </p> </div> </div> <div className="flex w-full justify-end items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button onClick={onClose} type="button" className="transition-all duration-300 bg-transparent text-white hover:opacity-60 px-4 py-2 rounded-lg text-sm border-none" > Cancel </button> <button onClick={onConfirm} type="submit" className="transition-all duration-300 bg-red-500 light:text-white text-white hover:opacity-60 px-4 py-2 rounded-lg text-sm border-none" > Confirm </button> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/CommunityHub/UnauthenticatedHubModal/index.jsx
frontend/src/components/CommunityHub/UnauthenticatedHubModal/index.jsx
import { X } from "@phosphor-icons/react"; import { useTranslation } from "react-i18next"; import paths from "@/utils/paths"; import { Link } from "react-router-dom"; import ModalWrapper from "@/components/ModalWrapper"; export default function UnauthenticatedHubModal({ show, onClose }) { const { t } = useTranslation(); if (!show) return null; return ( <ModalWrapper isOpen={show}> <div className="relative w-[400px] max-w-full bg-theme-bg-primary rounded-lg shadow border border-theme-modal-border"> <div className="p-6"> <button onClick={onClose} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={18} weight="bold" className="text-white" /> </button> <div className="flex flex-col items-center justify-center gap-y-4"> <h3 className="text-lg font-semibold text-white"> {t("community_hub.publish.generic.unauthenticated.title")} </h3> <p className="text-lg text-white text-center max-w-[300px]"> {t("community_hub.publish.generic.unauthenticated.description")} </p> <Link to={paths.communityHub.authentication()} className="w-[265px] bg-theme-bg-secondary hover:bg-theme-sidebar-item-hover text-theme-text-primary py-2 px-4 rounded-lg transition-colors mt-4 text-sm font-semibold text-center" > {t("community_hub.publish.generic.unauthenticated.button")} </Link> </div> </div> </div> </ModalWrapper> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/CommunityHub/PublishEntityModal/index.jsx
frontend/src/components/CommunityHub/PublishEntityModal/index.jsx
import { X } from "@phosphor-icons/react"; import { useCommunityHubAuth } from "@/hooks/useCommunityHubAuth"; import UnauthenticatedHubModal from "@/components/CommunityHub/UnauthenticatedHubModal"; import SystemPrompts from "./SystemPrompts"; import ModalWrapper from "@/components/ModalWrapper"; import AgentFlows from "./AgentFlows"; import SlashCommands from "./SlashCommands"; export default function PublishEntityModal({ show, onClose, entityType, entity, }) { const { isAuthenticated, loading } = useCommunityHubAuth(); if (!show || loading) return null; if (!isAuthenticated) return <UnauthenticatedHubModal show={show} onClose={onClose} />; const renderEntityForm = () => { switch (entityType) { case "system-prompt": return <SystemPrompts entity={entity} />; case "agent-flow": return <AgentFlows entity={entity} />; case "slash-command": return <SlashCommands entity={entity} />; default: return null; } }; return ( <ModalWrapper isOpen={show}> <div className="relative max-w-[900px] bg-theme-bg-primary rounded-lg shadow border border-theme-modal-border"> <div className="relative p-6"> <button onClick={onClose} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={18} weight="bold" className="text-white" /> </button> </div> {renderEntityForm()} </div> </ModalWrapper> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/CommunityHub/PublishEntityModal/SlashCommands/index.jsx
frontend/src/components/CommunityHub/PublishEntityModal/SlashCommands/index.jsx
import { useState, useRef } from "react"; import { useTranslation } from "react-i18next"; import CommunityHub from "@/models/communityHub"; import showToast from "@/utils/toast"; import paths from "@/utils/paths"; import { X } from "@phosphor-icons/react"; import { Link } from "react-router-dom"; export default function SlashCommands({ entity }) { const { t } = useTranslation(); const formRef = useRef(null); const [isSubmitting, setIsSubmitting] = useState(false); const [tags, setTags] = useState([]); const [tagInput, setTagInput] = useState(""); const [visibility, setVisibility] = useState("public"); const [isSuccess, setIsSuccess] = useState(false); const [itemId, setItemId] = useState(null); const handleSubmit = async (e) => { e.preventDefault(); e.stopPropagation(); setIsSubmitting(true); try { const form = new FormData(formRef.current); const data = { name: form.get("name"), description: form.get("description"), command: entity.command, prompt: form.get("prompt"), tags: tags, visibility: visibility, }; const { success, error, itemId } = await CommunityHub.createSlashCommand(data); if (!success) throw new Error(error); setItemId(itemId); setIsSuccess(true); } catch (error) { console.error("Failed to publish slash command:", error); showToast(`Failed to publish slash command: ${error.message}`, "error", { clear: true, }); } finally { setIsSubmitting(false); } }; const handleKeyDown = (e) => { if (e.key === "Enter" || e.key === ",") { e.preventDefault(); const value = tagInput.trim(); if (value.length > 20) return; if (value && !tags.includes(value)) { setTags((prevTags) => [...prevTags, value].slice(0, 5)); // Limit to 5 tags setTagInput(""); } } }; const removeTag = (tagToRemove) => { setTags(tags.filter((tag) => tag !== tagToRemove)); }; if (isSuccess) { return ( <div className="p-6 -mt-12 w-[400px]"> <div className="flex flex-col items-center justify-center gap-y-2"> <h3 className="text-lg font-semibold text-theme-text-primary"> {t("community_hub.publish.slash_command.success_title")} </h3> <p className="text-lg text-theme-text-primary text-center max-w-2xl"> {t("community_hub.publish.slash_command.success_description")} </p> <p className="text-theme-text-secondary text-center text-sm"> {t("community_hub.publish.slash_command.success_thank_you")} </p> <Link to={paths.communityHub.viewItem("slash-command", itemId)} target="_blank" rel="noreferrer" className="w-[265px] bg-theme-bg-secondary hover:bg-theme-sidebar-item-hover text-theme-text-primary py-2 px-4 rounded-lg transition-colors mt-4 text-sm font-semibold text-center" > {t("community_hub.publish.slash_command.view_on_hub")} </Link> </div> </div> ); } return ( <> <div className="w-full flex gap-x-2 items-center mb-3 -mt-8"> <h3 className="text-xl font-semibold text-theme-text-primary px-6 py-3 flex items-center gap-x-2"> {t("community_hub.publish.slash_command.modal_title")} <code className="bg-theme-bg-secondary rounded-lg px-1 text-theme-text-secondary text-lg font-mono"> {entity.command} </code> </h3> </div> <form ref={formRef} className="flex" onSubmit={handleSubmit}> <div className="w-1/2 p-6 pt-0 space-y-4"> <div> <label className="block text-sm font-semibold text-theme-text-primary mb-1"> {t("community_hub.publish.slash_command.name_label")} </label> <div className="text-xs text-theme-text-secondary mb-2"> {t("community_hub.publish.slash_command.name_description")} </div> <input type="text" name="name" required minLength={3} maxLength={300} defaultValue={entity.name} placeholder={t( "community_hub.publish.slash_command.name_placeholder" )} className="border-none w-full bg-theme-bg-secondary rounded-lg p-2 text-theme-text-primary text-sm focus:outline-primary-button active:outline-primary-button outline-none placeholder:text-theme-text-placeholder" /> </div> <div> <label className="block text-sm font-semibold text-theme-text-primary mb-1"> {t("community_hub.publish.slash_command.description_label")} </label> <div className="text-xs text-white/60 mb-2"> {t("community_hub.publish.slash_command.description_description")} </div> <textarea name="description" required minLength={10} maxLength={1000} defaultValue={entity.description} placeholder={t( "community_hub.publish.slash_command.description_description" )} className="border-none w-full bg-theme-bg-secondary rounded-lg p-2 text-white text-sm focus:outline-primary-button active:outline-primary-button outline-none min-h-[80px] placeholder:text-theme-text-placeholder" /> </div> <div> <label className="block text-sm font-semibold text-white mb-1"> {t("community_hub.publish.slash_command.tags_label")} </label> <div className="text-xs text-white/60 mb-2"> {t("community_hub.publish.slash_command.tags_description")} </div> <div className="flex flex-wrap gap-2 p-2 bg-theme-bg-secondary rounded-lg min-h-[42px]"> {tags.map((tag, index) => ( <span key={index} className="flex items-center gap-1 px-2 py-1 text-sm text-theme-text-primary bg-white/10 light:bg-black/10 rounded-md" > {tag} <button type="button" onClick={() => removeTag(tag)} className="border-none text-theme-text-primary hover:text-theme-text-secondary cursor-pointer" > <X size={14} /> </button> </span> ))} <input type="text" value={tagInput} onChange={(e) => setTagInput(e.target.value)} onKeyDown={handleKeyDown} placeholder={t( "community_hub.publish.slash_command.tags_placeholder" )} className="flex-1 min-w-[200px] border-none text-sm bg-transparent text-theme-text-primary placeholder:text-theme-text-placeholder p-0 h-[24px] focus:outline-none" /> </div> </div> <div> <label className="block text-sm font-semibold text-white mb-1"> {t("community_hub.publish.slash_command.visibility_label")} </label> <div className="text-xs text-white/60 mb-2"> {visibility === "public" ? t("community_hub.publish.slash_command.public_description") : t("community_hub.publish.slash_command.private_description")} </div> <div className="w-fit h-[42px] bg-theme-bg-secondary rounded-lg p-0.5"> <div className="flex items-center" role="group"> <input type="radio" id="public" name="visibility" value="public" className="peer/public hidden" defaultChecked onChange={(e) => setVisibility(e.target.value)} /> <input type="radio" id="private" name="visibility" value="private" className="peer/private hidden" onChange={(e) => setVisibility(e.target.value)} /> <label htmlFor="public" className="h-[36px] px-4 rounded-lg text-sm font-medium transition-all duration-200 cursor-pointer text-theme-text-primary hover:text-theme-text-secondary peer-checked/public:bg-theme-sidebar-item-hover peer-checked/public:text-theme-primary-button flex items-center justify-center" > Public </label> <label htmlFor="private" className="h-[36px] px-4 rounded-lg text-sm font-medium transition-all duration-200 cursor-pointer text-theme-text-primary hover:text-theme-text-secondary peer-checked/private:bg-theme-sidebar-item-hover peer-checked/private:text-theme-primary-button flex items-center justify-center" > Private </label> </div> </div> </div> </div> <div className="w-1/2 p-6 pt-0 space-y-4"> <div> <label className="block text-sm font-semibold text-white mb-1"> {t("community_hub.publish.slash_command.prompt_label")} </label> <div className="text-xs text-white/60 mb-2"> {t("community_hub.publish.slash_command.prompt_description")} </div> <textarea name="prompt" required minLength={10} defaultValue={entity.prompt} placeholder={t( "community_hub.publish.slash_command.prompt_placeholder" )} className="border-none w-full bg-theme-bg-secondary rounded-lg p-2 text-white text-sm focus:outline-primary-button active:outline-primary-button outline-none min-h-[300px] placeholder:text-theme-text-placeholder" /> </div> <button type="submit" disabled={isSubmitting} className="border-none w-full bg-cta-button hover:opacity-80 text-theme-text-primary font-medium py-2 px-4 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed" > {isSubmitting ? t("community_hub.publish.slash_command.submitting") : t("community_hub.publish.slash_command.publish_button")} </button> </div> </form> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/CommunityHub/PublishEntityModal/AgentFlows/index.jsx
frontend/src/components/CommunityHub/PublishEntityModal/AgentFlows/index.jsx
import { useState, useRef } from "react"; import { useTranslation } from "react-i18next"; import CommunityHub from "@/models/communityHub"; import showToast from "@/utils/toast"; import paths from "@/utils/paths"; import { X, CaretRight } from "@phosphor-icons/react"; import { BLOCK_INFO } from "@/pages/Admin/AgentBuilder/BlockList"; import { Link } from "react-router-dom"; export default function AgentFlows({ entity }) { const { t } = useTranslation(); const formRef = useRef(null); const [isSubmitting, setIsSubmitting] = useState(false); const [tags, setTags] = useState([]); const [tagInput, setTagInput] = useState(""); const [isSuccess, setIsSuccess] = useState(false); const [itemId, setItemId] = useState(null); const [expandedStep, setExpandedStep] = useState(null); const handleSubmit = async (e) => { e.preventDefault(); e.stopPropagation(); setIsSubmitting(true); try { const form = new FormData(formRef.current); const data = { name: form.get("name"), description: form.get("description"), tags: tags, visibility: "private", flow: JSON.stringify({ name: form.get("name"), description: form.get("description"), steps: entity.steps, tags: tags, visibility: "private", }), }; const { success, error, itemId } = await CommunityHub.createAgentFlow(data); if (!success) throw new Error(error); setItemId(itemId); setIsSuccess(true); } catch (error) { console.error("Failed to publish agent flow:", error); showToast(`Failed to publish agent flow: ${error.message}`, "error", { clear: true, }); } finally { setIsSubmitting(false); } }; const handleKeyDown = (e) => { if (e.key === "Enter" || e.key === ",") { e.preventDefault(); const value = tagInput.trim(); if (value.length > 20) return; if (value && !tags.includes(value)) { setTags((prevTags) => [...prevTags, value].slice(0, 5)); // Limit to 5 tags setTagInput(""); } } }; const removeTag = (tagToRemove) => { setTags(tags.filter((tag) => tag !== tagToRemove)); }; if (isSuccess) { return ( <div className="p-6 -mt-12 w-[400px]"> <div className="flex flex-col items-center justify-center gap-y-2"> <h3 className="text-lg font-semibold text-theme-text-primary"> {t("community_hub.publish.agent_flow.success_title")} </h3> <p className="text-lg text-theme-text-primary text-center max-w-2xl"> {t("community_hub.publish.agent_flow.success_description")} </p> <p className="text-theme-text-secondary text-center text-sm"> {t("community_hub.publish.agent_flow.success_thank_you")} </p> <Link to={paths.communityHub.viewItem("agent-flow", itemId)} target="_blank" rel="noreferrer" className="w-[265px] bg-theme-bg-secondary hover:bg-theme-sidebar-item-hover text-theme-text-primary py-2 px-4 rounded-lg transition-colors mt-4 text-sm font-semibold text-center" > {t("community_hub.publish.agent_flow.view_on_hub")} </Link> </div> </div> ); } return ( <> <div className="w-full flex gap-x-2 items-center mb-3 -mt-8"> <h3 className="text-xl font-semibold text-theme-text-primary px-6 py-3"> {t("community_hub.publish.agent_flow.modal_title")} </h3> </div> <form ref={formRef} className="flex" onSubmit={handleSubmit}> <div className="w-1/2 p-6 pt-0 space-y-4"> <div> <label className="block text-sm font-semibold text-theme-text-primary mb-1"> {t("community_hub.publish.agent_flow.name_label")} </label> <div className="text-xs text-theme-text-secondary mb-2"> {t("community_hub.publish.agent_flow.name_description")} </div> <input type="text" name="name" required minLength={3} maxLength={300} defaultValue={entity.name} placeholder={t( "community_hub.publish.agent_flow.name_placeholder" )} className="border-none w-full bg-theme-bg-secondary rounded-lg p-2 text-theme-text-primary text-sm focus:outline-primary-button active:outline-primary-button outline-none placeholder:text-theme-text-placeholder" /> </div> <div> <label className="block text-sm font-semibold text-theme-text-primary mb-1"> {t("community_hub.publish.agent_flow.description_label")} </label> <div className="text-xs text-white/60 mb-2"> {t("community_hub.publish.agent_flow.description_description")} </div> <textarea name="description" required minLength={10} maxLength={1000} defaultValue={entity.description} placeholder={t( "community_hub.publish.agent_flow.description_description" )} className="border-none w-full bg-theme-bg-secondary rounded-lg p-2 text-white text-sm focus:outline-primary-button active:outline-primary-button outline-none min-h-[80px] placeholder:text-theme-text-placeholder" /> </div> <div> <label className="block text-sm font-semibold text-white mb-1"> {t("community_hub.publish.agent_flow.tags_label")} </label> <div className="text-xs text-white/60 mb-2"> {t("community_hub.publish.agent_flow.tags_description")} </div> <div className="flex flex-wrap gap-2 p-2 bg-theme-bg-secondary rounded-lg min-h-[42px]"> {tags.map((tag, index) => ( <span key={index} className="flex items-center gap-1 px-2 py-1 text-sm text-theme-text-primary bg-white/10 light:bg-black/10 rounded-md" > {tag} <button type="button" onClick={() => removeTag(tag)} className="border-none text-theme-text-primary hover:text-theme-text-secondary cursor-pointer" > <X size={14} /> </button> </span> ))} <input type="text" value={tagInput} onChange={(e) => setTagInput(e.target.value)} onKeyDown={handleKeyDown} placeholder={t( "community_hub.publish.agent_flow.tags_placeholder" )} className="flex-1 min-w-[200px] border-none text-sm bg-transparent text-theme-text-primary placeholder:text-theme-text-placeholder p-0 h-[24px] focus:outline-none" /> </div> </div> <div> <label className="block text-sm font-semibold text-white"> {t("community_hub.publish.agent_flow.visibility_label")} </label> <span className="text-xs text-theme-text-secondary"> {t("community_hub.publish.agent_flow.privacy_note")} </span> </div> </div> <div className="w-1/2 p-6 pt-0 flex flex-col gap-y-4"> <div> <label className="block text-sm font-semibold text-theme-text-primary mb-1"> Flow Steps </label> <div className="text-xs text-white/60"> The steps the agent will follow when the flow is triggered. </div> </div> <div className="flex flex-col gap-y-0.5"> {entity.steps && entity.steps.length > 0 ? ( entity.steps.map((step, idx) => { const info = BLOCK_INFO[step.type]; const isExpanded = expandedStep === idx; const summary = info?.getSummary ? info.getSummary(step.config) : ""; return ( <div key={idx} className="flex flex-col items-center w-full"> <div className="flex flex-col bg-theme-bg-secondary rounded-lg px-3 py-2 w-full cursor-pointer group" onClick={() => setExpandedStep(isExpanded ? null : idx)} > <div className="flex items-center gap-x-3 w-full"> <span>{info?.icon}</span> <span className="text-theme-text-primary text-sm font-medium flex-1"> {info?.label || step.type} </span> {!isExpanded && ( <span className="text-theme-text-secondary text-xs ml-2 overflow-hidden text-ellipsis whitespace-nowrap max-w-[120px] min-w-0"> {summary} </span> )} <span className={`ml-2 text-theme-text-secondary transition-transform duration-200 ${isExpanded ? "rotate-90" : ""}`} > <CaretRight size={16} /> </span> </div> {isExpanded && summary && ( <div className="w-full text-theme-text-secondary text-xs mt-1 whitespace-pre-line break-words"> {summary} </div> )} </div> {idx < entity.steps.length - 1 && ( <span className="text-theme-text-secondary text-lg my-1"> ↓ </span> )} </div> ); }) ) : ( <div className="text-theme-text-secondary text-xs"> No steps defined. </div> )} </div> <button type="submit" disabled={isSubmitting} className="border-none mt-4 w-full bg-cta-button hover:opacity-80 text-theme-text-primary font-medium py-2 px-4 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed" > {isSubmitting ? t("community_hub.publish.agent_flow.submitting") : t("community_hub.publish.agent_flow.submit")} </button> </div> </form> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/CommunityHub/PublishEntityModal/SystemPrompts/index.jsx
frontend/src/components/CommunityHub/PublishEntityModal/SystemPrompts/index.jsx
import { useState, useRef } from "react"; import { useTranslation } from "react-i18next"; import CommunityHub from "@/models/communityHub"; import showToast from "@/utils/toast"; import paths from "@/utils/paths"; import { X } from "@phosphor-icons/react"; import { Link } from "react-router-dom"; export default function SystemPrompts({ entity }) { const { t } = useTranslation(); const formRef = useRef(null); const [isSubmitting, setIsSubmitting] = useState(false); const [tags, setTags] = useState([]); const [tagInput, setTagInput] = useState(""); const [visibility, setVisibility] = useState("public"); const [isSuccess, setIsSuccess] = useState(false); const [itemId, setItemId] = useState(null); const handleSubmit = async (e) => { e.preventDefault(); e.stopPropagation(); setIsSubmitting(true); try { const form = new FormData(formRef.current); const data = { name: form.get("name"), description: form.get("description"), prompt: form.get("prompt"), tags: tags, visibility: visibility, }; const { success, error, itemId } = await CommunityHub.createSystemPrompt(data); if (!success) throw new Error(error); setItemId(itemId); setIsSuccess(true); } catch (error) { console.error("Failed to publish prompt:", error); showToast(`Failed to publish prompt: ${error.message}`, "error", { clear: true, }); } finally { setIsSubmitting(false); } }; const handleKeyDown = (e) => { if (e.key === "Enter" || e.key === ",") { e.preventDefault(); const value = tagInput.trim(); if (value.length > 20) return; if (value && !tags.includes(value)) { setTags((prevTags) => [...prevTags, value].slice(0, 5)); // Limit to 5 tags setTagInput(""); } } }; const removeTag = (tagToRemove) => { setTags(tags.filter((tag) => tag !== tagToRemove)); }; if (isSuccess) { return ( <div className="p-6 -mt-12 w-[400px]"> <div className="flex flex-col items-center justify-center gap-y-2"> <h3 className="text-lg font-semibold text-theme-text-primary"> {t("community_hub.publish.system_prompt.success_title")} </h3> <p className="text-lg text-theme-text-primary text-center max-w-2xl"> {t("community_hub.publish.system_prompt.success_description")} </p> <p className="text-theme-text-secondary text-center text-sm"> {t("community_hub.publish.system_prompt.success_thank_you")} </p> <Link to={paths.communityHub.viewItem("system-prompt", itemId)} target="_blank" rel="noreferrer" className="w-[265px] bg-theme-bg-secondary hover:bg-theme-sidebar-item-hover text-theme-text-primary py-2 px-4 rounded-lg transition-colors mt-4 text-sm font-semibold text-center" > {t("community_hub.publish.system_prompt.view_on_hub")} </Link> </div> </div> ); } return ( <> <div className="w-full flex gap-x-2 items-center mb-3 -mt-8"> <h3 className="text-xl font-semibold text-theme-text-primary px-6 py-3"> {t(`community_hub.publish.system_prompt.modal_title`)} </h3> </div> <form ref={formRef} className="flex" onSubmit={handleSubmit}> <div className="w-1/2 p-6 pt-0 space-y-4"> <div> <label className="block text-sm font-semibold text-theme-text-primary mb-1"> {t("community_hub.publish.system_prompt.name_label")} </label> <div className="text-xs text-theme-text-secondary mb-2"> {t("community_hub.publish.system_prompt.name_description")} </div> <input type="text" name="name" required minLength={3} maxLength={300} placeholder={t( "community_hub.publish.system_prompt.name_placeholder" )} className="border-none w-full bg-theme-bg-secondary rounded-lg p-2 text-theme-text-primary text-sm focus:outline-primary-button active:outline-primary-button outline-none placeholder:text-theme-text-placeholder" /> </div> <div> <label className="block text-sm font-semibold text-theme-text-primary mb-1"> {t("community_hub.publish.system_prompt.description_label")} </label> <div className="text-xs text-white/60 mb-2"> {t("community_hub.publish.system_prompt.description_description")} </div> <textarea name="description" required minLength={10} maxLength={1000} placeholder={t( "community_hub.publish.system_prompt.description_description" )} className="border-none w-full bg-theme-bg-secondary rounded-lg p-2 text-white text-sm focus:outline-primary-button active:outline-primary-button outline-none min-h-[80px] placeholder:text-theme-text-placeholder" /> </div> <div> <label className="block text-sm font-semibold text-white mb-1"> {t("community_hub.publish.system_prompt.tags_label")} </label> <div className="text-xs text-white/60 mb-2"> {t("community_hub.publish.system_prompt.tags_description")} </div> <div className="flex flex-wrap gap-2 p-2 bg-theme-bg-secondary rounded-lg min-h-[42px]"> {tags.map((tag, index) => ( <span key={index} className="flex items-center gap-1 px-2 py-1 text-sm text-theme-text-primary bg-white/10 light:bg-black/10 rounded-md" > {tag} <button type="button" onClick={() => removeTag(tag)} className="border-none text-theme-text-primary hover:text-theme-text-secondary cursor-pointer" > <X size={14} /> </button> </span> ))} <input type="text" value={tagInput} onChange={(e) => setTagInput(e.target.value)} onKeyDown={handleKeyDown} placeholder={t( "community_hub.publish.system_prompt.tags_placeholder" )} className="flex-1 min-w-[200px] border-none text-sm bg-transparent text-theme-text-primary placeholder:text-theme-text-placeholder p-0 h-[24px] focus:outline-none" /> </div> </div> <div> <label className="block text-sm font-semibold text-white mb-1"> {t("community_hub.publish.system_prompt.visibility_label")} </label> <div className="text-xs text-white/60 mb-2"> {visibility === "public" ? t("community_hub.publish.system_prompt.public_description") : t("community_hub.publish.system_prompt.private_description")} </div> <div className="w-fit h-[42px] bg-theme-bg-secondary rounded-lg p-0.5"> <div className="flex items-center" role="group"> <input type="radio" id="public" name="visibility" value="public" className="peer/public hidden" defaultChecked onChange={(e) => setVisibility(e.target.value)} /> <input type="radio" id="private" name="visibility" value="private" className="peer/private hidden" onChange={(e) => setVisibility(e.target.value)} /> <label htmlFor="public" className="h-[36px] px-4 rounded-lg text-sm font-medium transition-all duration-200 cursor-pointer text-theme-text-primary hover:text-theme-text-secondary peer-checked/public:bg-theme-sidebar-item-hover peer-checked/public:text-theme-primary-button flex items-center justify-center" > Public </label> <label htmlFor="private" className="h-[36px] px-4 rounded-lg text-sm font-medium transition-all duration-200 cursor-pointer text-theme-text-primary hover:text-theme-text-secondary peer-checked/private:bg-theme-sidebar-item-hover peer-checked/private:text-theme-primary-button flex items-center justify-center" > Private </label> </div> </div> </div> </div> <div className="w-1/2 p-6 pt-0 space-y-4"> <div> <label className="block text-sm font-semibold text-white mb-1"> {t("community_hub.publish.system_prompt.prompt_label")} </label> <div className="text-xs text-white/60 mb-2"> {t("community_hub.publish.system_prompt.prompt_description")} </div> <textarea name="prompt" required minLength={10} defaultValue={entity} placeholder={t( "community_hub.publish.system_prompt.prompt_placeholder" )} className="border-none w-full bg-theme-bg-secondary rounded-lg p-2 text-white text-sm focus:outline-primary-button active:outline-primary-button outline-none min-h-[300px] placeholder:text-theme-text-placeholder" /> </div> <button type="submit" disabled={isSubmitting} className="border-none w-full bg-cta-button hover:opacity-80 text-theme-text-primary font-medium py-2 px-4 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed" > {isSubmitting ? t("community_hub.publish.system_prompt.submitting") : t("community_hub.publish.system_prompt.publish_button")} </button> </div> </form> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/ChatBubble/index.jsx
frontend/src/components/ChatBubble/index.jsx
import React from "react"; import UserIcon from "../UserIcon"; import { userFromStorage } from "@/utils/request"; import renderMarkdown from "@/utils/chat/markdown"; import DOMPurify from "@/utils/chat/purify"; export default function ChatBubble({ message, type, popMsg }) { const isUser = type === "user"; return ( <div className={`flex justify-center items-end w-full bg-theme-bg-secondary`} > <div className={`py-8 px-4 w-full flex gap-x-5 md:max-w-[80%] flex-col`}> <div className="flex gap-x-5"> <UserIcon user={{ uid: isUser ? userFromStorage()?.username : "system" }} role={type} /> <div className={`markdown whitespace-pre-line text-white font-normal text-sm md:text-sm flex flex-col gap-y-1 mt-2`} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(renderMarkdown(message)), }} /> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/lib/CTAButton/index.jsx
frontend/src/components/lib/CTAButton/index.jsx
export default function CTAButton({ children, disabled = false, onClick, className = "", }) { return ( <button disabled={disabled} onClick={() => onClick?.()} className={`border-none text-xs px-4 py-1 font-semibold light:text-[#ffffff] rounded-lg bg-primary-button hover:bg-secondary hover:text-white h-[34px] -mr-8 whitespace-nowrap w-fit ${className}`} > <div className="flex items-center justify-center gap-2">{children}</div> </button> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/ErrorBoundaryFallback/index.jsx
frontend/src/components/ErrorBoundaryFallback/index.jsx
import { NavLink } from "react-router-dom"; import { House, ArrowClockwise, Copy, Check } from "@phosphor-icons/react"; import { useState } from "react"; export default function ErrorBoundaryFallback({ error, resetErrorBoundary }) { const [copied, setCopied] = useState(false); const copyErrorDetails = async () => { const details = { url: window.location.href, error: error?.name || "Unknown Error", message: error?.message || "No message available", stack: error?.stack || "No stack trace available", userAgent: navigator.userAgent, timestamp: new Date().toISOString(), }; const formattedDetails = ` Error Report ============ Timestamp: ${details.timestamp} URL: ${details.url} User Agent: ${details.userAgent} Error: ${details.error} Message: ${details.message} Stack Trace: ${details.stack} `.trim(); try { await navigator.clipboard.writeText(formattedDetails); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (err) { console.error("Failed to copy error details:", err); } }; return ( <div className="flex flex-col items-center justify-center min-h-screen bg-theme-bg-primary text-theme-text-primary gap-4 p-4 md:p-8 w-full"> <h1 className="text-xl md:text-2xl font-bold text-center"> An error occurred. </h1> <p className="text-theme-text-secondary text-center px-4"> {error?.message} </p> {import.meta.env.DEV && ( <div className="w-full max-w-4xl"> <div className="flex justify-end mb-2"> <button onClick={copyErrorDetails} className="flex items-center gap-2 px-3 py-1.5 bg-theme-bg-secondary text-theme-text-primary rounded hover:bg-theme-sidebar-item-hover transition-all duration-200 text-xs font-medium" title="Copy error details" > {copied ? ( <> <Check className="w-3.5 h-3.5" weight="bold" /> Copied! </> ) : ( <> <Copy className="w-3.5 h-3.5" /> Copy Details </> )} </button> </div> <pre className="w-full text-xs md:text-sm text-theme-text-secondary bg-theme-bg-secondary p-4 md:p-6 rounded-lg overflow-x-auto overflow-y-auto max-h-[60vh] md:max-h-[70vh] whitespace-pre-wrap break-words font-mono border border-theme-border shadow-sm"> {error?.stack} </pre> </div> )} <div className="flex flex-col md:flex-row gap-3 md:gap-4 mt-4 w-full md:w-auto"> <button onClick={resetErrorBoundary} className="flex items-center justify-center gap-2 px-4 py-2 bg-theme-bg-secondary text-theme-text-primary rounded-lg hover:bg-theme-sidebar-item-hover transition-all duration-300 w-full md:w-auto" > <ArrowClockwise className="w-4 h-4" /> Reset </button> <NavLink to="/" className="flex items-center justify-center gap-2 px-4 py-2 bg-theme-bg-secondary text-theme-text-primary rounded-lg hover:bg-theme-sidebar-item-hover transition-all duration-300 w-full md:w-auto" > <House className="w-4 h-4" /> Home </NavLink> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/SpeechToText/BrowserNative/index.jsx
frontend/src/components/SpeechToText/BrowserNative/index.jsx
export default function BrowserNative() { return ( <div className="w-full h-10 items-center flex"> <p className="text-sm font-base text-white text-opacity-60"> There is no configuration needed for this provider. </p> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/ContextualSaveBar/index.jsx
frontend/src/components/ContextualSaveBar/index.jsx
import { Warning } from "@phosphor-icons/react"; export default function ContextualSaveBar({ showing = false, onSave, onCancel, }) { if (!showing) return null; return ( <div className="fixed top-0 left-0 right-0 h-14 bg-dark-input flex items-center justify-end px-4 z-[999]"> <div className="absolute ml-4 left-0 md:left-1/2 transform md:-translate-x-1/2 flex items-center gap-x-2"> <Warning size={18} className="text-[#FFFFFF]" /> <p className="text-[#FFFFFF] font-medium text-xs">Unsaved Changes</p> </div> <div className="flex items-center gap-x-2"> <button className="border-none text-theme-text-primary font-medium text-sm px-[10px] py-[6px] rounded-md bg-theme-bg-secondary hover:bg-theme-bg-primary" onClick={onCancel} > Cancel </button> <button className="border-none text-theme-text-primary font-medium text-sm px-[10px] py-[6px] rounded-md bg-primary-button hover:bg-primary-button-hover" onClick={onSave} > Save </button> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/NewWorkspace.jsx
frontend/src/components/Modals/NewWorkspace.jsx
import React, { useRef, useState } from "react"; import { X } from "@phosphor-icons/react"; import Workspace from "@/models/workspace"; import paths from "@/utils/paths"; import { useTranslation } from "react-i18next"; import ModalWrapper from "@/components/ModalWrapper"; const noop = () => false; export default function NewWorkspaceModal({ hideModal = noop }) { const formEl = useRef(null); const [error, setError] = useState(null); const { t } = useTranslation(); const handleCreate = async (e) => { setError(null); e.preventDefault(); const data = {}; const form = new FormData(formEl.current); for (var [key, value] of form.entries()) data[key] = value; const { workspace, message } = await Workspace.new(data); if (!!workspace) { window.location.href = paths.workspace.chat(workspace.slug); } setError(message); }; return ( <ModalWrapper isOpen={true}> <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> {t("new-workspace.title")} </h3> </div> <button onClick={hideModal} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={24} weight="bold" className="text-white" /> </button> </div> <div className="h-full w-full overflow-y-auto" style={{ maxHeight: "calc(100vh - 200px)" }} > <form ref={formEl} onSubmit={handleCreate}> <div className="py-7 px-9 space-y-2 flex-col"> <div className="w-full flex flex-col gap-y-4"> <div> <label htmlFor="name" className="block mb-2 text-sm font-medium text-white" > {t("common.workspaces-name")} </label> <input name="name" type="text" id="name" className="border-none bg-theme-settings-input-bg w-full text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder={t("new-workspace.placeholder")} required={true} autoComplete="off" autoFocus={true} /> </div> {error && ( <p className="text-red-400 text-sm">Error: {error}</p> )} </div> </div> <div className="flex w-full justify-end items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button type="submit" className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > Save </button> </div> </form> </div> </div> </ModalWrapper> ); } export function useNewWorkspaceModal() { const [showing, setShowing] = useState(false); const showModal = () => { setShowing(true); }; const hideModal = () => { setShowing(false); }; return { showing, showModal, hideModal }; }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/Password/index.jsx
frontend/src/components/Modals/Password/index.jsx
import React, { useState, useEffect } from "react"; import System from "../../../models/system"; import SingleUserAuth from "./SingleUserAuth"; import MultiUserAuth from "./MultiUserAuth"; import { AUTH_TOKEN, AUTH_USER, AUTH_TIMESTAMP, } from "../../../utils/constants"; import useLogo from "../../../hooks/useLogo"; import illustration from "@/media/illustrations/login-illustration.svg"; export default function PasswordModal({ mode = "single" }) { const { loginLogo } = useLogo(); return ( <div className="fixed top-0 left-0 right-0 z-50 w-full overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] h-full bg-theme-bg-primary flex flex-col md:flex-row items-center justify-center"> <div style={{ background: ` radial-gradient(circle at center, transparent 40%, black 100%), linear-gradient(180deg, #85F8FF 0%, #65A6F2 100%) `, width: "575px", filter: "blur(150px)", opacity: "0.4", }} className="absolute left-0 top-0 z-0 h-full w-full" /> <div className="hidden md:flex md:w-1/2 md:h-full md:items-center md:justify-center"> <img className="w-full h-full object-contain z-50" src={illustration} alt="login illustration" /> </div> <div className="flex flex-col items-center justify-center h-full w-full md:w-1/2 z-50 relative md:-mt-20 mt-0 !border-none bg-theme-bg-secondary md:bg-transparent"> <img src={loginLogo} alt="Logo" className={`hidden relative md:flex rounded-2xl w-fit m-4 z-30 ${ mode === "single" ? "md:top-2" : "md:top-12" } absolute max-h-[65px]`} style={{ objectFit: "contain" }} /> {mode === "single" ? <SingleUserAuth /> : <MultiUserAuth />} </div> </div> ); } export function usePasswordModal(notry = false) { const [auth, setAuth] = useState({ loading: true, requiresAuth: false, mode: "single", }); useEffect(() => { async function checkAuthReq() { if (!window) return; // If the last validity check is still valid // we can skip the loading. if (!System.needsAuthCheck() && notry === false) { setAuth({ loading: false, requiresAuth: false, mode: "multi", }); return; } const settings = await System.keys(); if (settings?.MultiUserMode) { const currentToken = window.localStorage.getItem(AUTH_TOKEN); if (!!currentToken) { const valid = notry ? false : await System.checkAuth(currentToken); if (!valid) { setAuth({ loading: false, requiresAuth: true, mode: "multi", }); window.localStorage.removeItem(AUTH_USER); window.localStorage.removeItem(AUTH_TOKEN); window.localStorage.removeItem(AUTH_TIMESTAMP); return; } else { setAuth({ loading: false, requiresAuth: false, mode: "multi", }); return; } } else { setAuth({ loading: false, requiresAuth: true, mode: "multi", }); return; } } else { // Running token check in single user Auth mode. // If Single user Auth is disabled - skip check const requiresAuth = settings?.RequiresAuth || false; if (!requiresAuth) { setAuth({ loading: false, requiresAuth: false, mode: "single", }); return; } const currentToken = window.localStorage.getItem(AUTH_TOKEN); if (!!currentToken) { const valid = notry ? false : await System.checkAuth(currentToken); if (!valid) { setAuth({ loading: false, requiresAuth: true, mode: "single", }); window.localStorage.removeItem(AUTH_TOKEN); window.localStorage.removeItem(AUTH_USER); window.localStorage.removeItem(AUTH_TIMESTAMP); return; } else { setAuth({ loading: false, requiresAuth: false, mode: "single", }); return; } } else { setAuth({ loading: false, requiresAuth: true, mode: "single", }); return; } } } checkAuthReq(); }, []); return auth; }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/Password/SingleUserAuth.jsx
frontend/src/components/Modals/Password/SingleUserAuth.jsx
import React, { useEffect, useState } from "react"; import System from "../../../models/system"; import { AUTH_TOKEN } from "../../../utils/constants"; import paths from "../../../utils/paths"; import ModalWrapper from "@/components/ModalWrapper"; import { useModal } from "@/hooks/useModal"; import RecoveryCodeModal from "@/components/Modals/DisplayRecoveryCodeModal"; import { useTranslation } from "react-i18next"; export default function SingleUserAuth() { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [recoveryCodes, setRecoveryCodes] = useState([]); const [downloadComplete, setDownloadComplete] = useState(false); const [token, setToken] = useState(null); const [customAppName, setCustomAppName] = useState(null); const { isOpen: isRecoveryCodeModalOpen, openModal: openRecoveryCodeModal, closeModal: closeRecoveryCodeModal, } = useModal(); const handleLogin = async (e) => { setError(null); setLoading(true); e.preventDefault(); const data = {}; const form = new FormData(e.target); for (var [key, value] of form.entries()) data[key] = value; const { valid, token, message, recoveryCodes } = await System.requestToken(data); if (valid && !!token) { setToken(token); if (recoveryCodes) { setRecoveryCodes(recoveryCodes); openRecoveryCodeModal(); } else { window.localStorage.setItem(AUTH_TOKEN, token); window.location = paths.home(); } } else { setError(message); setLoading(false); } setLoading(false); }; const handleDownloadComplete = () => { setDownloadComplete(true); }; useEffect(() => { if (downloadComplete && token) { window.localStorage.setItem(AUTH_TOKEN, token); window.location = paths.home(); } }, [downloadComplete, token]); useEffect(() => { const fetchCustomAppName = async () => { const { appName } = await System.fetchCustomAppName(); setCustomAppName(appName || ""); setLoading(false); }; fetchCustomAppName(); }, []); return ( <> <form onSubmit={handleLogin}> <div className="flex flex-col justify-center items-center relative rounded-2xl bg-theme-bg-secondary md:shadow-[0_4px_14px_rgba(0,0,0,0.25)] md:px-12 py-12 -mt-36 md:-mt-10"> <div className="flex items-start justify-between pt-11 pb-9 rounded-t"> <div className="flex items-center flex-col gap-y-4"> <div className="flex gap-x-1"> <h3 className="text-md md:text-2xl font-bold text-white text-center white-space-nowrap hidden md:block"> {t("login.multi-user.welcome")} </h3> <p className="text-4xl md:text-2xl font-bold bg-gradient-to-r from-[#75D6FF] via-[#FFFFFF] light:via-[#75D6FF] to-[#FFFFFF] light:to-[#75D6FF] bg-clip-text text-transparent"> {customAppName || "AnythingLLM"} </p> </div> <p className="text-sm text-theme-text-secondary text-center"> {t("login.sign-in.start")} {customAppName || "AnythingLLM"}{" "} {t("login.sign-in.end")} </p> </div> </div> <div className="w-full px-4 md:px-12"> <div className="w-full flex flex-col gap-y-4"> <div className="w-screen md:w-full md:px-0 px-6"> <input name="password" type="password" placeholder="Password" className="border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-md p-2.5 w-full h-[48px] md:w-[300px] md:h-[34px]" required={true} autoComplete="off" /> </div> {error && <p className="text-red-400 text-sm">Error: {error}</p>} </div> </div> <div className="flex items-center md:p-12 px-10 mt-12 md:mt-0 space-x-2 border-gray-600 w-full flex-col gap-y-8"> <button disabled={loading} type="submit" className="md:text-primary-button md:bg-transparent text-dark-text text-sm font-bold focus:ring-4 focus:outline-none rounded-md border-[1.5px] border-primary-button md:h-[34px] h-[48px] md:hover:text-white md:hover:bg-primary-button bg-primary-button focus:z-10 w-full" > {loading ? t("login.multi-user.validating") : t("login.multi-user.login")} </button> </div> </div> </form> <ModalWrapper isOpen={isRecoveryCodeModalOpen} noPortal={true}> <RecoveryCodeModal recoveryCodes={recoveryCodes} onDownloadComplete={handleDownloadComplete} onClose={closeRecoveryCodeModal} /> </ModalWrapper> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/Password/MultiUserAuth.jsx
frontend/src/components/Modals/Password/MultiUserAuth.jsx
import React, { useEffect, useState } from "react"; import System from "../../../models/system"; import { AUTH_TOKEN, AUTH_USER } from "../../../utils/constants"; import paths from "../../../utils/paths"; import showToast from "@/utils/toast"; import ModalWrapper from "@/components/ModalWrapper"; import { useModal } from "@/hooks/useModal"; import RecoveryCodeModal from "@/components/Modals/DisplayRecoveryCodeModal"; import { useTranslation } from "react-i18next"; import { t } from "i18next"; const RecoveryForm = ({ onSubmit, setShowRecoveryForm }) => { const [username, setUsername] = useState(""); const [recoveryCodeInputs, setRecoveryCodeInputs] = useState( Array(2).fill("") ); const handleRecoveryCodeChange = (index, value) => { const updatedCodes = [...recoveryCodeInputs]; updatedCodes[index] = value; setRecoveryCodeInputs(updatedCodes); }; const handleSubmit = (e) => { e.preventDefault(); const recoveryCodes = recoveryCodeInputs.filter( (code) => code.trim() !== "" ); onSubmit(username, recoveryCodes); }; return ( <form onSubmit={handleSubmit} className="flex flex-col justify-center items-center relative rounded-2xl border-none bg-theme-bg-secondary md:shadow-[0_4px_14px_rgba(0,0,0,0.25)] md:px-8 px-0 py-4 w-full md:w-fit mt-10 md:mt-0" > <div className="flex items-start justify-between pt-11 pb-9 w-screen md:w-full md:px-12 px-6 "> <div className="flex flex-col gap-y-4 w-full"> <h3 className="text-4xl md:text-lg font-bold text-theme-text-primary text-center md:text-left"> {t("login.password-reset.title")} </h3> <p className="text-sm text-theme-text-secondary md:text-left md:max-w-[300px] px-4 md:px-0 text-center"> {t("login.password-reset.description")} </p> </div> </div> <div className="md:px-12 px-6 space-y-6 flex h-full w-full"> <div className="w-full flex flex-col gap-y-4"> <div className="flex flex-col gap-y-2"> <label className="text-white text-sm font-bold"> {t("login.multi-user.placeholder-username")} </label> <input name="username" type="text" placeholder={t("login.multi-user.placeholder-username")} value={username} onChange={(e) => setUsername(e.target.value)} className="border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-md p-2.5 w-full h-[48px] md:w-[300px] md:h-[34px]" required /> </div> <div className="flex flex-col gap-y-2"> <label className="text-white text-sm font-bold"> {t("login.password-reset.recovery-codes")} </label> {recoveryCodeInputs.map((code, index) => ( <div key={index}> <input type="text" name={`recoveryCode${index + 1}`} placeholder={t("login.password-reset.recovery-code", { index: index + 1, })} value={code} onChange={(e) => handleRecoveryCodeChange(index, e.target.value) } className="border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-md p-2.5 w-full h-[48px] md:w-[300px] md:h-[34px]" required /> </div> ))} </div> </div> </div> <div className="flex items-center md:p-12 md:px-0 px-6 mt-12 md:mt-0 space-x-2 border-gray-600 w-full flex-col gap-y-8"> <button type="submit" className="md:text-primary-button md:bg-transparent md:w-[300px] text-dark-text text-sm font-bold focus:ring-4 focus:outline-none rounded-md border-[1.5px] border-primary-button md:h-[34px] h-[48px] md:hover:text-white md:hover:bg-primary-button bg-primary-button focus:z-10 w-full" > {t("login.password-reset.title")} </button> <button type="button" className="text-white text-sm flex gap-x-1 hover:text-primary-button hover:underline -mb-8" onClick={() => setShowRecoveryForm(false)} > {t("login.password-reset.back-to-login")} </button> </div> </form> ); }; const ResetPasswordForm = ({ onSubmit }) => { const [newPassword, setNewPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const handleSubmit = (e) => { e.preventDefault(); onSubmit(newPassword, confirmPassword); }; return ( <form onSubmit={handleSubmit} className="flex flex-col justify-center items-center relative rounded-2xl bg-theme-bg-secondary md:shadow-[0_4px_14px_rgba(0,0,0,0.25)] md:px-8 px-0 py-4 w-full md:w-fit mt-10 md:mt-0" > <div className="flex items-start justify-between pt-11 pb-9 w-screen md:w-full md:px-12 px-6"> <div className="flex flex-col gap-y-4 w-full"> <h3 className="text-4xl md:text-2xl font-bold text-white text-center md:text-left"> Reset Password </h3> <p className="text-sm text-white/90 md:text-left md:max-w-[300px] px-4 md:px-0 text-center"> Enter your new password. </p> </div> </div> <div className="md:px-12 px-6 space-y-6 flex h-full w-full"> <div className="w-full flex flex-col gap-y-4"> <div> <input type="password" name="newPassword" placeholder="New Password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" required /> </div> <div> <input type="password" name="confirmPassword" placeholder="Confirm Password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" required /> </div> </div> </div> <div className="flex items-center md:p-12 md:px-0 px-6 mt-12 md:mt-0 space-x-2 border-gray-600 w-full flex-col gap-y-8"> <button type="submit" className="md:text-primary-button md:bg-transparent md:w-[300px] text-dark-text text-sm font-bold focus:ring-4 focus:outline-none rounded-md border-[1.5px] border-primary-button md:h-[34px] h-[48px] md:hover:text-white md:hover:bg-primary-button bg-primary-button focus:z-10 w-full" > Reset Password </button> </div> </form> ); }; export default function MultiUserAuth() { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [recoveryCodes, setRecoveryCodes] = useState([]); const [downloadComplete, setDownloadComplete] = useState(false); const [user, setUser] = useState(null); const [token, setToken] = useState(null); const [showRecoveryForm, setShowRecoveryForm] = useState(false); const [showResetPasswordForm, setShowResetPasswordForm] = useState(false); const [customAppName, setCustomAppName] = useState(null); const { isOpen: isRecoveryCodeModalOpen, openModal: openRecoveryCodeModal, closeModal: closeRecoveryCodeModal, } = useModal(); const handleLogin = async (e) => { setError(null); setLoading(true); e.preventDefault(); const data = {}; const form = new FormData(e.target); for (var [key, value] of form.entries()) data[key] = value; const { valid, user, token, message, recoveryCodes } = await System.requestToken(data); if (valid && !!token && !!user) { setUser(user); setToken(token); if (recoveryCodes) { setRecoveryCodes(recoveryCodes); openRecoveryCodeModal(); } else { window.localStorage.setItem(AUTH_USER, JSON.stringify(user)); window.localStorage.setItem(AUTH_TOKEN, token); window.location = paths.home(); } } else { setError(message); setLoading(false); } setLoading(false); }; const handleDownloadComplete = () => setDownloadComplete(true); const handleResetPassword = () => setShowRecoveryForm(true); const handleRecoverySubmit = async (username, recoveryCodes) => { const { success, resetToken, error } = await System.recoverAccount( username, recoveryCodes ); if (success && resetToken) { window.localStorage.setItem("resetToken", resetToken); setShowRecoveryForm(false); setShowResetPasswordForm(true); } else { showToast(error, "error", { clear: true }); } }; const handleResetSubmit = async (newPassword, confirmPassword) => { const resetToken = window.localStorage.getItem("resetToken"); if (resetToken) { const { success, error } = await System.resetPassword( resetToken, newPassword, confirmPassword ); if (success) { window.localStorage.removeItem("resetToken"); setShowResetPasswordForm(false); showToast("Password reset successful", "success", { clear: true }); } else { showToast(error, "error", { clear: true }); } } else { showToast("Invalid reset token", "error", { clear: true }); } }; useEffect(() => { if (downloadComplete && user && token) { window.localStorage.setItem(AUTH_USER, JSON.stringify(user)); window.localStorage.setItem(AUTH_TOKEN, token); window.location = paths.home(); } }, [downloadComplete, user, token]); useEffect(() => { const fetchCustomAppName = async () => { const { appName } = await System.fetchCustomAppName(); setCustomAppName(appName || ""); setLoading(false); }; fetchCustomAppName(); }, []); if (showRecoveryForm) { return ( <RecoveryForm onSubmit={handleRecoverySubmit} setShowRecoveryForm={setShowRecoveryForm} /> ); } if (showResetPasswordForm) return <ResetPasswordForm onSubmit={handleResetSubmit} />; return ( <> <form onSubmit={handleLogin}> <div className="flex flex-col justify-center items-center relative rounded-2xl bg-theme-bg-secondary md:shadow-[0_4px_14px_rgba(0,0,0,0.25)] md:px-12 py-12 -mt-4 md:mt-0"> <div className="flex items-start justify-between pt-11 pb-9 rounded-t"> <div className="flex items-center flex-col gap-y-4"> <div className="flex gap-x-1"> <h3 className="text-md md:text-2xl font-bold text-white text-center white-space-nowrap hidden md:block"> {t("login.multi-user.welcome")} </h3> <p className="text-4xl md:text-2xl font-bold bg-gradient-to-r from-[#75D6FF] via-[#FFFFFF] light:via-[#75D6FF] to-[#FFFFFF] light:to-[#75D6FF] bg-clip-text text-transparent"> {customAppName || "AnythingLLM"} </p> </div> <p className="text-sm text-theme-text-secondary text-center"> {t("login.sign-in.start")} {customAppName || "AnythingLLM"}{" "} {t("login.sign-in.end")} </p> </div> </div> <div className="w-full px-4 md:px-12"> <div className="w-full flex flex-col gap-y-4"> <div className="w-screen md:w-full md:px-0 px-6"> <input name="username" type="text" placeholder={t("login.multi-user.placeholder-username")} className="border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-md p-2.5 w-full h-[48px] md:w-[300px] md:h-[34px]" required={true} autoComplete="off" /> </div> <div className="w-screen md:w-full md:px-0 px-6"> <input name="password" type="password" placeholder={t("login.multi-user.placeholder-password")} className="border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-md p-2.5 w-full h-[48px] md:w-[300px] md:h-[34px]" required={true} autoComplete="off" /> </div> {error && <p className="text-red-400 text-sm">Error: {error}</p>} </div> </div> <div className="flex items-center md:p-12 px-10 mt-12 md:mt-0 space-x-2 border-gray-600 w-full flex-col gap-y-8"> <button disabled={loading} type="submit" className="md:text-primary-button md:bg-transparent text-dark-text text-sm font-bold focus:ring-4 focus:outline-none rounded-md border-[1.5px] border-primary-button md:h-[34px] h-[48px] md:hover:text-white md:hover:bg-primary-button bg-primary-button focus:z-10 w-full" > {loading ? t("login.multi-user.validating") : t("login.multi-user.login")} </button> <button type="button" className="text-white text-sm flex gap-x-1 hover:text-primary-button hover:underline" onClick={handleResetPassword} > {t("login.multi-user.forgot-pass")}? <b>{t("login.multi-user.reset")}</b> </button> </div> </div> </form> <ModalWrapper isOpen={isRecoveryCodeModalOpen} noPortal={true}> <RecoveryCodeModal recoveryCodes={recoveryCodes} onDownloadComplete={handleDownloadComplete} onClose={closeRecoveryCodeModal} /> </ModalWrapper> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/index.jsx
frontend/src/components/Modals/ManageWorkspace/index.jsx
import React, { useState, useEffect, memo } from "react"; import { X } from "@phosphor-icons/react"; import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; import Workspace from "../../../models/workspace"; import System from "../../../models/system"; import { isMobile } from "react-device-detect"; import useUser from "../../../hooks/useUser"; import DocumentSettings from "./Documents"; import DataConnectors from "./DataConnectors"; import ModalWrapper from "@/components/ModalWrapper"; const noop = () => {}; const ManageWorkspace = ({ hideModal = noop, providedSlug = null }) => { const { t } = useTranslation(); const { slug } = useParams(); const { user } = useUser(); const [workspace, setWorkspace] = useState(null); const [settings, setSettings] = useState({}); const [selectedTab, setSelectedTab] = useState("documents"); useEffect(() => { async function getSettings() { const _settings = await System.keys(); setSettings(_settings ?? {}); } getSettings(); }, []); useEffect(() => { async function fetchWorkspace() { const workspace = await Workspace.bySlug(providedSlug ?? slug); setWorkspace(workspace); } fetchWorkspace(); }, [providedSlug, slug]); if (!workspace) return null; if (isMobile) { return ( <ModalWrapper isOpen={true}> <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> {t("connectors.manage.editing")} "{workspace.name}" </h3> </div> <button onClick={hideModal} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={24} weight="bold" className="text-white" /> </button> </div> <div className="h-full w-full overflow-y-auto" style={{ maxHeight: "calc(100vh - 200px)" }} > <div className="py-7 px-9 space-y-2 flex-col"> <p className="text-white"> {t("connectors.manage.desktop-only")} </p> </div> </div> <div className="flex w-full justify-end items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button onClick={hideModal} type="button" className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > {t("connectors.manage.dismiss")} </button> </div> </div> </ModalWrapper> ); } return ( <div className="w-screen h-screen fixed top-0 left-0 flex justify-center items-center z-99"> <div className="backdrop h-full w-full absolute top-0 z-10" /> <div className="absolute max-h-full w-fit transition duration-300 z-20 md:overflow-y-auto py-10"> <div className="relative bg-theme-bg-secondary rounded-[12px] shadow border-2 border-theme-modal-border"> <div className="flex items-start justify-between p-2 rounded-t border-theme-modal-border relative"> <button onClick={hideModal} type="button" className="z-29 text-white bg-transparent rounded-lg text-sm p-1.5 ml-auto inline-flex items-center bg-sidebar-button hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={20} weight="bold" className="text-white" /> </button> </div> {user?.role !== "default" && ( <ModalTabSwitcher selectedTab={selectedTab} setSelectedTab={setSelectedTab} /> )} {selectedTab === "documents" ? ( <DocumentSettings workspace={workspace} systemSettings={settings} /> ) : ( <DataConnectors workspace={workspace} systemSettings={settings} /> )} </div> </div> </div> ); }; export default memo(ManageWorkspace); const ModalTabSwitcher = ({ selectedTab, setSelectedTab }) => { const { t } = useTranslation(); return ( <div className="w-full flex justify-center z-10 relative"> <div className="gap-x-2 flex justify-center -mt-[68px] mb-10 bg-theme-bg-secondary p-1 rounded-xl shadow border-2 border-theme-modal-border w-fit"> <button onClick={() => setSelectedTab("documents")} className={`border-none px-4 py-2 rounded-[8px] font-semibold hover:bg-theme-modal-border hover:bg-opacity-60 ${ selectedTab === "documents" ? "bg-theme-modal-border font-bold text-white light:bg-[#E0F2FE] light:text-[#026AA2]" : "text-white/20 font-medium hover:text-white light:bg-white light:text-[#535862] light:hover:bg-[#E0F2FE]" }`} > {t("connectors.manage.documents")} </button> <button onClick={() => setSelectedTab("dataConnectors")} className={`border-none px-4 py-2 rounded-[8px] font-semibold hover:bg-theme-modal-border hover:bg-opacity-60 ${ selectedTab === "dataConnectors" ? "bg-theme-modal-border font-bold text-white light:bg-[#E0F2FE] light:text-[#026AA2]" : "text-white/20 font-medium hover:text-white light:bg-white light:text-[#535862] light:hover:bg-[#E0F2FE]" }`} > {t("connectors.manage.data-connectors")} </button> </div> </div> ); }; export function useManageWorkspaceModal() { const { user } = useUser(); const [showing, setShowing] = useState(false); function showModal() { if (user?.role !== "default") { setShowing(true); } } function hideModal() { setShowing(false); } useEffect(() => { function onEscape(event) { if (!showing || event.key !== "Escape") return; setShowing(false); } document.addEventListener("keydown", onEscape); return () => { document.removeEventListener("keydown", onEscape); }; }, [showing]); return { showing, showModal, hideModal }; }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/index.jsx
import ConnectorImages from "@/components/DataConnectorOption/media"; import { MagnifyingGlass } from "@phosphor-icons/react"; import { useTranslation } from "react-i18next"; import GithubOptions from "./Connectors/Github"; import GitlabOptions from "./Connectors/Gitlab"; import YoutubeOptions from "./Connectors/Youtube"; import ConfluenceOptions from "./Connectors/Confluence"; import DrupalWikiOptions from "./Connectors/DrupalWiki"; import { useState } from "react"; import ConnectorOption from "./ConnectorOption"; import WebsiteDepthOptions from "./Connectors/WebsiteDepth"; import ObsidianOptions from "./Connectors/Obsidian"; import PaperlessNgxOptions from "./Connectors/PaperlessNgx"; export const getDataConnectors = (t) => ({ github: { name: t("connectors.github.name"), image: ConnectorImages.github, description: t("connectors.github.description"), options: <GithubOptions />, }, gitlab: { name: t("connectors.gitlab.name"), image: ConnectorImages.gitlab, description: t("connectors.gitlab.description"), options: <GitlabOptions />, }, "youtube-transcript": { name: t("connectors.youtube.name"), image: ConnectorImages.youtube, description: t("connectors.youtube.description"), options: <YoutubeOptions />, }, "website-depth": { name: t("connectors.website-depth.name"), image: ConnectorImages.websiteDepth, description: t("connectors.website-depth.description"), options: <WebsiteDepthOptions />, }, confluence: { name: t("connectors.confluence.name"), image: ConnectorImages.confluence, description: t("connectors.confluence.description"), options: <ConfluenceOptions />, }, drupalwiki: { name: "Drupal Wiki", image: ConnectorImages.drupalwiki, description: "Import Drupal Wiki spaces in a single click.", options: <DrupalWikiOptions />, }, obsidian: { name: "Obsidian", image: ConnectorImages.obsidian, description: "Import Obsidian vault in a single click.", options: <ObsidianOptions />, }, "paperless-ngx": { name: "Paperless-ngx", image: ConnectorImages.paperlessNgx, description: "Import documents from your Paperless-ngx instance.", options: <PaperlessNgxOptions />, }, }); export default function DataConnectors() { const { t } = useTranslation(); const [selectedConnector, setSelectedConnector] = useState("github"); const [searchQuery, setSearchQuery] = useState(""); const DATA_CONNECTORS = getDataConnectors(t); const filteredConnectors = Object.keys(DATA_CONNECTORS).filter((slug) => DATA_CONNECTORS[slug].name.toLowerCase().includes(searchQuery.toLowerCase()) ); return ( <div className="flex upload-modal -mt-10 relative min-h-[80vh] w-[70vw]"> <div className="w-full p-4 top-0 z-20"> <div className="w-full flex items-center sticky top-0 z-50"> <MagnifyingGlass size={16} weight="bold" className="absolute left-4 z-30 text-white" /> <input type="text" placeholder={t("connectors.search-placeholder")} className="border-none z-20 pl-10 h-[38px] rounded-full w-full px-4 py-1 text-sm border-2 border-slate-300/40 outline-none focus:outline-primary-button active:outline-primary-button outline-none placeholder:text-theme-settings-input-placeholder text-white bg-theme-settings-input-bg" autoComplete="off" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} /> </div> <div className="mt-2 flex flex-col gap-y-2"> {filteredConnectors.length > 0 ? ( filteredConnectors.map((slug, index) => ( <ConnectorOption key={index} slug={slug} selectedConnector={selectedConnector} setSelectedConnector={setSelectedConnector} image={DATA_CONNECTORS[slug].image} name={DATA_CONNECTORS[slug].name} description={DATA_CONNECTORS[slug].description} /> )) ) : ( <div className="text-white text-center mt-4"> {t("connectors.no-connectors")} </div> )} </div> </div> <div className="xl:block hidden absolute left-1/2 top-0 bottom-0 w-[0.5px] bg-white/20 -translate-x-1/2"></div> <div className="w-full p-4 top-0 text-white min-w-[500px]"> {DATA_CONNECTORS[selectedConnector].options} </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/ConnectorOption/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/ConnectorOption/index.jsx
export default function ConnectorOption({ slug, selectedConnector, setSelectedConnector, image, name, description, }) { return ( <button onClick={() => setSelectedConnector(slug)} className={`border-none flex text-left gap-x-3.5 items-center py-2 px-4 hover:bg-theme-file-picker-hover ${ selectedConnector === slug ? "bg-theme-file-picker-hover" : "" } rounded-lg cursor-pointer w-full`} > <img src={image} alt={name} className="w-[40px] h-[40px] rounded-md" /> <div className="flex flex-col"> <div className="text-white font-bold text-[14px]">{name}</div> <div> <p className="text-[12px] text-white/60">{description}</p> </div> </div> </button> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/WebsiteDepth/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/WebsiteDepth/index.jsx
import React, { useState } from "react"; import System from "@/models/system"; import showToast from "@/utils/toast"; import pluralize from "pluralize"; import { useTranslation } from "react-i18next"; export default function WebsiteDepthOptions() { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const handleSubmit = async (e) => { e.preventDefault(); const form = new FormData(e.target); try { setLoading(true); showToast("Scraping website - this may take a while.", "info", { clear: true, autoClose: false, }); const { data, error } = await System.dataConnectors.websiteDepth.scrape({ url: form.get("url"), depth: parseInt(form.get("depth")), maxLinks: parseInt(form.get("maxLinks")), }); if (!!error) { showToast(error, "error", { clear: true }); setLoading(false); return; } showToast( `Successfully scraped ${data.length} ${pluralize( "page", data.length )}!`, "success", { clear: true } ); e.target.reset(); setLoading(false); } catch (e) { console.error(e); showToast(e.message, "error", { clear: true }); setLoading(false); } }; return ( <div className="flex w-full"> <div className="flex flex-col w-full px-1 md:pb-6 pb-16"> <form className="w-full" onSubmit={handleSubmit}> <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.website-depth.URL")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.website-depth.URL_explained")} </p> </div> <input type="url" name="url" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="https://example.com" required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {" "} {t("connectors.website-depth.depth")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.website-depth.depth_explained")} </p> </div> <input type="number" name="depth" min="1" max="5" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" required={true} defaultValue="1" /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.website-depth.max_pages")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.website-depth.max_pages_explained")} </p> </div> <input type="number" name="maxLinks" min="1" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" required={true} defaultValue="20" /> </div> </div> </div> <div className="flex flex-col gap-y-2 w-full pr-10"> <button type="submit" disabled={loading} className="mt-2 w-full justify-center border-none px-4 py-2 rounded-lg text-dark-text light:text-white text-sm font-bold items-center flex gap-x-2 bg-theme-home-button-primary hover:bg-theme-home-button-primary-hover disabled:bg-theme-home-button-primary-hover disabled:cursor-not-allowed" > {loading ? "Scraping website..." : "Submit"} </button> {loading && ( <p className="text-xs text-theme-text-secondary"> {t("connectors.website-depth.task_explained")} </p> )} </div> </form> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Obsidian/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Obsidian/index.jsx
import { useState } from "react"; import { useTranslation } from "react-i18next"; import { FolderOpen, Info } from "@phosphor-icons/react"; import System from "@/models/system"; import showToast from "@/utils/toast"; export default function ObsidianOptions() { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [vaultPath, setVaultPath] = useState(""); const [selectedFiles, setSelectedFiles] = useState([]); const handleFolderPick = async (e) => { const files = Array.from(e.target.files); if (files.length === 0) return; // Filter for .md files only const markdownFiles = files.filter((file) => file.name.endsWith(".md")); setSelectedFiles(markdownFiles); // Set the folder path from the first file if (markdownFiles.length > 0) { const path = markdownFiles[0].webkitRelativePath.split("/")[0]; setVaultPath(path); } }; const handleSubmit = async (e) => { e.preventDefault(); if (selectedFiles.length === 0) return; try { setLoading(true); showToast("Importing Obsidian vault - this may take a while.", "info", { clear: true, autoClose: false, }); // Read all files and prepare them for submission const fileContents = await Promise.all( selectedFiles.map(async (file) => { const content = await file.text(); return { name: file.name, path: file.webkitRelativePath, content: content, }; }) ); const { data, error } = await System.dataConnectors.obsidian.collect({ files: fileContents, }); if (!!error) { showToast(error, "error", { clear: true }); setLoading(false); setSelectedFiles([]); setVaultPath(""); return; } // Show results const successCount = data.processed; const failCount = data.failed; const totalCount = data.total; if (successCount === totalCount) { showToast( `Successfully imported ${successCount} files from your vault!`, "success", { clear: true } ); } else { showToast( `Imported ${successCount} files, ${failCount} failed`, "warning", { clear: true } ); } setLoading(false); } catch (e) { console.error(e); showToast(e.message, "error", { clear: true }); setLoading(false); } }; return ( <div className="flex w-full"> <div className="flex flex-col w-full px-1 md:pb-6 pb-16"> <form className="w-full" onSubmit={handleSubmit}> <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col md:flex-row md:items-center gap-x-2 text-white mb-4 bg-blue-800/30 w-fit rounded-lg px-4 py-2"> <div className="gap-x-2 flex items-center"> <Info className="shrink-0" size={25} /> <p className="text-sm"> {t("connectors.obsidian.vault_warning")} </p> </div> </div> <div className="flex flex-col"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.obsidian.vault_location")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.obsidian.vault_description")} </p> </div> <div className="flex gap-x-2"> <input type="text" value={vaultPath} onChange={(e) => setVaultPath(e.target.value)} placeholder="/path/to/your/vault" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" required={true} autoComplete="off" spellCheck={false} readOnly /> <label className="px-3 py-2 bg-theme-settings-input-bg border border-none rounded-lg text-white hover:bg-theme-settings-input-bg/80 cursor-pointer"> <FolderOpen size={20} /> <input type="file" webkitdirectory="" onChange={handleFolderPick} className="hidden" /> </label> </div> {selectedFiles.length > 0 && ( <> <p className="text-xs text-white mt-2 font-bold"> {t("connectors.obsidian.selected_files", { count: selectedFiles.length, })} </p> {selectedFiles.map((file, i) => ( <p key={i} className="text-xs text-white mt-2"> {file.webkitRelativePath} </p> ))} </> )} </div> </div> </div> <div className="flex flex-col gap-y-2 w-full pr-10"> <button type="submit" disabled={loading || selectedFiles.length === 0} className="border-none mt-2 w-full justify-center px-4 py-2 rounded-lg text-dark-text light:text-white text-sm font-bold items-center flex gap-x-2 bg-theme-home-button-primary hover:bg-theme-home-button-primary-hover disabled:bg-theme-home-button-primary-hover disabled:cursor-not-allowed" > {loading ? t("connectors.obsidian.importing") : t("connectors.obsidian.import_vault")} </button> {loading && ( <p className="text-xs text-white/50"> {t("connectors.obsidian.processing_time")} </p> )} </div> </form> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Gitlab/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Gitlab/index.jsx
import React, { useEffect, useState } from "react"; import System from "@/models/system"; import showToast from "@/utils/toast"; import pluralize from "pluralize"; import { TagsInput } from "react-tag-input-component"; import { Info, Warning } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; import { useTranslation } from "react-i18next"; const DEFAULT_BRANCHES = ["main", "master"]; export default function GitlabOptions() { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [repo, setRepo] = useState(null); const [accessToken, setAccessToken] = useState(null); const [ignores, setIgnores] = useState([]); const [settings, setSettings] = useState({ repo: null, accessToken: null, }); const handleSubmit = async (e) => { e.preventDefault(); const form = new FormData(e.target); try { setLoading(true); showToast( "Fetching all files for repo - this may take a while.", "info", { clear: true, autoClose: false } ); const { data, error } = await System.dataConnectors.gitlab.collect({ repo: form.get("repo"), accessToken: form.get("accessToken"), branch: form.get("branch"), ignorePaths: ignores, fetchIssues: form.get("fetchIssues"), fetchWikis: form.get("fetchWikis"), }); if (!!error) { showToast(error, "error", { clear: true }); setLoading(false); return; } showToast( `${data.files} ${pluralize("file", data.files)} collected from ${ data.author }/${data.repo}:${data.branch}. Output folder is ${data.destination}.`, "success", { clear: true } ); e.target.reset(); setLoading(false); return; } catch (e) { console.error(e); showToast(e.message, "error", { clear: true }); setLoading(false); } }; return ( <div className="flex w-full"> <div className="flex flex-col w-full px-1 md:pb-6 pb-16"> <form className="w-full" onSubmit={handleSubmit}> <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.gitlab.URL")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.gitlab.URL_explained")} </p> </div> <input type="url" name="repo" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="https://gitlab.com/gitlab-org/gitlab" required={true} autoComplete="off" onChange={(e) => setRepo(e.target.value)} onBlur={() => setSettings({ ...settings, repo })} spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white font-bold text-sm flex gap-x-2 items-center"> <p className="font-bold text-white"> {t("connectors.gitlab.token")} </p>{" "} <p className="text-xs font-light flex items-center"> <span className="text-theme-text-secondary"> {t("connectors.gitlab.optional")} </span> <PATTooltip accessToken={accessToken} /> </p> </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.gitlab.token_description")} </p> </div> <input type="text" name="accessToken" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="glpat-XXXXXXXXXXXXXXXXXXXX" required={false} autoComplete="off" spellCheck={false} onChange={(e) => setAccessToken(e.target.value)} onBlur={() => setSettings({ ...settings, accessToken })} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white font-bold text-sm flex gap-x-2 items-center"> <p className="font-bold text-white">Settings</p> </label> <p className="text-xs font-normal text-white"> {t("connectors.gitlab.token_description")} </p> </div> <div className="flex items-center gap-x-2 mb-3"> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" name="fetchIssues" value={true} className="peer sr-only" /> <div className="peer-disabled:opacity-50 pointer-events-none peer h-6 w-11 rounded-full bg-[#CFCFD0] after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:shadow-xl after:border-none after:bg-white after:box-shadow-md after:transition-all after:content-[''] peer-checked:bg-[#32D583] peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-transparent"></div> <span className="ml-3 text-sm font-medium text-white"> {t("connectors.gitlab.fetch_issues")} </span> </label> </div> <div className="flex items-center gap-x-2"> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" name="fetchWikis" value={true} className="peer sr-only" /> <div className="peer-disabled:opacity-50 pointer-events-none peer h-6 w-11 rounded-full bg-[#CFCFD0] after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:shadow-xl after:border-none after:bg-white after:box-shadow-md after:transition-all after:content-[''] peer-checked:bg-[#32D583] peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-transparent"></div> <span className="ml-3 text-sm font-medium text-white"> Fetch Wikis as Documents </span> </label> </div> </div> <GitLabBranchSelection repo={settings.repo} accessToken={settings.accessToken} /> </div> <div className="flex flex-col w-full py-4 pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm flex gap-x-2 items-center"> <p className="text-white text-sm font-bold"> {t("connectors.gitlab.ignores")} </p> </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.gitlab.git_ignore")} </p> </div> <TagsInput value={ignores} onChange={setIgnores} name="ignores" placeholder="!*.js, images/*, .DS_Store, bin/*" classNames={{ tag: "bg-theme-settings-input-bg light:bg-black/10 bg-blue-300/10 text-zinc-800", input: "flex p-1 !bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none", }} /> </div> </div> <div className="flex flex-col gap-y-2 w-full pr-10"> <PATAlert accessToken={accessToken} /> <button type="submit" disabled={loading} className="mt-2 w-full justify-center border-none px-4 py-2 rounded-lg text-dark-text light:text-white text-sm font-bold items-center flex gap-x-2 bg-theme-home-button-primary hover:bg-theme-home-button-primary-hover disabled:bg-theme-home-button-primary-hover disabled:cursor-not-allowed" > {loading ? "Collecting files..." : "Submit"} </button> {loading && ( <p className="text-xs text-white/50"> {t("connectors.gitlab.task_explained")} </p> )} </div> </form> </div> </div> ); } function GitLabBranchSelection({ repo, accessToken }) { const { t } = useTranslation(); const [allBranches, setAllBranches] = useState(DEFAULT_BRANCHES); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchAllBranches() { if (!repo) { setAllBranches(DEFAULT_BRANCHES); setLoading(false); return; } setLoading(true); const { branches } = await System.dataConnectors.gitlab.branches({ repo, accessToken, }); setAllBranches(branches.length > 0 ? branches : DEFAULT_BRANCHES); setLoading(false); } fetchAllBranches(); }, [repo, accessToken]); if (loading) { return ( <div className="flex flex-col w-60"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.gitlab.branch")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.gitlab.branch_explained")} </p> </div> <select name="branch" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-lg block w-full p-2.5" > <option disabled={true} selected={true}> {t("connectors.gitlab.branch_loading")} </option> </select> </div> ); } return ( <div className="flex flex-col w-60"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold">Branch</label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.gitlab.branch_explained")} </p> </div> <select name="branch" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-lg block w-full p-2.5" > {allBranches.map((branch) => { return ( <option key={branch} value={branch}> {branch} </option> ); })} </select> </div> ); } function PATAlert({ accessToken }) { const { t } = useTranslation(); if (!!accessToken) return null; return ( <div className="flex flex-col md:flex-row md:items-center gap-x-2 text-white mb-4 bg-blue-800/30 w-fit rounded-lg px-4 py-2"> <div className="gap-x-2 flex items-center"> <Info className="shrink-0" size={25} /> <p className="text-sm"> <span dangerouslySetInnerHTML={{ __html: t("connectors.gitlab.token_information"), }} /> <br /> <br /> <a href="https://gitlab.com/-/user_settings/personal_access_tokens" rel="noreferrer" target="_blank" className="underline" onClick={(e) => e.stopPropagation()} > {t("connectors.gitlab.token_personal")} </a> </p> </div> </div> ); } function PATTooltip({ accessToken }) { const { t } = useTranslation(); if (!!accessToken) return null; return ( <> {!accessToken && ( <Warning size={14} className="ml-1 text-orange-500 cursor-pointer" data-tooltip-id="access-token-tooltip" data-tooltip-place="right" /> )} <Tooltip delayHide={300} id="access-token-tooltip" className="max-w-xs z-99" clickable={true} > <p className="text-sm"> {t("connectors.gitlab.token_explained_start")} <a href="https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html" rel="noreferrer" target="_blank" className="underline" onClick={(e) => e.stopPropagation()} > {t("connectors.gitlab.token_explained_link1")} </a> {t("connectors.gitlab.token_explained_middle")} <a href="https://gitlab.com/-/profile/personal_access_tokens" rel="noreferrer" target="_blank" className="underline" onClick={(e) => e.stopPropagation()} > {t("connectors.gitlab.token_explained_link2")} </a> {t("connectors.gitlab.token_explained_end")} </p> </Tooltip> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Github/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Github/index.jsx
import React, { useEffect, useState } from "react"; import System from "@/models/system"; import { useTranslation } from "react-i18next"; import showToast from "@/utils/toast"; import pluralize from "pluralize"; import { TagsInput } from "react-tag-input-component"; import { Info, Warning } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; const DEFAULT_BRANCHES = ["main", "master"]; export default function GithubOptions() { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [repo, setRepo] = useState(null); const [accessToken, setAccessToken] = useState(null); const [ignores, setIgnores] = useState([]); const [settings, setSettings] = useState({ repo: null, accessToken: null, }); const handleSubmit = async (e) => { e.preventDefault(); const form = new FormData(e.target); try { setLoading(true); showToast( "Fetching all files for repo - this may take a while.", "info", { clear: true, autoClose: false } ); const { data, error } = await System.dataConnectors.github.collect({ repo: form.get("repo"), accessToken: form.get("accessToken"), branch: form.get("branch"), ignorePaths: ignores, }); if (!!error) { showToast(error, "error", { clear: true }); setLoading(false); return; } showToast( `${data.files} ${pluralize("file", data.files)} collected from ${ data.author }/${data.repo}:${data.branch}. Output folder is ${data.destination}.`, "success", { clear: true } ); e.target.reset(); setLoading(false); return; } catch (e) { console.error(e); showToast(e.message, "error", { clear: true }); setLoading(false); } }; return ( <div className="flex w-full"> <div className="flex flex-col w-full px-1 md:pb-6 pb-16"> <form className="w-full" onSubmit={handleSubmit}> <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.github.URL")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.github.URL_explained")} </p> </div> <input type="url" name="repo" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="https://github.com/Mintplex-Labs/anything-llm" required={true} autoComplete="off" onChange={(e) => setRepo(e.target.value)} onBlur={() => setSettings({ ...settings, repo })} spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white font-bold text-sm flex gap-x-2 items-center"> <p className="font-bold text-white"> {t("connectors.github.token")} </p>{" "} <p className="text-xs font-light flex items-center"> <span className="text-theme-text-secondary"> {t("connectors.github.optional")} </span> <PATTooltip accessToken={accessToken} /> </p> </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.github.token_explained")} </p> </div> <input type="text" name="accessToken" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="github_pat_1234_abcdefg" required={false} autoComplete="off" spellCheck={false} onChange={(e) => setAccessToken(e.target.value)} onBlur={() => setSettings({ ...settings, accessToken })} /> </div> <GitHubBranchSelection repo={settings.repo} accessToken={settings.accessToken} /> </div> <div className="flex flex-col w-full py-4 pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm flex gap-x-2 items-center"> <p className="text-white text-sm font-bold"> {t("connectors.github.ignores")} </p> </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.github.git_ignore")} </p> </div> <TagsInput value={ignores} onChange={setIgnores} name="ignores" placeholder="!*.js, images/*, .DS_Store, bin/*" classNames={{ tag: "bg-theme-settings-input-bg light:bg-black/10 bg-blue-300/10 text-zinc-800", input: "flex p-1 !bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none", }} /> </div> </div> <div className="flex flex-col gap-y-2 w-full pr-10"> <PATAlert accessToken={accessToken} /> <button type="submit" disabled={loading} className="mt-2 w-full justify-center border-none px-4 py-2 rounded-lg text-dark-text light:text-white text-sm font-bold items-center flex gap-x-2 bg-theme-home-button-primary hover:bg-theme-home-button-primary-hover disabled:bg-theme-home-button-primary-hover disabled:cursor-not-allowed" > {loading ? "Collecting files..." : "Submit"} </button> {loading && ( <p className="text-xs text-white/50"> {t("connectors.github.task_explained")} </p> )} </div> </form> </div> </div> ); } function GitHubBranchSelection({ repo, accessToken }) { const { t } = useTranslation(); const [allBranches, setAllBranches] = useState(DEFAULT_BRANCHES); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchAllBranches() { if (!repo) { setAllBranches(DEFAULT_BRANCHES); setLoading(false); return; } setLoading(true); const { branches } = await System.dataConnectors.github.branches({ repo, accessToken, }); setAllBranches(branches.length > 0 ? branches : DEFAULT_BRANCHES); setLoading(false); } fetchAllBranches(); }, [repo, accessToken]); if (loading) { return ( <div className="flex flex-col w-60"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold">Branch</label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.github.branch")} </p> </div> <select name="branch" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-lg block w-full p-2.5" > <option disabled={true} selected={true}> {t("connectors.github.branch_loading")} </option> </select> </div> ); } return ( <div className="flex flex-col w-60"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold">Branch</label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.github.branch_explained")} </p> </div> <select name="branch" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-lg block w-full p-2.5" > {allBranches.map((branch) => { return ( <option key={branch} value={branch}> {branch} </option> ); })} </select> </div> ); } function PATAlert({ accessToken }) { const { t } = useTranslation(); if (!!accessToken) return null; return ( <div className="flex flex-col md:flex-row md:items-center gap-x-2 text-white mb-4 bg-blue-800/30 w-fit rounded-lg px-4 py-2"> <div className="gap-x-2 flex items-center"> <Info className="shrink-0" size={25} /> <p className="text-sm"> <span dangerouslySetInnerHTML={{ __html: t("connectors.github.token_information"), }} /> <br /> <br /> <a href="https://github.com/settings/personal-access-tokens/new" rel="noreferrer" target="_blank" className="underline" onClick={(e) => e.stopPropagation()} > {" "} {t("connectors.github.token_personal")} </a> </p> </div> </div> ); } function PATTooltip({ accessToken }) { const { t } = useTranslation(); if (!!accessToken) return null; return ( <> {!accessToken && ( <Warning size={14} className="ml-1 text-orange-500 cursor-pointer" data-tooltip-id="access-token-tooltip" data-tooltip-place="right" /> )} <Tooltip delayHide={300} id="access-token-tooltip" className="max-w-xs z-99" clickable={true} > <p className="text-sm"> {t("connectors.github.token_explained_start")} <a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens" rel="noreferrer" target="_blank" className="underline" onClick={(e) => e.stopPropagation()} > {t("connectors.github.token_explained_link1")} </a> {t("connectors.github.token_explained_middle")} <a href="https://github.com/settings/personal-access-tokens/new" rel="noreferrer" target="_blank" className="underline" onClick={(e) => e.stopPropagation()} > {t("connectors.github.token_explained_link2")} </a> {t("connectors.github.token_explained_end")} </p> </Tooltip> </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/PaperlessNgx/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/PaperlessNgx/index.jsx
import React, { useState } from "react"; import System from "@/models/system"; import showToast from "@/utils/toast"; import { Info } from "@phosphor-icons/react"; export default function PaperlessNgxOptions() { const [loading, setLoading] = useState(false); const handleSubmit = async (e) => { e.preventDefault(); const form = new FormData(e.target); try { setLoading(true); showToast( "Fetching documents from Paperless-ngx - this may take a while.", "info", { clear: true, autoClose: false } ); const { data, error } = await System.dataConnectors.paperlessNgx.collect({ baseUrl: form.get("baseUrl"), apiToken: form.get("apiToken"), }); if (!!error) { showToast(error, "error", { clear: true }); setLoading(false); return; } showToast( `Successfully imported ${data.files} documents from Paperless-ngx. Output folder is ${data.destination}.`, "success", { clear: true } ); e.target.reset(); setLoading(false); } catch (e) { console.error(e); showToast(e.message, "error", { clear: true }); setLoading(false); } }; return ( <div className="flex w-full"> <div className="flex flex-col w-full px-1 md:pb-6 pb-16"> <form className="w-full" onSubmit={handleSubmit}> <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> Base URL </label> <p className="text-xs font-normal text-theme-text-secondary"> The URL where your Paperless-ngx instance is running (e.g., http://localhost:8000) </p> </div> <input type="url" name="baseUrl" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="http://localhost:8000" required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold flex gap-x-2 items-center"> <p className="font-bold text-white">API Token</p> </label> <p className="text-xs font-normal text-theme-text-secondary"> Your Paperless-ngx API token. You can find this under &apos;My Profile&apos; and then &apos;API Auth Token&apos;. </p> </div> <input type="password" name="apiToken" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Enter your API token" required={true} autoComplete="off" spellCheck={false} /> </div> </div> </div> <div className="flex flex-col gap-y-2 w-full pr-10"> <div className="flex flex-col md:flex-row md:items-center gap-x-2 text-white mb-4 bg-blue-800/30 w-fit rounded-lg px-4 py-2"> <div className="gap-x-2 flex items-center"> <Info className="shrink-0" size={25} /> <p className="text-sm"> Make sure your Paperless-ngx instance is running and accessible from this machine. </p> </div> </div> <button type="submit" disabled={loading} className="mt-2 w-full justify-center border-none px-4 py-2 rounded-lg text-dark-text light:text-white text-sm font-bold items-center flex gap-x-2 bg-theme-home-button-primary hover:bg-theme-home-button-primary-hover disabled:bg-theme-home-button-primary-hover disabled:cursor-not-allowed" > {loading ? "Importing documents..." : "Submit"} </button> {loading && ( <p className="text-xs text-white/50"> Once complete, all documents will be available for embedding into workspaces. </p> )} </div> </form> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/DrupalWiki/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/DrupalWiki/index.jsx
/** * Copyright 2024 * * Authors: * - Eugen Mayer (KontextWork) */ import { useState } from "react"; import System from "@/models/system"; import showToast from "@/utils/toast"; import { Warning } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; export default function DrupalWikiOptions() { const [loading, setLoading] = useState(false); const handleSubmit = async (e) => { e.preventDefault(); const form = new FormData(e.target); try { setLoading(true); showToast( "Fetching all pages for the given Drupal Wiki spaces - this may take a while.", "info", { clear: true, autoClose: false, } ); const { data, error } = await System.dataConnectors.drupalwiki.collect({ baseUrl: form.get("baseUrl"), spaceIds: form.get("spaceIds"), accessToken: form.get("accessToken"), }); if (!!error) { showToast(error, "error", { clear: true }); setLoading(false); return; } showToast( `Pages collected from Drupal Wiki spaces ${data.spaceIds}. Output folder is ${data.destination}.`, "success", { clear: true } ); e.target.reset(); setLoading(false); } catch (e) { console.error(e); showToast(e.message, "error", { clear: true }); setLoading(false); } }; return ( <div className="flex w-full"> <div className="flex flex-col w-full px-1 md:pb-6 pb-16"> <form className="w-full" onSubmit={handleSubmit}> <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold flex gap-x-2 items-center"> <p className="font-bold text-white">Drupal Wiki base URL</p> </label> <p className="text-xs font-normal text-theme-text-secondary"> This is the base URL of your&nbsp; <a href="https://drupal-wiki.com" target="_blank" rel="noopener noreferrer" className="underline" > Drupal Wiki </a> . </p> </div> <input type="url" name="baseUrl" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="eg: https://mywiki.drupal-wiki.net, https://drupalwiki.mycompany.tld, etc..." required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> Drupal Wiki Space IDs </label> <p className="text-xs font-normal text-theme-text-secondary"> Comma separated Space IDs you want to extract. See the&nbsp; <a href="https://help.drupal-wiki.com/node/606" target="_blank" rel="noopener noreferrer" className="underline" onClick={(e) => e.stopPropagation()} > manual </a> &nbsp; on how to retrieve the Space IDs. Be sure that your 'API-Token User' has access to those spaces. </p> </div> <input type="text" name="spaceIds" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="eg: 12,34,69" required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold flex gap-x-2 items-center"> <p className="font-bold text-white"> Drupal Wiki API Token </p> <Warning size={14} className="ml-1 text-orange-500 cursor-pointer" data-tooltip-id="access-token-tooltip" data-tooltip-place="right" /> <Tooltip delayHide={300} id="access-token-tooltip" className="max-w-xs z-99" clickable={true} > <p className="text-sm font-light text-theme-text-primary"> You need to provide an API token for authentication. See the Drupal Wiki&nbsp; <a href="https://help.drupal-wiki.com/node/605#2-Zugriffs-Token-generieren" target="_blank" rel="noopener noreferrer" className="underline" > manual </a> &nbsp;on how to generate an API-Token for your user. </p> </Tooltip> </label> <p className="text-xs font-normal text-theme-text-secondary"> Access token for authentication. </p> </div> <input type="password" name="accessToken" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="pat:123" required={true} autoComplete="off" spellCheck={false} /> </div> </div> </div> <div className="flex flex-col gap-y-2 w-full pr-10"> <button type="submit" disabled={loading} className="mt-2 w-full justify-center border-none px-4 py-2 rounded-lg text-dark-text light:text-white text-sm font-bold items-center flex gap-x-2 bg-theme-home-button-primary hover:bg-theme-home-button-primary-hover disabled:bg-theme-home-button-primary-hover disabled:cursor-not-allowed" > {loading ? "Collecting pages..." : "Submit"} </button> {loading && ( <p className="text-xs text-theme-text-secondary"> Once complete, all pages will be available for embedding into workspaces. </p> )} </div> </form> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Confluence/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Confluence/index.jsx
import { useState } from "react"; import { useTranslation } from "react-i18next"; import System from "@/models/system"; import showToast from "@/utils/toast"; import { Warning } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; export default function ConfluenceOptions() { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [accessType, setAccessType] = useState("username"); const [isCloud, setIsCloud] = useState(true); const handleSubmit = async (e) => { e.preventDefault(); const form = new FormData(e.target); try { setLoading(true); showToast( "Fetching all pages for Confluence space - this may take a while.", "info", { clear: true, autoClose: false, } ); const { data, error } = await System.dataConnectors.confluence.collect({ baseUrl: form.get("baseUrl"), spaceKey: form.get("spaceKey"), username: form.get("username"), accessToken: form.get("accessToken"), cloud: form.get("isCloud") === "true", personalAccessToken: form.get("personalAccessToken"), bypassSSL: form.get("bypassSSL") === "true", }); if (!!error) { showToast(error, "error", { clear: true }); setLoading(false); return; } showToast( `Pages collected from Confluence space ${data.spaceKey}. Output folder is ${data.destination}.`, "success", { clear: true } ); e.target.reset(); setLoading(false); } catch (e) { console.error(e); showToast(e.message, "error", { clear: true }); setLoading(false); } }; return ( <div className="flex w-full"> <div className="flex flex-col w-full px-1 md:pb-6 pb-16"> <form className="w-full" onSubmit={handleSubmit}> <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold flex gap-x-2 items-center"> <p className="font-bold text-theme-text-primary"> {t("connectors.confluence.deployment_type")} </p> </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.confluence.deployment_type_explained")} </p> </div> <select name="isCloud" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" required={true} autoComplete="off" spellCheck={false} defaultValue="true" onChange={(e) => setIsCloud(e.target.value === "true")} > <option value="true">Atlassian Cloud</option> <option value="false">Self-hosted</option> </select> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold flex gap-x-2 items-center"> <p className="font-bold text-white"> {t("connectors.confluence.base_url")} </p> </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.confluence.base_url_explained")} </p> </div> <input type="url" name="baseUrl" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="eg: https://example.atlassian.net, http://localhost:8211, etc..." required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.confluence.space_key")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.confluence.space_key_explained")} </p> </div> <input type="text" name="spaceKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="eg: ~7120208c08555d52224113949698b933a3bb56" required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.confluence.auth_type")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.confluence.auth_type_explained")} </p> </div> <select name="accessType" className="border-none bg-theme-settings-input-bg w-fit mt-2 px-4 border-gray-500 text-white text-sm rounded-lg block py-2" defaultValue={accessType} onChange={(e) => setAccessType(e.target.value)} > {[ { name: t("connectors.confluence.auth_type_username"), value: "username", }, { name: t("connectors.confluence.auth_type_personal"), value: "personalToken", }, ].map((type) => { return ( <option key={type.value} value={type.value}> {type.name} </option> ); })} </select> </div> {accessType === "username" && ( <> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.confluence.username")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.confluence.username_explained")} </p> </div> <input type="text" name="username" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="[email protected]" required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold flex gap-x-2 items-center"> <p className="font-bold text-white"> {t("connectors.confluence.token")} </p> <Warning size={14} className="ml-1 text-orange-500 cursor-pointer" data-tooltip-id="access-token-tooltip" data-tooltip-place="right" /> <Tooltip delayHide={300} id="access-token-tooltip" className="max-w-xs z-99" clickable={true} > <p className="text-sm"> {t("connectors.confluence.token_explained_start")} <a href="https://id.atlassian.com/manage-profile/security/api-tokens" target="_blank" rel="noopener noreferrer" className="underline" onClick={(e) => e.stopPropagation()} > {t("connectors.confluence.token_explained_link")} </a> . </p> </Tooltip> </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.confluence.token_desc")} </p> </div> <input type="password" name="accessToken" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="abcd1234" required={true} autoComplete="off" spellCheck={false} /> </div> </> )} {accessType === "personalToken" && ( <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.confluence.pat_token")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.confluence.pat_token_explained")} </p> </div> <input type="password" name="personalAccessToken" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="abcd1234" required={true} autoComplete="off" spellCheck={false} /> </div> )} </div> </div> {!isCloud && ( <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold flex gap-x-2 items-center"> <input type="checkbox" name="bypassSSL" className="mr-2" defaultChecked={false} /> <p className="font-bold text-theme-text-primary"> {t("connectors.confluence.bypass_ssl")} </p> </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.confluence.bypass_ssl_explained")} </p> </div> </div> </div> </div> )} <div className="flex flex-col gap-y-2 w-full pr-10"> <button type="submit" disabled={loading} className="mt-2 w-full justify-center border-none px-4 py-2 rounded-lg text-dark-text light:text-white text-sm font-bold items-center flex gap-x-2 bg-theme-home-button-primary hover:bg-theme-home-button-primary-hover disabled:bg-theme-home-button-primary-hover disabled:cursor-not-allowed" > {loading ? "Collecting pages..." : "Submit"} </button> {loading && ( <p className="text-xs text-theme-text-secondary"> {t("connectors.confluence.task_explained")} </p> )} </div> </form> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Youtube/index.jsx
frontend/src/components/Modals/ManageWorkspace/DataConnectors/Connectors/Youtube/index.jsx
import React, { useState } from "react"; import System from "@/models/system"; import showToast from "@/utils/toast"; import { useTranslation } from "react-i18next"; export default function YoutubeOptions() { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const handleSubmit = async (e) => { e.preventDefault(); const form = new FormData(e.target); try { setLoading(true); showToast("Fetching transcript for YouTube video.", "info", { clear: true, autoClose: false, }); const { data, error } = await System.dataConnectors.youtube.transcribe({ url: form.get("url"), }); if (!!error) { showToast(error, "error", { clear: true }); setLoading(false); return; } showToast( `${data.title} by ${data.author} transcription completed. Output folder is ${data.destination}.`, "success", { clear: true } ); e.target.reset(); setLoading(false); return; } catch (e) { console.error(e); showToast(e.message, "error", { clear: true }); setLoading(false); } }; return ( <div className="flex w-full"> <div className="flex flex-col w-full px-1 md:pb-6 pb-16"> <form className="w-full" onSubmit={handleSubmit}> <div className="w-full flex flex-col py-2"> <div className="w-full flex flex-col gap-4"> <div className="flex flex-col pr-10"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-bold"> {t("connectors.youtube.URL")} </label> <p className="text-xs font-normal text-theme-text-secondary"> {t("connectors.youtube.URL_explained_start")} <a href="https://support.google.com/youtube/answer/6373554" rel="noreferrer" target="_blank" className="underline" onClick={(e) => e.stopPropagation()} > {t("connectors.youtube.URL_explained_link")} </a> {t("connectors.youtube.URL_explained_end")} </p> </div> <input type="url" name="url" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="https://youtube.com/watch?v=abc123" required={true} autoComplete="off" spellCheck={false} /> </div> </div> </div> <div className="flex flex-col gap-y-2 w-full pr-10"> <button type="submit" disabled={loading} className="mt-2 w-full justify-center border-none px-4 py-2 rounded-lg text-dark-text light:text-white text-sm font-bold items-center flex gap-x-2 bg-theme-home-button-primary hover:bg-theme-home-button-primary-hover disabled:bg-theme-home-button-primary-hover disabled:cursor-not-allowed" > {loading ? "Collecting transcript..." : "Collect transcript"} </button> {loading && ( <p className="text-xs text-theme-text-secondary max-w-sm"> {t("connectors.youtube.task_explained")} </p> )} </div> </form> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/index.jsx
import { ArrowsDownUp } from "@phosphor-icons/react"; import { useEffect, useState } from "react"; import Workspace from "../../../../models/workspace"; import System from "../../../../models/system"; import showToast from "../../../../utils/toast"; import Directory from "./Directory"; import WorkspaceDirectory from "./WorkspaceDirectory"; // OpenAI Cost per token // ref: https://openai.com/pricing#:~:text=%C2%A0/%201K%20tokens-,Embedding%20models,-Build%20advanced%20search const MODEL_COSTS = { "text-embedding-ada-002": 0.0000001, // $0.0001 / 1K tokens "text-embedding-3-small": 0.00000002, // $0.00002 / 1K tokens "text-embedding-3-large": 0.00000013, // $0.00013 / 1K tokens }; export default function DocumentSettings({ workspace, systemSettings }) { const [highlightWorkspace, setHighlightWorkspace] = useState(false); const [availableDocs, setAvailableDocs] = useState([]); const [loading, setLoading] = useState(true); const [workspaceDocs, setWorkspaceDocs] = useState([]); const [selectedItems, setSelectedItems] = useState({}); const [hasChanges, setHasChanges] = useState(false); const [movedItems, setMovedItems] = useState([]); const [embeddingsCost, setEmbeddingsCost] = useState(0); const [loadingMessage, setLoadingMessage] = useState(""); async function fetchKeys(refetchWorkspace = false) { setLoading(true); const localFiles = await System.localFiles(); const currentWorkspace = refetchWorkspace ? await Workspace.bySlug(workspace.slug) : workspace; const documentsInWorkspace = currentWorkspace.documents.map((doc) => doc.docpath) || []; // Documents that are not in the workspace const availableDocs = { ...localFiles, items: localFiles.items.map((folder) => { if (folder.items && folder.type === "folder") { return { ...folder, items: folder.items.filter( (file) => file.type === "file" && !documentsInWorkspace.includes(`${folder.name}/${file.name}`) ), }; } else { return folder; } }), }; // Documents that are already in the workspace const workspaceDocs = { ...localFiles, items: localFiles.items.map((folder) => { if (folder.items && folder.type === "folder") { return { ...folder, items: folder.items.filter( (file) => file.type === "file" && documentsInWorkspace.includes(`${folder.name}/${file.name}`) ), }; } else { return folder; } }), }; setAvailableDocs(availableDocs); setWorkspaceDocs(workspaceDocs); setLoading(false); } useEffect(() => { fetchKeys(true); }, []); const updateWorkspace = async (e) => { e.preventDefault(); setLoading(true); showToast("Updating workspace...", "info", { autoClose: false }); setLoadingMessage("This may take a while for large documents"); const changesToSend = { adds: movedItems.map((item) => `${item.folderName}/${item.name}`), }; setSelectedItems({}); setHasChanges(false); setHighlightWorkspace(false); await Workspace.modifyEmbeddings(workspace.slug, changesToSend) .then((res) => { if (!!res.message) { showToast(`Error: ${res.message}`, "error", { clear: true }); return; } showToast("Workspace updated successfully.", "success", { clear: true, }); }) .catch((error) => { showToast(`Workspace update failed: ${error}`, "error", { clear: true, }); }); setMovedItems([]); await fetchKeys(true); setLoading(false); setLoadingMessage(""); }; const moveSelectedItemsToWorkspace = () => { setHighlightWorkspace(false); setHasChanges(true); const newMovedItems = []; for (const itemId of Object.keys(selectedItems)) { for (const folder of availableDocs.items) { const foundItem = folder.items.find((file) => file.id === itemId); if (foundItem) { newMovedItems.push({ ...foundItem, folderName: folder.name }); break; } } } let totalTokenCount = 0; newMovedItems.forEach((item) => { const { cached, token_count_estimate } = item; if (!cached) { totalTokenCount += token_count_estimate; } }); // Do not do cost estimation unless the embedding engine is OpenAi. if (systemSettings?.EmbeddingEngine === "openai") { const COST_PER_TOKEN = MODEL_COSTS[ systemSettings?.EmbeddingModelPref || "text-embedding-ada-002" ]; const dollarAmount = (totalTokenCount / 1000) * COST_PER_TOKEN; setEmbeddingsCost(dollarAmount); } setMovedItems([...movedItems, ...newMovedItems]); let newAvailableDocs = JSON.parse(JSON.stringify(availableDocs)); let newWorkspaceDocs = JSON.parse(JSON.stringify(workspaceDocs)); for (const itemId of Object.keys(selectedItems)) { let foundItem = null; let foundFolderIndex = null; newAvailableDocs.items = newAvailableDocs.items.map( (folder, folderIndex) => { const remainingItems = folder.items.filter((file) => { const match = file.id === itemId; if (match) { foundItem = { ...file }; foundFolderIndex = folderIndex; } return !match; }); return { ...folder, items: remainingItems, }; } ); if (foundItem) { newWorkspaceDocs.items[foundFolderIndex].items.push(foundItem); } } setAvailableDocs(newAvailableDocs); setWorkspaceDocs(newWorkspaceDocs); setSelectedItems({}); }; return ( <div className="flex upload-modal -mt-6 z-10 relative"> <Directory files={availableDocs} setFiles={setAvailableDocs} loading={loading} loadingMessage={loadingMessage} setLoading={setLoading} workspace={workspace} fetchKeys={fetchKeys} selectedItems={selectedItems} setSelectedItems={setSelectedItems} updateWorkspace={updateWorkspace} highlightWorkspace={highlightWorkspace} setHighlightWorkspace={setHighlightWorkspace} moveToWorkspace={moveSelectedItemsToWorkspace} setLoadingMessage={setLoadingMessage} /> <div className="upload-modal-arrow"> <ArrowsDownUp className="text-white text-base font-bold rotate-90 w-11 h-11" /> </div> <WorkspaceDirectory workspace={workspace} files={workspaceDocs} highlightWorkspace={highlightWorkspace} loading={loading} loadingMessage={loadingMessage} setLoadingMessage={setLoadingMessage} setLoading={setLoading} fetchKeys={fetchKeys} hasChanges={hasChanges} saveChanges={updateWorkspace} embeddingCosts={embeddingsCost} movedItems={movedItems} /> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/UploadFile/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/UploadFile/index.jsx
import { CloudArrowUp } from "@phosphor-icons/react"; import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import showToast from "../../../../../utils/toast"; import System from "../../../../../models/system"; import { useDropzone } from "react-dropzone"; import { v4 } from "uuid"; import FileUploadProgress from "./FileUploadProgress"; import Workspace from "../../../../../models/workspace"; import debounce from "lodash.debounce"; export default function UploadFile({ workspace, fetchKeys, setLoading, setLoadingMessage, }) { const { t } = useTranslation(); const [ready, setReady] = useState(false); const [files, setFiles] = useState([]); const [fetchingUrl, setFetchingUrl] = useState(false); const handleSendLink = async (e) => { e.preventDefault(); setLoading(true); setLoadingMessage("Scraping link..."); setFetchingUrl(true); const formEl = e.target; const form = new FormData(formEl); const { response, data } = await Workspace.uploadLink( workspace.slug, form.get("link") ); if (!response.ok) { showToast(`Error uploading link: ${data.error}`, "error"); } else { fetchKeys(true); showToast("Link uploaded successfully", "success"); formEl.reset(); } setLoading(false); setFetchingUrl(false); }; // Queue all fetchKeys calls through the same debouncer to prevent spamming the server. // either a success or error will trigger a fetchKeys call so the UI is not stuck loading. const debouncedFetchKeys = debounce(() => fetchKeys(true), 1000); const handleUploadSuccess = () => debouncedFetchKeys(); const handleUploadError = () => debouncedFetchKeys(); const onDrop = async (acceptedFiles, rejections) => { const newAccepted = acceptedFiles.map((file) => { return { uid: v4(), file, }; }); const newRejected = rejections.map((file) => { return { uid: v4(), file: file.file, rejected: true, reason: file.errors[0].code, }; }); setFiles([...newAccepted, ...newRejected]); }; useEffect(() => { async function checkProcessorOnline() { const online = await System.checkDocumentProcessorOnline(); setReady(online); } checkProcessorOnline(); }, []); const { getRootProps, getInputProps } = useDropzone({ onDrop, disabled: !ready, }); return ( <div> <div className={`w-[560px] border-dashed border-[2px] border-theme-modal-border light:border-[#686C6F] rounded-2xl bg-theme-bg-primary transition-colors duration-300 p-3 ${ ready ? " light:bg-[#E0F2FE] cursor-pointer hover:bg-theme-bg-secondary light:hover:bg-transparent" : "cursor-not-allowed" }`} {...getRootProps()} > <input {...getInputProps()} /> {ready === false ? ( <div className="flex flex-col items-center justify-center h-full"> <CloudArrowUp className="w-8 h-8 text-white/80 light:invert" /> <div className="text-white text-opacity-80 text-sm font-semibold py-1"> {t("connectors.upload.processor-offline")} </div> <div className="text-white text-opacity-60 text-xs font-medium py-1 px-20 text-center"> {t("connectors.upload.processor-offline-desc")} </div> </div> ) : files.length === 0 ? ( <div className="flex flex-col items-center justify-center"> <CloudArrowUp className="w-8 h-8 text-white/80 light:invert" /> <div className="text-white text-opacity-80 text-sm font-semibold py-1"> {t("connectors.upload.click-upload")} </div> <div className="text-white text-opacity-60 text-xs font-medium py-1"> {t("connectors.upload.file-types")} </div> </div> ) : ( <div className="grid grid-cols-2 gap-2 overflow-auto max-h-[180px] p-1 overflow-y-scroll no-scroll"> {files.map((file) => ( <FileUploadProgress key={file.uid} file={file.file} uuid={file.uid} setFiles={setFiles} slug={workspace.slug} rejected={file?.rejected} reason={file?.reason} onUploadSuccess={handleUploadSuccess} onUploadError={handleUploadError} setLoading={setLoading} setLoadingMessage={setLoadingMessage} /> ))} </div> )} </div> <div className="text-center text-white text-opacity-50 text-xs font-medium w-[560px] py-2"> {t("connectors.upload.or-submit-link")} </div> <form onSubmit={handleSendLink} className="flex gap-x-2"> <input disabled={fetchingUrl} name="link" type="url" className="border-none disabled:bg-theme-settings-input-bg disabled:text-theme-settings-input-placeholder bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-3/4 p-2.5" placeholder={t("connectors.upload.placeholder-link")} autoComplete="off" /> <button disabled={fetchingUrl} type="submit" className="disabled:bg-white/20 disabled:text-slate-300 disabled:border-slate-400 disabled:cursor-wait bg bg-transparent hover:bg-slate-200 hover:text-slate-800 w-auto border border-white light:border-theme-modal-border text-sm text-white p-2.5 rounded-lg" > {fetchingUrl ? t("connectors.upload.fetching") : t("connectors.upload.fetch-website")} </button> </form> <div className="mt-6 text-center text-white text-opacity-80 text-xs font-medium w-[560px]"> {t("connectors.upload.privacy-notice")} </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/UploadFile/FileUploadProgress/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/UploadFile/FileUploadProgress/index.jsx
import React, { useState, useEffect, memo } from "react"; import truncate from "truncate"; import { CheckCircle, XCircle } from "@phosphor-icons/react"; import Workspace from "../../../../../../models/workspace"; import { humanFileSize, milliToHms } from "../../../../../../utils/numbers"; import PreLoader from "../../../../../Preloader"; function FileUploadProgressComponent({ slug, uuid, file, setFiles, rejected = false, reason = null, onUploadSuccess, onUploadError, setLoading, setLoadingMessage, }) { const [timerMs, setTimerMs] = useState(10); const [status, setStatus] = useState("pending"); const [error, setError] = useState(""); const [isFadingOut, setIsFadingOut] = useState(false); const fadeOut = (cb) => { setIsFadingOut(true); cb?.(); }; const beginFadeOut = () => { setIsFadingOut(false); setFiles((prev) => { return prev.filter((item) => item.uid !== uuid); }); }; useEffect(() => { async function uploadFile() { setLoading(true); setLoadingMessage("Uploading file..."); const start = Number(new Date()); const formData = new FormData(); formData.append("file", file, file.name); const timer = setInterval(() => { setTimerMs(Number(new Date()) - start); }, 100); // Chunk streaming not working in production so we just sit and wait const { response, data } = await Workspace.uploadFile(slug, formData); if (!response.ok) { setStatus("failed"); clearInterval(timer); onUploadError(data.error); setError(data.error); } else { setLoading(false); setLoadingMessage(""); setStatus("complete"); clearInterval(timer); onUploadSuccess(); } // Begin fadeout timer to clear uploader queue. setTimeout(() => { fadeOut(() => setTimeout(() => beginFadeOut(), 300)); }, 5000); } !!file && !rejected && uploadFile(); }, []); if (rejected) { return ( <div className={`${ isFadingOut ? "file-upload-fadeout" : "file-upload" } h-14 px-2 py-2 flex items-center gap-x-4 rounded-lg bg-error/40 light:bg-error/30 light:border-solid light:border-error/40 border border-transparent`} > <div className="w-6 h-6 flex-shrink-0"> <XCircle color="var(--theme-bg-primary)" className="w-6 h-6 stroke-white bg-error rounded-full p-1 w-full h-full" /> </div> <div className="flex flex-col"> <p className="text-white light:text-red-600 text-xs font-semibold"> {truncate(file.name, 30)} </p> <p className="text-red-100 light:text-red-600 text-xs font-medium"> {reason || "this file failed to upload"} </p> </div> </div> ); } if (status === "failed") { return ( <div className={`${ isFadingOut ? "file-upload-fadeout" : "file-upload" } h-14 px-2 py-2 flex items-center gap-x-4 rounded-lg bg-error/40 light:bg-error/30 light:border-solid light:border-error/40 border border-transparent`} > <div className="w-6 h-6 flex-shrink-0"> <XCircle color="var(--theme-bg-primary)" className="w-6 h-6 stroke-white bg-error rounded-full p-1 w-full h-full" /> </div> <div className="flex flex-col"> <p className="text-white light:text-red-600 text-xs font-semibold"> {truncate(file.name, 30)} </p> <p className="text-red-100 light:text-red-600 text-xs font-medium"> {error} </p> </div> </div> ); } return ( <div className={`${ isFadingOut ? "file-upload-fadeout" : "file-upload" } h-14 px-2 py-2 flex items-center gap-x-4 rounded-lg bg-zinc-800 light:border-solid light:border-theme-modal-border light:bg-theme-bg-sidebar border border-white/20 shadow-md`} > <div className="w-6 h-6 flex-shrink-0"> {status !== "complete" ? ( <div className="flex items-center justify-center"> <PreLoader size="6" /> </div> ) : ( <CheckCircle color="var(--theme-bg-primary)" className="w-6 h-6 stroke-white bg-green-500 rounded-full p-1 w-full h-full" /> )} </div> <div className="flex flex-col"> <p className="text-white light:text-theme-text-primary text-xs font-medium"> {truncate(file.name, 30)} </p> <p className="text-white/80 light:text-theme-text-secondary text-xs font-medium"> {humanFileSize(file.size)} | {milliToHms(timerMs)} </p> </div> </div> ); } export default memo(FileUploadProgressComponent);
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/Directory/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/Directory/index.jsx
import UploadFile from "../UploadFile"; import PreLoader from "@/components/Preloader"; import { memo, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import FolderRow from "./FolderRow"; import System from "@/models/system"; import { MagnifyingGlass, Plus, Trash } from "@phosphor-icons/react"; import Document from "@/models/document"; import showToast from "@/utils/toast"; import FolderSelectionPopup from "./FolderSelectionPopup"; import MoveToFolderIcon from "./MoveToFolderIcon"; import { useModal } from "@/hooks/useModal"; import NewFolderModal from "./NewFolderModal"; import debounce from "lodash.debounce"; import { filterFileSearchResults } from "./utils"; import ContextMenu from "./ContextMenu"; import { Tooltip } from "react-tooltip"; import { safeJsonParse } from "@/utils/request"; function Directory({ files, setFiles, loading, setLoading, workspace, fetchKeys, selectedItems, setSelectedItems, setHighlightWorkspace, moveToWorkspace, setLoadingMessage, loadingMessage, }) { const { t } = useTranslation(); const [amountSelected, setAmountSelected] = useState(0); const [showFolderSelection, setShowFolderSelection] = useState(false); const [searchTerm, setSearchTerm] = useState(""); const { isOpen: isFolderModalOpen, openModal: openFolderModal, closeModal: closeFolderModal, } = useModal(); const [contextMenu, setContextMenu] = useState({ visible: false, x: 0, y: 0, }); useEffect(() => { setAmountSelected(Object.keys(selectedItems).length); }, [selectedItems]); const deleteFiles = async (event) => { event.stopPropagation(); if (!window.confirm(t("connectors.directory.delete-confirmation"))) { return false; } try { const toRemove = []; const foldersToRemove = []; for (const itemId of Object.keys(selectedItems)) { for (const folder of files.items) { const foundItem = folder.items.find((file) => file.id === itemId); if (foundItem) { toRemove.push(`${folder.name}/${foundItem.name}`); break; } } } for (const folder of files.items) { if (folder.name === "custom-documents") { continue; } if (isSelected(folder.id, folder)) { foldersToRemove.push(folder.name); } } setLoading(true); setLoadingMessage( t("connectors.directory.removing-message", { count: toRemove.length, folderCount: foldersToRemove.length, }) ); await System.deleteDocuments(toRemove); for (const folderName of foldersToRemove) { await System.deleteFolder(folderName); } await fetchKeys(true); setSelectedItems({}); } catch (error) { console.error("Failed to delete files and folders:", error); } finally { setLoading(false); setSelectedItems({}); } }; const toggleSelection = (item) => { setSelectedItems((prevSelectedItems) => { const newSelectedItems = { ...prevSelectedItems }; if (item.type === "folder") { // select all files in the folder if (newSelectedItems[item.name]) { delete newSelectedItems[item.name]; item.items.forEach((file) => delete newSelectedItems[file.id]); } else { newSelectedItems[item.name] = true; item.items.forEach((file) => (newSelectedItems[file.id] = true)); } } else { // single file selections if (newSelectedItems[item.id]) { delete newSelectedItems[item.id]; } else { newSelectedItems[item.id] = true; } } return newSelectedItems; }); }; // check if item is selected based on selectedItems state const isSelected = (id, item) => { if (item && item.type === "folder") { if (!selectedItems[item.name]) { return false; } return item.items.every((file) => selectedItems[file.id]); } return !!selectedItems[id]; }; const moveToFolder = async (folder) => { const toMove = []; for (const itemId of Object.keys(selectedItems)) { for (const currentFolder of files.items) { const foundItem = currentFolder.items.find( (file) => file.id === itemId ); if (foundItem) { toMove.push({ ...foundItem, folderName: currentFolder.name }); break; } } } setLoading(true); setLoadingMessage(`Moving ${toMove.length} documents. Please wait.`); const { success, message } = await Document.moveToFolder( toMove, folder.name ); if (!success) { showToast(`Error moving files: ${message}`, "error"); setLoading(false); return; } if (success && message) { // show info if some files were not moved due to being embedded showToast(message, "info"); } else { showToast( t("connectors.directory.move-success", { count: toMove.length }), "success" ); } await fetchKeys(true); setSelectedItems({}); setLoading(false); }; const handleSearch = debounce((e) => { const searchValue = e.target.value; setSearchTerm(searchValue); }, 500); const filteredFiles = filterFileSearchResults(files, searchTerm); const handleContextMenu = (event) => { event.preventDefault(); setContextMenu({ visible: true, x: event.clientX, y: event.clientY }); }; const closeContextMenu = () => { setContextMenu({ visible: false, x: 0, y: 0 }); }; return ( <> <div className="px-8 pb-8" onContextMenu={handleContextMenu}> <div className="flex flex-col gap-y-6"> <div className="flex items-center justify-between w-[560px] px-5 relative"> <h3 className="text-white text-base font-bold"> {t("connectors.directory.my-documents")} </h3> <div className="relative"> <input type="search" placeholder={t("connectors.directory.search-document")} onChange={handleSearch} className="border-none search-input bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder focus:outline-primary-button active:outline-primary-button outline-none text-sm rounded-lg pl-9 pr-2.5 py-2 w-[250px] h-[32px] light:border-theme-modal-border light:border" /> <MagnifyingGlass size={14} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-white" weight="bold" /> </div> <button className="border-none flex items-center gap-x-2 cursor-pointer px-[14px] py-[7px] -mr-[14px] rounded-lg hover:bg-theme-sidebar-subitem-hover z-20 relative" onClick={openFolderModal} > <Plus size={18} weight="bold" className="text-theme-text-primary light:text-[#0ba5ec]" /> <div className="text-theme-text-primary light:text-[#0ba5ec] text-xs font-bold leading-[18px]"> {t("connectors.directory.new-folder")} </div> </button> </div> <div className="relative w-[560px] h-[310px] bg-theme-settings-input-bg rounded-2xl overflow-hidden border border-theme-modal-border"> <div className="absolute top-0 left-0 right-0 z-10 rounded-t-2xl text-theme-text-primary text-xs grid grid-cols-12 py-2 px-8 border-b border-white/20 light:border-theme-modal-border bg-theme-settings-input-bg"> <p className="col-span-6">Name</p> </div> <div className="overflow-y-auto h-full pt-8"> {loading ? ( <div className="w-full h-full flex items-center justify-center flex-col gap-y-5"> <PreLoader /> <p className="text-white text-sm font-semibold animate-pulse text-center w-1/3"> {loadingMessage} </p> </div> ) : filteredFiles.length > 0 ? ( filteredFiles.map( (item, index) => item.type === "folder" && ( <FolderRow key={index} item={item} selected={isSelected( item.id, item.type === "folder" ? item : null )} onRowClick={() => toggleSelection(item)} toggleSelection={toggleSelection} isSelected={isSelected} autoExpanded={index === 0} /> ) ) ) : ( <div className="w-full h-full flex items-center justify-center"> <p className="text-white text-opacity-40 text-sm font-medium"> {t("connectors.directory.no-documents")} </p> </div> )} </div> {amountSelected !== 0 && ( <div className="absolute bottom-[12px] left-0 right-0 flex justify-center pointer-events-none"> <div className="mx-auto bg-white/40 light:bg-white rounded-lg py-1 px-2 pointer-events-auto light:shadow-lg"> <div className="flex flex-row items-center gap-x-2"> <button onClick={moveToWorkspace} onMouseEnter={() => setHighlightWorkspace(true)} onMouseLeave={() => setHighlightWorkspace(false)} className="border-none text-sm font-semibold bg-white light:bg-[#E0F2FE] h-[30px] px-2.5 rounded-lg hover:bg-neutral-800/80 hover:text-white light:text-[#026AA2] light:hover:bg-[#026AA2] light:hover:text-white" > {t("connectors.directory.move-workspace")} </button> <div className="relative"> <button onClick={() => setShowFolderSelection(!showFolderSelection) } className="border-none text-sm font-semibold bg-white light:bg-[#E0F2FE] h-[32px] w-[32px] rounded-lg text-dark-text hover:bg-neutral-800/80 hover:text-white light:text-[#026AA2] light:hover:bg-[#026AA2] light:hover:text-white flex justify-center items-center group" > <MoveToFolderIcon className="text-dark-text light:text-[#026AA2] group-hover:text-white" /> </button> {showFolderSelection && ( <FolderSelectionPopup folders={files.items.filter( (item) => item.type === "folder" )} onSelect={moveToFolder} onClose={() => setShowFolderSelection(false)} /> )} </div> <button onClick={deleteFiles} className="border-none text-sm font-semibold bg-white light:bg-[#E0F2FE] h-[32px] w-[32px] rounded-lg text-dark-text hover:bg-neutral-800/80 hover:text-white light:text-[#026AA2] light:hover:bg-[#026AA2] light:hover:text-white flex justify-center items-center" > <Trash size={18} weight="bold" /> </button> </div> </div> </div> )} </div> <UploadFile workspace={workspace} fetchKeys={fetchKeys} setLoading={setLoading} setLoadingMessage={setLoadingMessage} /> </div> {isFolderModalOpen && ( <div className="bg-black/60 backdrop-blur-sm fixed top-0 left-0 outline-none w-screen h-screen flex items-center justify-center z-30"> <NewFolderModal closeModal={closeFolderModal} files={files} setFiles={setFiles} /> </div> )} <ContextMenu contextMenu={contextMenu} closeContextMenu={closeContextMenu} files={files} selectedItems={selectedItems} setSelectedItems={setSelectedItems} /> </div> <DirectoryTooltips /> </> ); } /** * Tooltips for the directory components. Renders when the directory is shown * or updated so that tooltips are attached as the items are changed. */ function DirectoryTooltips() { return ( <Tooltip id="directory-item" place="bottom" delayShow={800} className="tooltip invert light:invert-0 z-99 max-w-[300px]" render={({ content }) => { const data = safeJsonParse(content, null); if (!data) return null; return ( <div className="text-xs"> <p className="text-white light:invert font-medium break-all"> {data.title} </p> <div className="flex flex-col mt-1"> <p className=""> Date: <b>{data.date}</b> </p> <p className=""> Type: <b>{data.extension}</b> </p> </div> </div> ); }} /> ); } export default memo(Directory);
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/Directory/MoveToFolderIcon.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/Directory/MoveToFolderIcon.jsx
export default function MoveToFolderIcon({ className, width = 18, height = 18, }) { return ( <svg width={width} height={height} viewBox="0 0 17 19" fill="none" xmlns="http://www.w3.org/2000/svg" className={className} > <path d="M1.46092 17.9754L3.5703 12.7019C3.61238 12.5979 3.68461 12.5088 3.7777 12.4462C3.8708 12.3836 3.98051 12.3502 4.09272 12.3504H7.47897C7.59001 12.3502 7.69855 12.3174 7.79116 12.2562L9.19741 11.3196C9.29001 11.2583 9.39855 11.2256 9.50959 11.2254H15.5234C15.6126 11.2254 15.7004 11.2465 15.7798 11.2872C15.8591 11.3278 15.9277 11.3867 15.9798 11.459C16.0319 11.5313 16.0661 11.6149 16.0795 11.703C16.093 11.7912 16.0853 11.8812 16.0571 11.9658L14.0532 17.9754H1.46092Z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> <path fillRule="evenodd" clipRule="evenodd" d="M2.25331 6.53891H2.02342C1.67533 6.53891 1.34149 6.67719 1.09534 6.92333C0.849204 7.16947 0.710922 7.50331 0.710922 7.85141V17.9764C0.710922 18.3906 1.04671 18.7264 1.46092 18.7264C1.87514 18.7264 2.21092 18.3906 2.21092 17.9764V8.03891H2.25331V6.53891ZM13.0859 9.98714V11.2264C13.0859 11.6406 13.4217 11.9764 13.8359 11.9764C14.2501 11.9764 14.5859 11.6406 14.5859 11.2264V9.53891C14.5859 9.19081 14.4476 8.85698 14.2015 8.61083C13.9554 8.36469 13.6215 8.22641 13.2734 8.22641H13.0863V9.98714H13.0859Z" fill="currentColor" /> <path d="M7.53416 1.62906L7.53416 7.70406" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> <path d="M10.6411 5.21854L7.53456 7.70376L4.42803 5.21854" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> </svg> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/Directory/utils.js
frontend/src/components/Modals/ManageWorkspace/Documents/Directory/utils.js
import strDistance from "js-levenshtein"; const LEVENSHTEIN_MIN = 2; // Regular expression pattern to match the v4 UUID and the ending .json const uuidPattern = /-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/; const jsonPattern = /\.json$/; // Function to strip UUID v4 and JSON from file names as that will impact search results. export const stripUuidAndJsonFromString = (input = "") => { return input ?.replace(uuidPattern, "") // remove v4 uuid ?.replace(jsonPattern, "") // remove trailing .json ?.replace("-", " "); // turn slugged names into spaces }; export function filterFileSearchResults(files = [], searchTerm = "") { if (!searchTerm) return files?.items || []; const normalizedSearchTerm = searchTerm.toLowerCase().trim(); const searchResult = []; for (const folder of files?.items) { const folderNameNormalized = folder.name.toLowerCase(); // Check for exact match first, then fuzzy match if (folderNameNormalized.includes(normalizedSearchTerm)) { searchResult.push(folder); continue; } // Check children for matches const fileSearchResults = []; for (const file of folder?.items) { const fileNameNormalized = stripUuidAndJsonFromString( file.name ).toLowerCase(); // Exact match check if (fileNameNormalized.includes(normalizedSearchTerm)) { fileSearchResults.push(file); } // Fuzzy match only if no exact matches found else if ( fileSearchResults.length === 0 && strDistance(fileNameNormalized, normalizedSearchTerm) <= LEVENSHTEIN_MIN ) { fileSearchResults.push(file); } } if (fileSearchResults.length > 0) { searchResult.push({ ...folder, items: fileSearchResults, }); } } return searchResult; }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/Directory/NewFolderModal/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/Directory/NewFolderModal/index.jsx
import React, { useState } from "react"; import { X } from "@phosphor-icons/react"; import Document from "@/models/document"; export default function NewFolderModal({ closeModal, files, setFiles }) { const [error, setError] = useState(null); const [folderName, setFolderName] = useState(""); const handleCreate = async (e) => { e.preventDefault(); setError(null); if (folderName.trim() !== "") { const newFolder = { name: folderName, type: "folder", items: [], }; const { success } = await Document.createFolder(folderName); if (success) { setFiles({ ...files, items: [...files.items, newFolder], }); closeModal(); } else { setError("Failed to create folder"); } } }; return ( <div className="fixed inset-0 z-50 overflow-auto bg-black bg-opacity-50 flex items-center justify-center"> <div className="relative w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> Create New Folder </h3> </div> <button onClick={closeModal} type="button" className="absolute top-4 right-4 transition-all duration-300 bg-transparent rounded-lg text-sm p-1 inline-flex items-center hover:bg-theme-modal-border hover:border-theme-modal-border hover:border-opacity-50 border-transparent border" > <X size={24} weight="bold" className="text-white" /> </button> </div> <div className="p-6"> <form onSubmit={handleCreate}> <div className="space-y-4"> <div> <label htmlFor="folderName" className="block mb-2 text-sm font-medium text-white" > Folder Name </label> <input name="folderName" type="text" className="border-none bg-theme-settings-input-bg w-full text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Enter folder name" required={true} autoComplete="off" value={folderName} onChange={(e) => setFolderName(e.target.value)} /> </div> {error && <p className="text-red-400 text-sm">Error: {error}</p>} </div> <div className="flex justify-between items-center mt-6 pt-6 border-t border-theme-modal-border"> <button onClick={closeModal} type="button" className="transition-all duration-300 text-white hover:bg-zinc-700 px-4 py-2 rounded-lg text-sm" > Cancel </button> <button type="submit" className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > Create Folder </button> </div> </form> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/Directory/ContextMenu/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/Directory/ContextMenu/index.jsx
import { useRef, useEffect } from "react"; export default function ContextMenu({ contextMenu, closeContextMenu, files, selectedItems, setSelectedItems, }) { const contextMenuRef = useRef(null); useEffect(() => { const handleClickOutside = (event) => { if ( contextMenuRef.current && !contextMenuRef.current.contains(event.target) ) { closeContextMenu(); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [closeContextMenu]); const isAllSelected = () => { const allItems = files.items.flatMap((folder) => [ folder.name, ...folder.items.map((file) => file.id), ]); return allItems.every((item) => selectedItems[item]); }; const toggleSelectAll = () => { if (isAllSelected()) { setSelectedItems({}); } else { const newSelectedItems = {}; files.items.forEach((folder) => { newSelectedItems[folder.name] = true; folder.items.forEach((file) => { newSelectedItems[file.id] = true; }); }); setSelectedItems(newSelectedItems); } closeContextMenu(); }; if (!contextMenu.visible) return null; return ( <div ref={contextMenuRef} style={{ position: "fixed", top: `${contextMenu.y}px`, left: `${contextMenu.x}px`, zIndex: 1000, }} className="bg-theme-bg-secondary border border-theme-modal-border rounded-md shadow-lg" > <button onClick={toggleSelectAll} className="block w-full text-left px-4 py-2 text-sm text-theme-text-primary hover:bg-theme-file-picker-hover" > {isAllSelected() ? "Unselect All" : "Select All"} </button> <button onClick={closeContextMenu} className="block w-full text-left px-4 py-2 text-sm text-theme-text-primary hover:bg-theme-file-picker-hover" > Cancel </button> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/Directory/FolderSelectionPopup/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/Directory/FolderSelectionPopup/index.jsx
import { middleTruncate } from "@/utils/directories"; export default function FolderSelectionPopup({ folders, onSelect, onClose }) { const handleFolderSelect = (folder) => { onSelect(folder); onClose(); }; return ( <div className="absolute bottom-full left-0 mb-2 bg-white rounded-lg shadow-lg max-h-40 overflow-y-auto no-scroll"> <ul> {folders.map((folder) => ( <li key={folder.name} onClick={() => handleFolderSelect(folder)} className="px-4 py-2 text-xs text-gray-700 hover:bg-gray-200 rounded-lg cursor-pointer whitespace-nowrap" > {middleTruncate(folder.name, 25)} </li> ))} </ul> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/Directory/FileRow/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/Directory/FileRow/index.jsx
import React from "react"; import { formatDateTimeAsMoment, getFileExtension, middleTruncate, } from "@/utils/directories"; import { File } from "@phosphor-icons/react"; export default function FileRow({ item, selected, toggleSelection }) { return ( <tr onClick={() => toggleSelection(item)} className={`text-theme-text-primary text-xs grid grid-cols-12 py-2 pl-3.5 pr-8 hover:bg-theme-file-picker-hover cursor-pointer file-row ${ selected ? "selected light:text-white" : "" }`} > <div data-tooltip-id="directory-item" className="col-span-10 w-fit flex gap-x-[4px] items-center relative" data-tooltip-content={JSON.stringify({ title: item.title, date: formatDateTimeAsMoment(item?.published), extension: getFileExtension(item.url), })} > <div className={`shrink-0 w-3 h-3 rounded border-[1px] border-solid border-white ${ selected ? "text-white" : "text-theme-text-primary light:invert" } flex justify-center items-center cursor-pointer`} role="checkbox" aria-checked={selected} tabIndex={0} > {selected && <div className="w-2 h-2 bg-white rounded-[2px]" />} </div> <File className="shrink-0 text-base font-bold w-4 h-4 mr-[3px]" weight="fill" /> <p className="whitespace-nowrap overflow-hidden text-ellipsis max-w-[400px]"> {middleTruncate(item.title, 55)} </p> </div> <div className="col-span-2 flex justify-end items-center"> {item?.cached && ( <div className="bg-theme-settings-input-active rounded-3xl"> <p className="text-xs px-2 py-0.5">Cached</p> </div> )} </div> </tr> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/Directory/FolderRow/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/Directory/FolderRow/index.jsx
import { useState } from "react"; import FileRow from "../FileRow"; import { CaretDown, FolderNotch } from "@phosphor-icons/react"; import { middleTruncate } from "@/utils/directories"; export default function FolderRow({ item, selected, onRowClick, toggleSelection, isSelected, autoExpanded = false, }) { const [expanded, setExpanded] = useState(autoExpanded); const handleExpandClick = (event) => { event.stopPropagation(); setExpanded(!expanded); }; return ( <> <tr onClick={onRowClick} className={`text-theme-text-primary text-xs grid grid-cols-12 py-2 pl-3.5 pr-8 hover:bg-theme-file-picker-hover cursor-pointer file-row ${ selected ? "selected light:text-white !text-white" : "" }`} > <div className={`col-span-6 flex gap-x-[4px] items-center ${ selected ? "!text-white" : "text-theme-text-primary" }`} > <div className={`shrink-0 w-3 h-3 rounded border-[1px] border-solid border-white ${ selected ? "text-white" : "text-theme-text-primary light:invert" } flex justify-center items-center cursor-pointer`} role="checkbox" aria-checked={selected} tabIndex={0} onClick={(event) => { event.stopPropagation(); toggleSelection(item); }} > {selected && <div className="w-2 h-2 bg-white rounded-[2px]" />} </div> <div onClick={handleExpandClick} className={`transform transition-transform duration-200 ${ expanded ? "rotate-360" : " rotate-270" }`} > <CaretDown className="text-base font-bold w-4 h-4" /> </div> <FolderNotch className="shrink-0 text-base font-bold w-4 h-4 mr-[3px]" weight="fill" /> <p className="whitespace-nowrap overflow-show max-w-[400px]"> {middleTruncate(item.name, 35)} </p> </div> <p className="col-span-2 pl-3.5" /> <p className="col-span-2 pl-2" /> </tr> {expanded && ( <> {item.items.map((fileItem) => ( <FileRow key={fileItem.id} item={fileItem} selected={isSelected(fileItem.id)} toggleSelection={toggleSelection} /> ))} </> )} </> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/WorkspaceDirectory/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/WorkspaceDirectory/index.jsx
import PreLoader from "@/components/Preloader"; import { dollarFormat } from "@/utils/numbers"; import WorkspaceFileRow from "./WorkspaceFileRow"; import { memo, useEffect, useState } from "react"; import ModalWrapper from "@/components/ModalWrapper"; import { Eye, PushPin } from "@phosphor-icons/react"; import { SEEN_DOC_PIN_ALERT, SEEN_WATCH_ALERT } from "@/utils/constants"; import paths from "@/utils/paths"; import { Link } from "react-router-dom"; import Workspace from "@/models/workspace"; import { Tooltip } from "react-tooltip"; import { safeJsonParse } from "@/utils/request"; import { useTranslation } from "react-i18next"; function WorkspaceDirectory({ workspace, files, highlightWorkspace, loading, loadingMessage, setLoadingMessage, setLoading, fetchKeys, hasChanges, saveChanges, embeddingCosts, movedItems, }) { const { t } = useTranslation(); const [selectedItems, setSelectedItems] = useState({}); const toggleSelection = (item) => { setSelectedItems((prevSelectedItems) => { const newSelectedItems = { ...prevSelectedItems }; if (newSelectedItems[item.id]) { delete newSelectedItems[item.id]; } else { newSelectedItems[item.id] = true; } return newSelectedItems; }); }; const toggleSelectAll = () => { const allItems = files.items.flatMap((folder) => folder.items); const allSelected = allItems.every((item) => selectedItems[item.id]); if (allSelected) { setSelectedItems({}); } else { const newSelectedItems = {}; allItems.forEach((item) => { newSelectedItems[item.id] = true; }); setSelectedItems(newSelectedItems); } }; const removeSelectedItems = async () => { setLoading(true); setLoadingMessage("Removing selected files from workspace"); const itemsToRemove = Object.keys(selectedItems).map((itemId) => { const folder = files.items.find((f) => f.items.some((i) => i.id === itemId) ); const item = folder.items.find((i) => i.id === itemId); return `${folder.name}/${item.name}`; }); try { await Workspace.modifyEmbeddings(workspace.slug, { adds: [], deletes: itemsToRemove, }); await fetchKeys(true); setSelectedItems({}); } catch (error) { console.error("Failed to remove documents:", error); } setLoadingMessage(""); setLoading(false); }; const handleSaveChanges = (e) => { setSelectedItems({}); saveChanges(e); }; if (loading) { return ( <div className="px-8"> <div className="flex items-center justify-start w-[560px]"> <h3 className="text-white text-base font-bold ml-5"> {workspace.name} </h3> </div> <div className="relative w-[560px] h-[445px] bg-theme-settings-input-bg rounded-2xl mt-5 border border-theme-modal-border"> <div className="text-white/80 text-xs grid grid-cols-12 py-2 px-3.5 border-b border-white/20 light:border-theme-modal-border bg-theme-settings-input-bg sticky top-0 z-10 rounded-t-2xl"> <div className="col-span-10 flex items-center gap-x-[4px]"> <div className="shrink-0 w-3 h-3" /> <p className="ml-[7px] text-theme-text-primary">Name</p> </div> <p className="col-span-2" /> </div> <div className="w-full h-[calc(100%-40px)] flex items-center justify-center flex-col gap-y-5"> <PreLoader /> <p className="text-theme-text-primary text-sm font-semibold animate-pulse text-center w-1/3"> {loadingMessage} </p> </div> </div> </div> ); } return ( <> <div className="px-8"> <div className="flex items-center justify-start w-[560px]"> <h3 className="text-white text-base font-bold ml-5"> {workspace.name} </h3> </div> <div className="relative w-[560px] h-[445px] mt-5"> <div className={`absolute inset-0 rounded-2xl ${ highlightWorkspace ? "border-4 border-cyan-300/80 z-[999]" : "" }`} /> <div className="relative w-full h-full bg-theme-settings-input-bg rounded-2xl overflow-hidden border border-theme-modal-border"> <div className="text-white/80 text-xs grid grid-cols-12 py-2 px-3.5 border-b border-white/20 light:border-theme-modal-border bg-theme-settings-input-bg sticky top-0 z-10"> <div className="col-span-10 flex items-center gap-x-[4px]"> {!hasChanges && files.items.some((folder) => folder.items.length > 0) ? ( <div className={`shrink-0 w-3 h-3 rounded border-[1px] border-solid border-white text-theme-text-primary light:invert flex justify-center items-center cursor-pointer`} role="checkbox" aria-checked={ Object.keys(selectedItems).length === files.items.reduce( (sum, folder) => sum + folder.items.length, 0 ) } tabIndex={0} onClick={toggleSelectAll} > {Object.keys(selectedItems).length === files.items.reduce( (sum, folder) => sum + folder.items.length, 0 ) && <div className="w-2 h-2 bg-white rounded-[2px]" />} </div> ) : ( <div className="shrink-0 w-3 h-3" /> )} <p className="ml-[7px] text-theme-text-primary">Name</p> </div> <p className="col-span-2" /> </div> <div className="overflow-y-auto h-[calc(100%-40px)]"> {files.items.some((folder) => folder.items.length > 0) || movedItems.length > 0 ? ( <RenderFileRows files={files} movedItems={movedItems} workspace={workspace} > {({ item, folder }) => ( <WorkspaceFileRow key={item.id} item={item} folderName={folder.name} workspace={workspace} setLoading={setLoading} setLoadingMessage={setLoadingMessage} fetchKeys={fetchKeys} hasChanges={hasChanges} movedItems={movedItems} selected={selectedItems[item.id]} toggleSelection={() => toggleSelection(item)} disableSelection={hasChanges} setSelectedItems={setSelectedItems} /> )} </RenderFileRows> ) : ( <div className="w-full h-full flex items-center justify-center"> <p className="text-white text-opacity-40 text-sm font-medium"> {t("connectors.directory.no_docs")} </p> </div> )} </div> {Object.keys(selectedItems).length > 0 && !hasChanges && ( <div className="absolute bottom-[12px] left-0 right-0 flex justify-center pointer-events-none"> <div className="mx-auto bg-white/40 light:bg-white rounded-lg py-1 px-2 pointer-events-auto light:shadow-lg"> <div className="flex flex-row items-center gap-x-2"> <button onClick={toggleSelectAll} className="border-none text-sm font-semibold bg-white light:bg-[#E0F2FE] h-[30px] px-2.5 rounded-lg hover:bg-neutral-800/80 hover:text-white light:text-[#026AA2] light:hover:bg-[#026AA2] light:hover:text-white" > {Object.keys(selectedItems).length === files.items.reduce( (sum, folder) => sum + folder.items.length, 0 ) ? t("connectors.directory.deselect_all") : t("connectors.directory.select_all")} </button> <button onClick={removeSelectedItems} className="border-none text-sm font-semibold bg-white light:bg-[#E0F2FE] h-[30px] px-2.5 rounded-lg hover:bg-neutral-800/80 hover:text-white light:text-[#026AA2] light:hover:bg-[#026AA2] light:hover:text-white" > {t("connectors.directory.remove_selected")} </button> </div> </div> </div> )} </div> </div> {hasChanges && ( <div className="flex items-center justify-between py-6"> <div className="text-white/80"> <p className="text-sm font-semibold"> {embeddingCosts === 0 ? "" : `Estimated Cost: ${ embeddingCosts < 0.01 ? `< $0.01` : dollarFormat(embeddingCosts) }`} </p> <p className="mt-2 text-xs italic" hidden={embeddingCosts === 0}> {t("connectors.directory.costs")} </p> </div> <button onClick={(e) => handleSaveChanges(e)} className="border border-slate-200 px-5 py-2.5 rounded-lg text-white text-sm items-center flex gap-x-2 hover:bg-slate-200 hover:text-slate-800 focus:ring-gray-800" > {t("connectors.directory.save_embed")} </button> </div> )} </div> <PinAlert /> <DocumentWatchAlert /> <WorkspaceDocumentTooltips /> </> ); } const PinAlert = memo(() => { const { t } = useTranslation(); const [showAlert, setShowAlert] = useState(false); function dismissAlert() { setShowAlert(false); window.localStorage.setItem(SEEN_DOC_PIN_ALERT, "1"); window.removeEventListener(handlePinEvent); } function handlePinEvent() { if (!!window?.localStorage?.getItem(SEEN_DOC_PIN_ALERT)) return; setShowAlert(true); } useEffect(() => { if (!window || !!window?.localStorage?.getItem(SEEN_DOC_PIN_ALERT)) return; window?.addEventListener("pinned_document", handlePinEvent); }, []); return ( <ModalWrapper isOpen={showAlert} noPortal={true}> <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="flex items-center gap-2"> <PushPin className="text-theme-text-primary text-lg w-6 h-6" weight="regular" /> <h3 className="text-xl font-semibold text-white"> {t("connectors.pinning.what_pinning")} </h3> </div> </div> <div className="py-7 px-9 space-y-2 flex-col"> <div className="w-full text-white text-md flex flex-col gap-y-2"> <p> <span dangerouslySetInnerHTML={{ __html: t("connectors.pinning.pin_explained_block1"), }} /> </p> <p> <span dangerouslySetInnerHTML={{ __html: t("connectors.pinning.pin_explained_block2"), }} /> </p> <p>{t("connectors.pinning.pin_explained_block3")}</p> </div> </div> <div className="flex w-full justify-end items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button onClick={dismissAlert} className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > {t("connectors.pinning.accept")} </button> </div> </div> </ModalWrapper> ); }); const DocumentWatchAlert = memo(() => { const { t } = useTranslation(); const [showAlert, setShowAlert] = useState(false); function dismissAlert() { setShowAlert(false); window.localStorage.setItem(SEEN_WATCH_ALERT, "1"); window.removeEventListener(handlePinEvent); } function handlePinEvent() { if (!!window?.localStorage?.getItem(SEEN_WATCH_ALERT)) return; setShowAlert(true); } useEffect(() => { if (!window || !!window?.localStorage?.getItem(SEEN_WATCH_ALERT)) return; window?.addEventListener("watch_document_for_changes", handlePinEvent); }, []); return ( <ModalWrapper isOpen={showAlert} noPortal={true}> <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="flex items-center gap-2"> <Eye className="text-theme-text-primary text-lg w-6 h-6" weight="regular" /> <h3 className="text-xl font-semibold text-white"> {t("connectors.watching.what_watching")} </h3> </div> </div> <div className="py-7 px-9 space-y-2 flex-col"> <div className="w-full text-white text-md flex flex-col gap-y-2"> <p> <span dangerouslySetInnerHTML={{ __html: t("connectors.watching.watch_explained_block1"), }} /> </p> <p>{t("connectors.watching.watch_explained_block2")}</p> <p> {t("connectors.watching.watch_explained_block3_start")} <Link to={paths.experimental.liveDocumentSync.manage()} className="text-blue-600 underline" > {t("connectors.watching.watch_explained_block3_link")} </Link> {t("connectors.watching.watch_explained_block3_end")} </p> </div> </div> <div className="flex w-full justify-end items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button onClick={dismissAlert} className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm" > {t("connectors.watching.accept")} </button> </div> </div> </ModalWrapper> ); }); function RenderFileRows({ files, movedItems, children, workspace }) { function sortMovedItemsAndFiles(a, b) { const aIsMovedItem = movedItems.some((movedItem) => movedItem.id === a.id); const bIsMovedItem = movedItems.some((movedItem) => movedItem.id === b.id); if (aIsMovedItem && !bIsMovedItem) return -1; if (!aIsMovedItem && bIsMovedItem) return 1; // Sort pinned items to the top const aIsPinned = a.pinnedWorkspaces?.includes(workspace.id); const bIsPinned = b.pinnedWorkspaces?.includes(workspace.id); if (aIsPinned && !bIsPinned) return -1; if (!aIsPinned && bIsPinned) return 1; return 0; } return files.items .flatMap((folder) => folder.items) .sort(sortMovedItemsAndFiles) .map((item) => { const folder = files.items.find((f) => f.items.includes(item)); return children({ item, folder }); }); } /** * Tooltips for the workspace directory components. Renders when the workspace directory is shown * or updated so that tooltips are attached as the items are changed. */ function WorkspaceDocumentTooltips() { return ( <> <Tooltip id="ws-directory-item" place="bottom" delayShow={800} className="tooltip invert light:invert-0 z-99 max-w-[200px]" render={({ content }) => { const data = safeJsonParse(content, null); if (!data) return null; return ( <div className="text-xs"> <p className="text-white light:invert font-medium break-all"> {data.title} </p> <div className="flex mt-1 gap-x-2"> <p className=""> Date: <b>{data.date}</b> </p> <p className=""> Type: <b>{data.extension}</b> </p> </div> </div> ); }} /> <Tooltip id="watch-changes" place="bottom" delayShow={300} className="tooltip invert !text-xs" /> <Tooltip id="pin-document" place="bottom" delayShow={300} className="tooltip invert !text-xs" /> <Tooltip id="remove-document" place="bottom" delayShow={300} className="tooltip invert !text-xs" /> </> ); } export default memo(WorkspaceDirectory);
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/ManageWorkspace/Documents/WorkspaceDirectory/WorkspaceFileRow/index.jsx
frontend/src/components/Modals/ManageWorkspace/Documents/WorkspaceDirectory/WorkspaceFileRow/index.jsx
import { memo, useState } from "react"; import { formatDateTimeAsMoment, getFileExtension, middleTruncate, } from "@/utils/directories"; import { ArrowUUpLeft, Eye, File, PushPin } from "@phosphor-icons/react"; import Workspace from "@/models/workspace"; import showToast from "@/utils/toast"; import System from "@/models/system"; export default function WorkspaceFileRow({ item, folderName, workspace, setLoading, setLoadingMessage, fetchKeys, hasChanges, movedItems, selected, toggleSelection, disableSelection, setSelectedItems, }) { const onRemoveClick = async (e) => { e.stopPropagation(); setLoading(true); try { setLoadingMessage(`Removing file from workspace`); await Workspace.modifyEmbeddings(workspace.slug, { adds: [], deletes: [`${folderName}/${item.name}`], }); await fetchKeys(true); } catch (error) { console.error("Failed to remove document:", error); } setSelectedItems({}); setLoadingMessage(""); setLoading(false); }; function toggleRowSelection(e) { if (disableSelection) return; e.stopPropagation(); toggleSelection(); } function handleRowSelection(e) { e.stopPropagation(); toggleSelection(); } const isMovedItem = movedItems?.some((movedItem) => movedItem.id === item.id); return ( <div className={`text-theme-text-primary text-xs grid grid-cols-12 py-2 pl-3.5 pr-8 h-[34px] items-center file-row ${ !disableSelection ? "hover:bg-theme-file-picker-hover cursor-pointer" : "" } ${isMovedItem ? "selected light:text-white" : ""} ${ selected ? "selected light:text-white" : "" }`} onClick={toggleRowSelection} > <div className="col-span-10 w-fit flex gap-x-[2px] items-center relative" data-tooltip-id="ws-directory-item" data-tooltip-content={JSON.stringify({ title: item.title, date: formatDateTimeAsMoment(item?.published), extension: getFileExtension(item.url), })} > <div className="shrink-0 w-3 h-3"> {!disableSelection ? ( <div className={`shrink-0 w-3 h-3 rounded border-[1px] border-solid border-white ${ selected ? "text-white" : "text-theme-text-primary light:invert" } flex justify-center items-center cursor-pointer`} role="checkbox" aria-checked={selected} tabIndex={0} onClick={handleRowSelection} > {selected && <div className="w-2 h-2 bg-white rounded-[2px]" />} </div> ) : null} </div> <File className="shrink-0 text-base font-bold w-4 h-4 mr-[3px] ml-1" weight="fill" /> <p className="whitespace-nowrap overflow-hidden text-ellipsis max-w-[400px]"> {middleTruncate(item.title, 50)} </p> </div> <div className="col-span-2 flex justify-end items-center"> {hasChanges ? ( <div className="w-4 h-4 ml-2 flex-shrink-0" /> ) : ( <div className="flex gap-x-2 items-center"> <WatchForChanges workspace={workspace} docPath={`${folderName}/${item.name}`} item={item} /> <PinItemToWorkspace workspace={workspace} docPath={`${folderName}/${item.name}`} item={item} /> <RemoveItemFromWorkspace item={item} onClick={onRemoveClick} /> </div> )} </div> </div> ); } const PinItemToWorkspace = memo(({ workspace, docPath, item }) => { const [pinned, setPinned] = useState( item?.pinnedWorkspaces?.includes(workspace.id) || false ); const pinEvent = new CustomEvent("pinned_document"); const updatePinStatus = async (e) => { try { e.stopPropagation(); if (!pinned) window.dispatchEvent(pinEvent); const success = await Workspace.setPinForDocument( workspace.slug, docPath, !pinned ); if (!success) { showToast(`Failed to ${!pinned ? "pin" : "unpin"} document.`, "error", { clear: true, }); return; } showToast( `Document ${!pinned ? "pinned to" : "unpinned from"} workspace`, "success", { clear: true } ); setPinned(!pinned); } catch (error) { showToast(`Failed to pin document. ${error.message}`, "error", { clear: true, }); return; } }; if (!item) return <div className="w-[16px] p-[2px] ml-2" />; return ( <div onClick={updatePinStatus} className="group flex items-center ml-2 cursor-pointer" data-tooltip-id="pin-document" data-tooltip-content={ pinned ? "Un-pin from workspace" : "Pin to workspace" } > {pinned ? ( <div className="bg-theme-settings-input-active group-hover:bg-red-500/20 rounded-3xl whitespace-nowrap"> <p className="text-xs px-2 py-0.5 group-hover:text-red-500"> <span className="group-hover:hidden">Pinned</span> <span className="hidden group-hover:inline">Un-pin</span> </p> </div> ) : ( <PushPin size={16} weight="regular" className="outline-none text-base font-bold flex-shrink-0" /> )} </div> ); }); const WatchForChanges = memo(({ workspace, docPath, item }) => { const [watched, setWatched] = useState(item?.watched || false); const watchEvent = new CustomEvent("watch_document_for_changes"); const updateWatchStatus = async (e) => { try { e.stopPropagation(); if (!watched) window.dispatchEvent(watchEvent); const success = await System.experimentalFeatures.liveSync.setWatchStatusForDocument( workspace.slug, docPath, !watched ); if (!success) { showToast( `Failed to ${!watched ? "watch" : "unwatch"} document.`, "error", { clear: true, } ); return; } showToast( `Document ${ !watched ? "will be watched for changes" : "will no longer be watched for changes" }.`, "success", { clear: true } ); setWatched(!watched); } catch (error) { showToast(`Failed to watch document. ${error.message}`, "error", { clear: true, }); return; } }; if (!item || !item.canWatch) return <div className="w-[16px] p-[2px] ml-2" />; return ( <div className="group flex gap-x-2 items-center hover:bg-theme-file-picker-hover p-[2px] rounded ml-2 cursor-pointer" onClick={updateWatchStatus} data-tooltip-id="watch-changes" data-active={watched} data-tooltip-content={ watched ? "Stop watching for changes" : "Watch document for changes" } > <Eye size={16} weight="regular" className="outline-none text-base font-bold flex-shrink-0 group-hover:hidden group-data-[active=true]:hidden" /> <Eye size={16} weight="fill" className="outline-none text-base font-bold flex-shrink-0 hidden group-hover:block group-data-[active=true]:block" /> </div> ); }); const RemoveItemFromWorkspace = ({ item, onClick }) => { return ( <div> <ArrowUUpLeft data-tooltip-id="remove-document" data-tooltip-content="Remove document from workspace" onClick={onClick} className="text-base font-bold w-4 h-4 ml-2 flex-shrink-0 cursor-pointer" /> </div> ); };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/Modals/DisplayRecoveryCodeModal/index.jsx
frontend/src/components/Modals/DisplayRecoveryCodeModal/index.jsx
import showToast from "@/utils/toast"; import { DownloadSimple, Key } from "@phosphor-icons/react"; import { saveAs } from "file-saver"; import { useState } from "react"; import ModalWrapper from "@/components/ModalWrapper"; export default function RecoveryCodeModal({ recoveryCodes, onDownloadComplete, onClose, }) { const [downloadClicked, setDownloadClicked] = useState(false); const downloadRecoveryCodes = () => { const blob = new Blob([recoveryCodes.join("\n")], { type: "text/plain" }); saveAs(blob, "recovery_codes.txt"); setDownloadClicked(true); }; const handleClose = () => { if (downloadClicked) { onDownloadComplete(); onClose(); } }; const handleCopyToClipboard = () => { navigator.clipboard.writeText(recoveryCodes.join(",\n")).then(() => { showToast("Recovery codes copied to clipboard", "success", { clear: true, }); }); }; return ( <ModalWrapper isOpen={true}> <div className="w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border overflow-hidden"> <div className="relative p-6 border-b rounded-t border-theme-modal-border"> <div className="w-full flex gap-x-2 items-center"> <Key size={24} className="text-white" weight="bold" /> <h3 className="text-xl font-semibold text-white overflow-hidden overflow-ellipsis whitespace-nowrap"> Recovery Codes </h3> </div> </div> <div className="h-full w-full overflow-y-auto" style={{ maxHeight: "calc(100vh - 200px)" }} > <div className="py-7 px-9 space-y-2 flex-col"> <p className="text-sm text-white flex flex-col"> In order to reset your password in the future, you will need these recovery codes. Download or copy your recovery codes to save them.{" "} <br /> <b className="mt-4">These recovery codes are only shown once!</b> </p> <div className="border-none bg-theme-settings-input-bg text-white hover:text-primary-button flex items-center justify-center rounded-md mt-6 cursor-pointer" onClick={handleCopyToClipboard} > <ul className="space-y-2 md:p-6 p-4"> {recoveryCodes.map((code, index) => ( <li key={index} className="md:text-sm text-xs"> {code} </li> ))} </ul> </div> </div> <div className="flex w-full justify-end items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <button type="button" className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm flex items-center gap-x-2" onClick={downloadClicked ? handleClose : downloadRecoveryCodes} > {downloadClicked ? ( "Close" ) : ( <> <DownloadSimple weight="bold" size={18} /> <p>Download</p> </> )} </button> </div> </div> </div> </ModalWrapper> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/OpenRouterOptions/index.jsx
frontend/src/components/EmbeddingSelection/OpenRouterOptions/index.jsx
import { useState, useEffect } from "react"; import System from "@/models/system"; export default function OpenRouterOptions({ settings }) { return ( <div className="w-full flex flex-col gap-y-4"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> API Key </label> <input type="password" name="OpenRouterApiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="OpenRouter API Key" defaultValue={settings?.OpenRouterApiKey ? "*".repeat(20) : ""} required={true} autoComplete="off" spellCheck={false} /> </div> <OpenRouterEmbeddingModelSelection settings={settings} /> </div> </div> ); } function OpenRouterEmbeddingModelSelection({ settings }) { const [models, setModels] = useState([]); const [loading, setLoading] = useState(true); const [selectedModel, setSelectedModel] = useState( settings?.EmbeddingModelPref || "" ); useEffect(() => { async function fetchModels() { setLoading(true); const response = await System.customModels("openrouter-embedder"); const fetchedModels = response?.models || []; setModels(fetchedModels); if ( settings?.EmbeddingModelPref && fetchedModels.some((m) => m.id === settings.EmbeddingModelPref) ) { setSelectedModel(settings.EmbeddingModelPref); } else if (fetchedModels.length > 0) { setSelectedModel(fetchedModels[0].id); } setLoading(false); } fetchModels(); }, [settings?.EmbeddingModelPref]); if (loading) { return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" disabled={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <option disabled={true} selected={true}> -- loading available models -- </option> </select> </div> ); } return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" required={true} value={selectedModel} onChange={(e) => setSelectedModel(e.target.value)} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > {models.map((model) => ( <option key={model.id} value={model.id}> {model.name} </option> ))} </select> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/LMStudioOptions/index.jsx
frontend/src/components/EmbeddingSelection/LMStudioOptions/index.jsx
import React, { useEffect, useState } from "react"; import System from "@/models/system"; import PreLoader from "@/components/Preloader"; import { LMSTUDIO_COMMON_URLS } from "@/utils/constants"; import { CaretDown, CaretUp, Info } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; import useProviderEndpointAutoDiscovery from "@/hooks/useProviderEndpointAutoDiscovery"; export default function LMStudioEmbeddingOptions({ settings }) { const { autoDetecting: loading, basePath, basePathValue, showAdvancedControls, setShowAdvancedControls, handleAutoDetectClick, } = useProviderEndpointAutoDiscovery({ provider: "lmstudio", initialBasePath: settings?.EmbeddingBasePath, ENDPOINTS: LMSTUDIO_COMMON_URLS, }); const [maxChunkLength, setMaxChunkLength] = useState( settings?.EmbeddingModelMaxChunkLength || 8192 ); const handleMaxChunkLengthChange = (e) => { setMaxChunkLength(Number(e.target.value)); }; return ( <div className="w-full flex flex-col gap-y-7"> <div className="w-full flex items-start gap-[36px] mt-1.5"> <LMStudioModelSelection settings={settings} basePath={basePath.value} /> <div className="flex flex-col w-60"> <div data-tooltip-place="top" data-tooltip-id="max-embedding-chunk-length-tooltip" className="flex gap-x-1 items-center mb-3" > <Info size={16} className="text-theme-text-secondary cursor-pointer" /> <label className="text-white text-sm font-semibold block"> Max embedding chunk length </label> <Tooltip id="max-embedding-chunk-length-tooltip"> Maximum length of text chunks, in characters, for embedding. </Tooltip> </div> <input type="number" name="EmbeddingModelMaxChunkLength" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="8192" min={1} value={maxChunkLength} onChange={handleMaxChunkLengthChange} onScroll={(e) => e.target.blur()} required={true} autoComplete="off" /> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Maximum length of text chunks, in characters, for embedding. </p> </div> </div> <div className="flex justify-start mt-4"> <button onClick={(e) => { e.preventDefault(); setShowAdvancedControls(!showAdvancedControls); }} className="border-none text-theme-text-primary hover:text-theme-text-secondary flex items-center text-sm" > {showAdvancedControls ? "Hide" : "Show"} Manual Endpoint Input {showAdvancedControls ? ( <CaretUp size={14} className="ml-1" /> ) : ( <CaretDown size={14} className="ml-1" /> )} </button> </div> <div hidden={!showAdvancedControls}> <div className="w-full flex items-start gap-4"> <div className="flex flex-col w-60"> <div className="flex justify-between items-center mb-2"> <label className="text-white text-sm font-semibold"> LM Studio Base URL </label> {loading ? ( <PreLoader size="6" /> ) : ( <> {!basePathValue.value && ( <button onClick={handleAutoDetectClick} className="bg-primary-button text-xs font-medium px-2 py-1 rounded-lg hover:bg-secondary hover:text-white shadow-[0_4px_14px_rgba(0,0,0,0.25)]" > Auto-Detect </button> )} </> )} </div> <input type="url" name="EmbeddingBasePath" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="http://localhost:1234/v1" value={basePathValue.value} required={true} autoComplete="off" spellCheck={false} onChange={basePath.onChange} onBlur={basePath.onBlur} /> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Enter the URL where LM Studio is running. </p> </div> </div> </div> </div> ); } function LMStudioModelSelection({ settings, basePath = null }) { const [customModels, setCustomModels] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function findCustomModels() { if (!basePath) { setCustomModels([]); setLoading(false); return; } setLoading(true); try { const { models } = await System.customModels( "lmstudio", null, basePath ); setCustomModels(models || []); } catch (error) { console.error("Failed to fetch custom models:", error); setCustomModels([]); } setLoading(false); } findCustomModels(); }, [basePath]); if (loading || customModels.length == 0) { return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-2"> LM Studio Embedding Model </label> <select name="EmbeddingModelPref" disabled={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <option disabled={true} selected={true}> {!!basePath ? "--loading available models--" : "Enter LM Studio URL first"} </option> </select> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Select the LM Studio model for embeddings. Models will load after entering a valid LM Studio URL. </p> </div> ); } return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-2"> LM Studio Embedding Model </label> <select name="EmbeddingModelPref" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > {customModels.length > 0 && ( <optgroup label="Your loaded models"> {customModels.map((model) => { return ( <option key={model.id} value={model.id} selected={settings.EmbeddingModelPref === model.id} > {model.id} </option> ); })} </optgroup> )} </select> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Choose the LM Studio model you want to use for generating embeddings. </p> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/OllamaOptions/index.jsx
frontend/src/components/EmbeddingSelection/OllamaOptions/index.jsx
import React, { useEffect, useState } from "react"; import System from "@/models/system"; import PreLoader from "@/components/Preloader"; import { OLLAMA_COMMON_URLS } from "@/utils/constants"; import { CaretDown, CaretUp, Info } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; import useProviderEndpointAutoDiscovery from "@/hooks/useProviderEndpointAutoDiscovery"; export default function OllamaEmbeddingOptions({ settings }) { const { autoDetecting: loading, basePath, basePathValue, showAdvancedControls, setShowAdvancedControls, handleAutoDetectClick, authToken, authTokenValue, } = useProviderEndpointAutoDiscovery({ provider: "ollama", initialBasePath: settings?.EmbeddingBasePath, ENDPOINTS: OLLAMA_COMMON_URLS, }); const [maxChunkLength, setMaxChunkLength] = useState( settings?.EmbeddingModelMaxChunkLength || 8192 ); const [batchSize, setBatchSize] = useState( settings?.OllamaEmbeddingBatchSize || 1 ); const handleMaxChunkLengthChange = (e) => { setMaxChunkLength(Number(e.target.value)); }; const handleBatchSizeChange = (e) => { setBatchSize(Number(e.target.value)); }; return ( <div className="w-full flex flex-col gap-y-7"> <div className="w-full flex items-start gap-[36px] mt-1.5"> <OllamaEmbeddingModelSelection settings={settings} basePath={basePath.value} /> <div className="flex flex-col w-60"> <div data-tooltip-place="top" data-tooltip-id="max-embedding-chunk-length-tooltip" className="flex gap-x-1 items-center mb-3" > <label className="text-white text-sm font-semibold block"> Max embedding chunk length </label> <Info size={16} className="text-theme-text-secondary cursor-pointer" /> <Tooltip id="max-embedding-chunk-length-tooltip"> Maximum length of text chunks, in characters, for embedding. </Tooltip> </div> <input type="number" name="EmbeddingModelMaxChunkLength" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="8192" min={1} value={maxChunkLength} onChange={handleMaxChunkLengthChange} onScroll={(e) => e.target.blur()} required={true} autoComplete="off" /> </div> </div> <div className="flex justify-start mt-4"> <button onClick={(e) => { e.preventDefault(); setShowAdvancedControls(!showAdvancedControls); }} className="border-none text-theme-text-primary hover:text-theme-text-secondary flex items-center text-sm" > {showAdvancedControls ? "Hide" : "Show"} Advanced Settings {showAdvancedControls ? ( <CaretUp size={14} className="ml-1" /> ) : ( <CaretDown size={14} className="ml-1" /> )} </button> </div> <div hidden={!showAdvancedControls}> <div className="w-full flex items-start gap-4"> <div className="flex flex-col w-60"> <div className="flex justify-between items-center mb-2"> <label className="text-white text-sm font-semibold"> Ollama Base URL </label> {loading ? ( <PreLoader size="6" /> ) : ( <> {!basePathValue.value && ( <button onClick={handleAutoDetectClick} className="bg-primary-button text-xs font-medium px-2 py-1 rounded-lg hover:bg-secondary hover:text-white shadow-[0_4px_14px_rgba(0,0,0,0.25)]" > Auto-Detect </button> )} </> )} </div> <input type="url" name="EmbeddingBasePath" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="http://127.0.0.1:11434" value={basePathValue.value} required={true} autoComplete="off" spellCheck={false} onChange={basePath.onChange} onBlur={basePath.onBlur} /> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Enter the URL where Ollama is running. </p> </div> <div className="flex flex-col w-60"> <div data-tooltip-place="top" data-tooltip-id="ollama-batch-size-tooltip" className="flex gap-x-1 items-center mb-3" > <label className="text-white text-sm font-semibold block"> Embedding batch size </label> <Info size={16} className="text-theme-text-secondary cursor-pointer" /> <Tooltip id="ollama-batch-size-tooltip"> Number of text chunks to embed in parallel. Higher values improve speed but use more memory. Default is 1. </Tooltip> </div> <input type="number" name="OllamaEmbeddingBatchSize" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="1" min={1} value={batchSize} onChange={handleBatchSizeChange} onScroll={(e) => e.target.blur()} required={true} autoComplete="off" /> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Increase this value to process multiple chunks simultaneously for faster embedding. </p> </div> <div> <label className="text-white font-semibold block mb-3 text-sm"> Auth Token (optional) </label> <input type="password" name="OllamaLLMAuthToken" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Enter your Auth Token" defaultValue={settings?.OllamaLLMAuthToken ? "*".repeat(20) : ""} value={authTokenValue.value} onChange={authToken.onChange} onBlur={authToken.onBlur} required={false} autoComplete="off" spellCheck={false} /> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Enter a <code>Bearer</code> Auth Token for interacting with your Ollama server. <br /> Used <b>only</b> if running Ollama behind an authentication server. </p> </div> </div> </div> </div> ); } function OllamaEmbeddingModelSelection({ settings, basePath = null }) { const [customModels, setCustomModels] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function findCustomModels() { if (!basePath) { setCustomModels([]); setLoading(false); return; } setLoading(true); try { const { models } = await System.customModels("ollama", null, basePath); setCustomModels(models || []); } catch (error) { console.error("Failed to fetch custom models:", error); setCustomModels([]); } setLoading(false); } findCustomModels(); }, [basePath]); if (loading || customModels.length == 0) { return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-2"> Ollama Embedding Model </label> <select name="EmbeddingModelPref" disabled={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <option disabled={true} selected={true}> {!!basePath ? "--loading available models--" : "Enter Ollama URL first"} </option> </select> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Select the Ollama model for embeddings. Models will load after entering a valid Ollama URL. </p> </div> ); } return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-2"> Ollama Embedding Model </label> <select name="EmbeddingModelPref" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > {customModels.length > 0 && ( <optgroup label="Your loaded models"> {customModels.map((model) => { return ( <option key={model.id} value={model.id} selected={settings.EmbeddingModelPref === model.id} > {model.id} </option> ); })} </optgroup> )} </select> <p className="text-xs leading-[18px] font-base text-white text-opacity-60 mt-2"> Choose the Ollama model you want to use for generating embeddings. </p> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/NativeEmbeddingOptions/index.jsx
frontend/src/components/EmbeddingSelection/NativeEmbeddingOptions/index.jsx
import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import System from "@/models/system"; export default function NativeEmbeddingOptions({ settings }) { const [loading, setLoading] = useState(true); const [availableModels, setAvailableModels] = useState([]); const [selectedModel, setSelectedModel] = useState( settings?.EmbeddingModelPref ); const [selectedModelInfo, setSelectedModelInfo] = useState(); useEffect(() => { System.customModels("native-embedder") .then(({ models }) => { if (models?.length > 0) { setAvailableModels(models); const _selectedModel = models.find((model) => model.id === settings?.EmbeddingModelPref) ?? models[0]; setSelectedModel(_selectedModel.id); setSelectedModelInfo(_selectedModel); } }) .finally(() => { setLoading(false); }); }, []); useEffect(() => { if (!availableModels?.length || !selectedModel) return; setSelectedModelInfo( availableModels.find((model) => model.id === selectedModel) ); }, [selectedModel, availableModels]); return ( <div className="w-full flex flex-col gap-y-4"> <div className="w-full flex flex-col mt-1.5"> <div className="flex flex-col w-96"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" required={true} defaultValue={selectedModel} className="border-none bg-theme-settings-input-bg border-gray-500 text-theme-text-primary text-sm rounded-lg block w-60 p-2.5" onChange={(e) => setSelectedModel(e.target.value)} > {loading ? ( <option value="--loading-available-models--" disabled={true} selected={true} > --loading available models-- </option> ) : ( <optgroup label="Available embedding models"> {availableModels.map((model) => { return ( <option key={model.id} value={model.id} selected={selectedModel === model.id} > {model.name} </option> ); })} </optgroup> )} </select> </div> {selectedModelInfo && ( <div className="flex flex-col gap-y-2 mt-2"> <p className="text-theme-text-secondary text-xs font-normal block"> {selectedModelInfo?.description} </p> <p className="text-theme-text-secondary text-xs font-normal block"> Trained on: {selectedModelInfo?.lang} </p> <p className="text-theme-text-secondary text-xs font-normal block"> Download Size: {selectedModelInfo?.size} </p> <Link to={selectedModelInfo?.modelCard} target="_blank" rel="noopener noreferrer" className="text-theme-text-secondary text-xs font-normal block underline hover:text-theme-text-primary" > View model card on Hugging Face &rarr; </Link> </div> )} </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/AzureAiOptions/index.jsx
frontend/src/components/EmbeddingSelection/AzureAiOptions/index.jsx
export default function AzureAiOptions({ settings }) { return ( <div className="w-full flex flex-col gap-y-4"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Azure Service Endpoint </label> <input type="url" name="AzureOpenAiEndpoint" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="https://my-azure.openai.azure.com" defaultValue={settings?.AzureOpenAiEndpoint} required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> API Key </label> <input type="password" name="AzureOpenAiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Azure OpenAI API Key" defaultValue={settings?.AzureOpenAiKey ? "*".repeat(20) : ""} required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Embedding Deployment Name </label> <input type="text" name="AzureOpenAiEmbeddingModelPref" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Azure OpenAI embedding model deployment name" defaultValue={settings?.AzureOpenAiEmbeddingModelPref} required={true} autoComplete="off" spellCheck={false} /> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/CohereOptions/index.jsx
frontend/src/components/EmbeddingSelection/CohereOptions/index.jsx
import { useState, useEffect } from "react"; import System from "@/models/system"; export default function CohereEmbeddingOptions({ settings }) { const [inputValue, setInputValue] = useState(settings?.CohereApiKey); const [cohereApiKey, setCohereApiKey] = useState(settings?.CohereApiKey); return ( <div className="w-full flex flex-col gap-y-4"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> API Key </label> <input type="password" name="CohereApiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Cohere API Key" defaultValue={settings?.CohereApiKey ? "*".repeat(20) : ""} required={true} autoComplete="off" spellCheck={false} onChange={(e) => setInputValue(e.target.value)} onBlur={() => setCohereApiKey(inputValue)} /> </div> <CohereModelSelection settings={settings} apiKey={cohereApiKey} /> </div> </div> ); } function CohereModelSelection({ apiKey, settings }) { const [models, setModels] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function findCustomModels() { if (!apiKey) { setModels([]); setLoading(true); return; } setLoading(true); const { models } = await System.customModels( "cohere-embedder", typeof apiKey === "boolean" ? null : apiKey ); setModels(models || []); setLoading(false); } findCustomModels(); }, [apiKey]); if (loading) { return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" disabled={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <option disabled={true} selected={true}> -- loading available models -- </option> </select> </div> ); } return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > {models.map((model) => ( <option key={model.id} value={model.id} selected={settings?.EmbeddingModelPref === model.id} > {model.name} </option> ))} </select> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/LocalAiOptions/index.jsx
frontend/src/components/EmbeddingSelection/LocalAiOptions/index.jsx
import React, { useEffect, useState } from "react"; import { CaretDown, CaretUp, Info } from "@phosphor-icons/react"; import System from "@/models/system"; import PreLoader from "@/components/Preloader"; import { LOCALAI_COMMON_URLS } from "@/utils/constants"; import useProviderEndpointAutoDiscovery from "@/hooks/useProviderEndpointAutoDiscovery"; import { Tooltip } from "react-tooltip"; export default function LocalAiOptions({ settings }) { const { autoDetecting: loading, basePath, basePathValue, showAdvancedControls, setShowAdvancedControls, handleAutoDetectClick, } = useProviderEndpointAutoDiscovery({ provider: "localai", initialBasePath: settings?.EmbeddingBasePath, ENDPOINTS: LOCALAI_COMMON_URLS, }); const [apiKeyValue, setApiKeyValue] = useState(settings?.LocalAiApiKey); const [apiKey, setApiKey] = useState(settings?.LocalAiApiKey); return ( <div className="w-full flex flex-col gap-y-7"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <LocalAIModelSelection settings={settings} apiKey={apiKey} basePath={basePath.value} /> <div className="flex flex-col w-60"> <div data-tooltip-place="top" data-tooltip-id="max-embedding-chunk-length-tooltip" className="flex gap-x-1 items-center mb-3" > <Info size={16} className="text-theme-text-secondary cursor-pointer" /> <label className="text-white text-sm font-semibold block"> Max embedding chunk length </label> <Tooltip id="max-embedding-chunk-length-tooltip"> Maximum length of text chunks, in characters, for embedding. </Tooltip> </div> <input type="number" name="EmbeddingModelMaxChunkLength" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="1000" min={1} onScroll={(e) => e.target.blur()} defaultValue={settings?.EmbeddingModelMaxChunkLength} required={false} autoComplete="off" /> </div> <div className="flex flex-col w-60"> <div className="flex flex-col gap-y-1 mb-2"> <label className="text-white text-sm font-semibold flex items-center gap-x-2"> Local AI API Key{" "} <p className="!text-xs !italic !font-thin">optional</p> </label> </div> <input type="password" name="LocalAiApiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="sk-mysecretkey" defaultValue={settings?.LocalAiApiKey ? "*".repeat(20) : ""} autoComplete="off" spellCheck={false} onChange={(e) => setApiKeyValue(e.target.value)} onBlur={() => setApiKey(apiKeyValue)} /> </div> </div> <div className="flex justify-start mt-4"> <button onClick={(e) => { e.preventDefault(); setShowAdvancedControls(!showAdvancedControls); }} className="border-none text-theme-text-primary hover:text-theme-text-secondary flex items-center text-sm" > {showAdvancedControls ? "Hide" : "Show"} advanced settings {showAdvancedControls ? ( <CaretUp size={14} className="ml-1" /> ) : ( <CaretDown size={14} className="ml-1" /> )} </button> </div> <div hidden={!showAdvancedControls}> <div className="w-full flex items-center gap-4"> <div className="flex flex-col w-60"> <div className="flex justify-between items-center mb-2"> <label className="text-white text-sm font-semibold"> LocalAI Base URL </label> {loading ? ( <PreLoader size="6" /> ) : ( <> {!basePathValue.value && ( <button onClick={handleAutoDetectClick} className="bg-primary-button text-xs font-medium px-2 py-1 rounded-lg hover:bg-secondary hover:text-white shadow-[0_4px_14px_rgba(0,0,0,0.25)]" > Auto-Detect </button> )} </> )} </div> <input type="url" name="EmbeddingBasePath" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="http://localhost:8080/v1" value={basePathValue.value} required={true} autoComplete="off" spellCheck={false} onChange={basePath.onChange} onBlur={basePath.onBlur} /> </div> </div> </div> </div> ); } function LocalAIModelSelection({ settings, apiKey = null, basePath = null }) { const [customModels, setCustomModels] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function findCustomModels() { if (!basePath || !basePath.includes("/v1")) { setCustomModels([]); setLoading(false); return; } setLoading(true); const { models } = await System.customModels( "localai", typeof apiKey === "boolean" ? null : apiKey, basePath ); setCustomModels(models || []); setLoading(false); } findCustomModels(); }, [basePath, apiKey]); if (loading || customModels.length == 0) { return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-2"> Embedding Model Name </label> <select name="EmbeddingModelPref" disabled={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <option disabled={true} selected={true}> {basePath?.includes("/v1") ? "-- loading available models --" : "-- waiting for URL --"} </option> </select> </div> ); } return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-2"> Embedding Model Name </label> <select name="EmbeddingModelPref" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > {customModels.length > 0 && ( <optgroup label="Your loaded models"> {customModels.map((model) => { return ( <option key={model.id} value={model.id} selected={settings?.EmbeddingModelPref === model.id} > {model.id} </option> ); })} </optgroup> )} </select> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/LiteLLMOptions/index.jsx
frontend/src/components/EmbeddingSelection/LiteLLMOptions/index.jsx
import { useEffect, useState } from "react"; import System from "@/models/system"; import { Warning, Info } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; export default function LiteLLMOptions({ settings }) { const [basePathValue, setBasePathValue] = useState(settings?.LiteLLMBasePath); const [basePath, setBasePath] = useState(settings?.LiteLLMBasePath); const [apiKeyValue, setApiKeyValue] = useState(settings?.LiteLLMAPIKey); const [apiKey, setApiKey] = useState(settings?.LiteLLMAPIKey); return ( <div className="w-full flex flex-col gap-y-7"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Base URL </label> <input type="url" name="LiteLLMBasePath" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="http://127.0.0.1:4000" defaultValue={settings?.LiteLLMBasePath} required={true} autoComplete="off" spellCheck={false} onChange={(e) => setBasePathValue(e.target.value)} onBlur={() => setBasePath(basePathValue)} /> </div> <LiteLLMModelSelection settings={settings} basePath={basePath} apiKey={apiKey} /> <div className="flex flex-col w-60"> <div data-tooltip-place="top" data-tooltip-id="max-embedding-chunk-length-tooltip" className="flex gap-x-1 items-center mb-3" > <Info size={16} className="text-theme-text-secondary cursor-pointer" /> <label className="text-white text-sm font-semibold block"> Max embedding chunk length </label> <Tooltip id="max-embedding-chunk-length-tooltip"> Maximum length of text chunks, in characters, for embedding. </Tooltip> </div> <input type="number" name="EmbeddingModelMaxChunkLength" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="8192" min={1} onScroll={(e) => e.target.blur()} defaultValue={settings?.EmbeddingModelMaxChunkLength} required={false} autoComplete="off" /> </div> </div> <div className="w-full flex items-center gap-[36px]"> <div className="flex flex-col w-60"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-semibold flex items-center gap-x-2"> API Key <p className="!text-xs !italic !font-thin">optional</p> </label> </div> <input type="password" name="LiteLLMAPIKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="sk-mysecretkey" defaultValue={settings?.LiteLLMAPIKey ? "*".repeat(20) : ""} autoComplete="off" spellCheck={false} onChange={(e) => setApiKeyValue(e.target.value)} onBlur={() => setApiKey(apiKeyValue)} /> </div> </div> </div> ); } function LiteLLMModelSelection({ settings, basePath = null, apiKey = null }) { const [customModels, setCustomModels] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function findCustomModels() { if (!basePath) { setCustomModels([]); setLoading(false); return; } setLoading(true); const { models } = await System.customModels( "litellm", typeof apiKey === "boolean" ? null : apiKey, basePath ); setCustomModels(models || []); setLoading(false); } findCustomModels(); }, [basePath, apiKey]); if (loading || customModels.length == 0) { return ( <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Embedding Model Selection </label> <select name="EmbeddingModelPref" disabled={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <option disabled={true} selected={true}> {basePath?.includes("/v1") ? "-- loading available models --" : "-- waiting for URL --"} </option> </select> </div> ); } return ( <div className="flex flex-col w-60"> <div className="flex items-center"> <label className="text-white text-sm font-semibold block mb-3"> Embedding Model Selection </label> <EmbeddingModelTooltip /> </div> <select name="EmbeddingModelPref" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > {customModels.length > 0 && ( <optgroup label="Your loaded models"> {customModels.map((model) => { return ( <option key={model.id} value={model.id} selected={settings.EmbeddingModelPref === model.id} > {model.id} </option> ); })} </optgroup> )} </select> </div> ); } function EmbeddingModelTooltip() { return ( <div className="flex items-center justify-center -mt-3 ml-1"> <Warning size={14} className="ml-1 text-orange-500 cursor-pointer" data-tooltip-id="model-tooltip" data-tooltip-place="right" /> <Tooltip delayHide={300} id="model-tooltip" className="max-w-xs" clickable={true} > <p className="text-sm"> Be sure to select a valid embedding model. Chat models are not embedding models. See{" "} <a href="https://litellm.vercel.app/docs/embedding/supported_embedding" target="_blank" rel="noreferrer" className="underline" > this page </a>{" "} for more information. </p> </Tooltip> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/MistralAiOptions/index.jsx
frontend/src/components/EmbeddingSelection/MistralAiOptions/index.jsx
export default function MistralAiOptions({ settings }) { return ( <div className="w-full flex flex-col gap-y-4"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> API Key </label> <input type="password" name="MistralApiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Mistral AI API Key" defaultValue={settings?.MistralApiKey ? "*".repeat(20) : ""} required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" required={true} defaultValue={settings?.EmbeddingModelPref} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <optgroup label="Available embedding models"> {["mistral-embed"].map((model) => { return ( <option key={model} value={model}> {model} </option> ); })} </optgroup> </select> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/GenericOpenAiOptions/index.jsx
frontend/src/components/EmbeddingSelection/GenericOpenAiOptions/index.jsx
import React, { useState } from "react"; import { CaretDown, CaretUp, Info } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; export default function GenericOpenAiEmbeddingOptions({ settings }) { const [showAdvancedControls, setShowAdvancedControls] = useState(false); return ( <div className="w-full flex flex-col gap-y-7"> <div className="w-full flex items-center gap-[36px] mt-1.5 flex-wrap"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Base URL </label> <input type="url" name="EmbeddingBasePath" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="https://api.openai.com/v1" defaultValue={settings?.EmbeddingBasePath} required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Embedding Model </label> <input type="text" name="EmbeddingModelPref" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="text-embedding-ada-002" defaultValue={settings?.EmbeddingModelPref} required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col w-60"> <div data-tooltip-place="top" data-tooltip-id="max-embedding-chunk-length-tooltip" className="flex gap-x-1 items-center mb-3" > <Info size={16} className="text-theme-text-secondary cursor-pointer" /> <label className="text-white text-sm font-semibold block"> Max embedding chunk length </label> <Tooltip id="max-embedding-chunk-length-tooltip"> Maximum length of text chunks, in characters, for embedding. </Tooltip> </div> <input type="number" name="EmbeddingModelMaxChunkLength" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="8192" min={1} onScroll={(e) => e.target.blur()} defaultValue={settings?.EmbeddingModelMaxChunkLength} required={false} autoComplete="off" /> </div> </div> <div className="w-full flex items-center gap-[36px]"> <div className="flex flex-col w-60"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-semibold flex items-center gap-x-2"> API Key <p className="!text-xs !italic !font-thin">optional</p> </label> </div> <input type="password" name="GenericOpenAiEmbeddingApiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="sk-mysecretkey" defaultValue={ settings?.GenericOpenAiEmbeddingApiKey ? "*".repeat(20) : "" } autoComplete="off" spellCheck={false} /> </div> </div> <div className="flex justify-start mt-4"> <button onClick={(e) => { e.preventDefault(); setShowAdvancedControls(!showAdvancedControls); }} className="border-none text-theme-text-primary hover:text-theme-text-secondary flex items-center text-sm" > {showAdvancedControls ? "Hide" : "Show"} advanced settings {showAdvancedControls ? ( <CaretUp size={14} className="ml-1" /> ) : ( <CaretDown size={14} className="ml-1" /> )} </button> </div> <div hidden={!showAdvancedControls}> <div className="w-full flex items-start gap-4"> <div className="flex flex-col w-60"> <div className="flex flex-col gap-y-1 mb-4"> <label className="text-white text-sm font-semibold flex items-center gap-x-2"> Max concurrent Chunks <p className="!text-xs !italic !font-thin">optional</p> </label> </div> <input type="number" name="GenericOpenAiEmbeddingMaxConcurrentChunks" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="500" min={1} onScroll={(e) => e.target.blur()} defaultValue={settings?.GenericOpenAiEmbeddingMaxConcurrentChunks} required={false} autoComplete="off" spellCheck={false} /> </div> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/EmbedderItem/index.jsx
frontend/src/components/EmbeddingSelection/EmbedderItem/index.jsx
export default function EmbedderItem({ name, value, image, description, checked, onClick, }) { return ( <div onClick={() => onClick(value)} className={`w-full p-2 rounded-md hover:cursor-pointer hover:bg-theme-bg-secondary ${ checked ? "bg-theme-bg-secondary" : "" }`} > <input type="checkbox" value={value} className="peer hidden" checked={checked} readOnly={true} formNoValidate={true} /> <div className="flex gap-x-4 items-center"> <img src={image} alt={`${name} logo`} className="w-10 h-10 rounded-md" /> <div className="flex flex-col"> <div className="text-sm font-semibold text-white">{name}</div> <div className="mt-1 text-xs text-description">{description}</div> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/OpenAiOptions/index.jsx
frontend/src/components/EmbeddingSelection/OpenAiOptions/index.jsx
export default function OpenAiOptions({ settings }) { return ( <div className="w-full flex flex-col gap-y-4"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> API Key </label> <input type="password" name="OpenAiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="OpenAI API Key" defaultValue={settings?.OpenAiKey ? "*".repeat(20) : ""} required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <optgroup label="Available embedding models"> {[ "text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large", ].map((model) => { return ( <option key={model} value={model} selected={settings?.EmbeddingModelPref === model} > {model} </option> ); })} </optgroup> </select> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/VoyageAiOptions/index.jsx
frontend/src/components/EmbeddingSelection/VoyageAiOptions/index.jsx
export default function VoyageAiOptions({ settings }) { return ( <div className="w-full flex flex-col gap-y-4"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> API Key </label> <input type="password" name="VoyageAiApiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Voyage AI API Key" defaultValue={settings?.VoyageAiApiKey ? "*".repeat(20) : ""} required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" required={true} defaultValue={settings?.EmbeddingModelPref} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <optgroup label="Available embedding models"> {[ "voyage-large-2-instruct", "voyage-finance-2", "voyage-multilingual-2", "voyage-law-2", "voyage-code-2", "voyage-large-2", "voyage-2", "voyage-3", "voyage-3-lite", "voyage-3-large", "voyage-code-3", ].map((model) => { return ( <option key={model} value={model}> {model} </option> ); })} </optgroup> </select> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EmbeddingSelection/GeminiOptions/index.jsx
frontend/src/components/EmbeddingSelection/GeminiOptions/index.jsx
const DEFAULT_MODELS = [ { id: "embedding-001", name: "Embedding 001", }, { id: "text-embedding-004", name: "Text Embedding 004", }, { id: "gemini-embedding-exp-03-07", name: "Gemini Embedding Exp 03 07", }, ]; export default function GeminiOptions({ settings }) { return ( <div className="w-full flex flex-col gap-y-4"> <div className="w-full flex items-center gap-[36px] mt-1.5"> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> API Key </label> <input type="password" name="GeminiEmbeddingApiKey" className="border-none bg-theme-settings-input-bg text-white placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block w-full p-2.5" placeholder="Gemini API Key" defaultValue={settings?.GeminiEmbeddingApiKey ? "*".repeat(20) : ""} required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col w-60"> <label className="text-white text-sm font-semibold block mb-3"> Model Preference </label> <select name="EmbeddingModelPref" required={true} className="border-none bg-theme-settings-input-bg border-gray-500 text-white text-sm rounded-lg block w-full p-2.5" > <optgroup label="Available embedding models"> {DEFAULT_MODELS.map((model) => { return ( <option key={model.id} value={model.id} selected={settings?.EmbeddingModelPref === model.id} > {model.name} </option> ); })} </optgroup> </select> </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/src/components/EditingChatBubble/index.jsx
frontend/src/components/EditingChatBubble/index.jsx
import React, { useState } from "react"; import { X } from "@phosphor-icons/react"; import { useTranslation } from "react-i18next"; import renderMarkdown from "@/utils/chat/markdown"; import DOMPurify from "@/utils/chat/purify"; export default function EditingChatBubble({ message, index, type, handleMessageChange, removeMessage, }) { const [isEditing, setIsEditing] = useState(false); const [tempMessage, setTempMessage] = useState(message[type]); const isUser = type === "user"; const { t } = useTranslation(); return ( <div> <p className={`text-xs text-white light:text-black/80 ${isUser ? "text-right" : ""}`} > {isUser ? t("common.user") : t("customization.items.welcome-messages.assistant")} </p> <div className={`relative flex w-full mt-2 items-start ${ isUser ? "justify-end" : "justify-start" }`} > <button className={`transition-all duration-300 absolute z-10 text-white rounded-full hover:bg-neutral-700 light:hover:invert hover:border-white border-transparent border shadow-lg ${ isUser ? "right-0 mr-2" : "ml-2" }`} style={{ top: "6px", [isUser ? "right" : "left"]: "290px" }} onClick={() => removeMessage(index)} > <X className="m-0.5" size={20} /> </button> <div className={`p-2 max-w-full md:w-[290px] text-black rounded-[8px] ${ isUser ? "bg-[#41444C] text-white" : "bg-[#2E3036] text-white" } }`} onDoubleClick={() => setIsEditing(true)} > {isEditing ? ( <input value={tempMessage} onChange={(e) => setTempMessage(e.target.value)} onBlur={() => { handleMessageChange(index, type, tempMessage); setIsEditing(false); }} autoFocus className={`w-full light:text-white ${ isUser ? "bg-[#41444C] text-white" : "bg-[#2E3036] text-white" }`} /> ) : ( tempMessage && ( <div className="markdown font-[500] md:font-semibold text-sm md:text-base break-words light:invert" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(renderMarkdown(tempMessage)), }} /> ) )} </div> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false