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/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js
collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js
const ignore = require("ignore"); /** * @typedef {Object} RepoLoaderArgs * @property {string} repo - The GitLab repository URL. * @property {string} [branch] - The branch to load from (optional). * @property {string} [accessToken] - GitLab access token for authentication (optional). * @property {string[]} [ignorePaths] - Array of paths to ignore when loading (optional). * @property {boolean} [fetchIssues] - Should issues be fetched (optional). * @property {boolean} [fetchWikis] - Should wiki be fetched (optional). */ /** * @typedef {Object} FileTreeObject * @property {string} id - The file object ID. * @property {string} name - name of file. * @property {('blob'|'tree')} type - type of file object. * @property {string} path - path + name of file. * @property {string} mode - Linux permission code. */ /** * @class * @classdesc Loads and manages GitLab repository content. */ class GitLabRepoLoader { /** * Creates an instance of RepoLoader. * @param {RepoLoaderArgs} [args] - The configuration options. * @returns {GitLabRepoLoader} */ constructor(args = {}) { this.ready = false; this.repo = args?.repo; this.branch = args?.branch; this.accessToken = args?.accessToken || null; this.ignorePaths = args?.ignorePaths || []; this.ignoreFilter = ignore().add(this.ignorePaths); this.withIssues = args?.fetchIssues || false; this.withWikis = args?.fetchWikis || false; this.projectId = null; this.apiBase = "https://gitlab.com"; this.author = null; this.project = null; this.branches = []; } #validGitlabUrl() { const validPatterns = [ /https:\/\/gitlab\.com\/(?<author>[^\/]+)\/(?<project>.*)/, // This should even match the regular hosted URL, but we may want to know // if this was a hosted GitLab (above) or a self-hosted (below) instance // since the API interface could be different. /(http|https):\/\/[^\/]+\/(?<author>[^\/]+)\/(?<project>.*)/, ]; const match = validPatterns .find((pattern) => this.repo.match(pattern)?.groups) ?.exec(this.repo); if (!match?.groups) return false; const { author, project } = match.groups; this.projectId = encodeURIComponent(`${author}/${project}`); this.apiBase = new URL(this.repo).origin; this.author = author; this.project = project; return true; } async #validBranch() { await this.getRepoBranches(); if (!!this.branch && this.branches.includes(this.branch)) return; console.log( "[Gitlab Loader]: Branch not set! Auto-assigning to a default branch." ); this.branch = this.branches.includes("main") ? "main" : "master"; console.log(`[Gitlab Loader]: Branch auto-assigned to ${this.branch}.`); return; } async #validateAccessToken() { if (!this.accessToken) return; try { await fetch(`${this.apiBase}/api/v4/user`, { method: "GET", headers: this.accessToken ? { "PRIVATE-TOKEN": this.accessToken } : {}, }).then((res) => res.ok); } catch (e) { console.error( "Invalid Gitlab Access Token provided! Access token will not be used", e.message ); this.accessToken = null; } } /** * Initializes the RepoLoader instance. * @returns {Promise<RepoLoader>} The initialized RepoLoader instance. */ async init() { if (!this.#validGitlabUrl()) return; await this.#validBranch(); await this.#validateAccessToken(); this.ready = true; return this; } /** * Recursively loads the repository content. * @returns {Promise<Array<Object>>} An array of loaded documents. * @throws {Error} If the RepoLoader is not in a ready state. */ async recursiveLoader() { if (!this.ready) throw new Error("[Gitlab Loader]: not in ready state!"); if (this.accessToken) console.log( `[Gitlab Loader]: Access token set! Recursive loading enabled for ${this.repo}!` ); const docs = []; console.log(`[Gitlab Loader]: Fetching files.`); const files = await this.fetchFilesRecursive(); console.log(`[Gitlab Loader]: Fetched ${files.length} files.`); for (const file of files) { if (this.ignoreFilter.ignores(file.path)) continue; docs.push({ pageContent: file.content, metadata: { source: file.path, url: `${this.repo}/-/blob/${this.branch}/${file.path}`, }, }); } if (this.withIssues) { console.log(`[Gitlab Loader]: Fetching issues.`); const issues = await this.fetchIssues(); console.log( `[Gitlab Loader]: Fetched ${issues.length} issues with discussions.` ); docs.push( ...issues.map((issue) => ({ issue, metadata: { source: `issue-${this.repo}-${issue.iid}`, url: issue.web_url, }, })) ); } if (this.withWikis) { console.log(`[Gitlab Loader]: Fetching wiki.`); const wiki = await this.fetchWiki(); console.log(`[Gitlab Loader]: Fetched ${wiki.length} wiki pages.`); docs.push( ...wiki.map((wiki) => ({ wiki, metadata: { source: `wiki-${this.repo}-${wiki.slug}`, url: `${this.repo}/-/wikis/${wiki.slug}`, }, })) ); } return docs; } #branchPrefSort(branches = []) { const preferredSort = ["main", "master"]; return branches.reduce((acc, branch) => { if (preferredSort.includes(branch)) return [branch, ...acc]; return [...acc, branch]; }, []); } /** * Retrieves all branches for the repository. * @returns {Promise<string[]>} An array of branch names. */ async getRepoBranches() { if (!this.#validGitlabUrl() || !this.projectId) return []; await this.#validateAccessToken(); this.branches = []; const branchesRequestData = { endpoint: `/api/v4/projects/${this.projectId}/repository/branches`, }; let branchesPage = []; while ((branchesPage = await this.fetchNextPage(branchesRequestData))) { if (!Array.isArray(branchesPage) || !branchesPage?.length) break; this.branches.push(...branchesPage.map((branch) => branch.name)); } return this.#branchPrefSort(this.branches); } /** * Returns list of all file objects from tree API for GitLab * @returns {Promise<FileTreeObject[]>} */ async fetchFilesRecursive() { const files = []; const filesRequestData = { endpoint: `/api/v4/projects/${this.projectId}/repository/tree`, queryParams: { ref: this.branch, recursive: true, }, }; let filesPage = null; let pagePromises = []; while ((filesPage = await this.fetchNextPage(filesRequestData))) { if (!Array.isArray(filesPage) || !filesPage?.length) break; // Fetch all the files that are not ignored in parallel. pagePromises = filesPage .filter((file) => { if (file.type !== "blob") return false; return !this.ignoreFilter.ignores(file.path); }) .map(async (file) => { const content = await this.fetchSingleFileContents(file.path); if (!content) return null; return { path: file.path, content, }; }); const pageFiles = await Promise.all(pagePromises); files.push(...pageFiles.filter((item) => item !== null)); console.log(`Fetched ${files.length} files.`); } console.log(`Total files fetched: ${files.length}`); return files; } /** * Fetches all issues from the repository. * @returns {Promise<Issue[]>} An array of issue objects. */ async fetchIssues() { const issues = []; const issuesRequestData = { endpoint: `/api/v4/projects/${this.projectId}/issues`, }; let issuesPage = null; let pagePromises = []; while ((issuesPage = await this.fetchNextPage(issuesRequestData))) { if (!Array.isArray(issuesPage) || !issuesPage?.length) break; // Fetch all the issues in parallel. pagePromises = issuesPage.map(async (issue) => { const discussionsRequestData = { endpoint: `/api/v4/projects/${this.projectId}/issues/${issue.iid}/discussions`, }; let discussionPage = null; const discussions = []; while ( (discussionPage = await this.fetchNextPage(discussionsRequestData)) ) { if (!Array.isArray(discussionPage) || !discussionPage?.length) break; discussions.push( ...discussionPage.map(({ notes }) => notes.map( ({ body, author, created_at }) => `${author.username} at ${created_at}: ${body}` ) ) ); } const result = { ...issue, discussions, }; return result; }); const pageIssues = await Promise.all(pagePromises); issues.push(...pageIssues); console.log(`Fetched ${issues.length} issues.`); } console.log(`Total issues fetched: ${issues.length}`); return issues; } /** * Fetches all wiki pages from the repository. * @returns {Promise<WikiPage[]>} An array of wiki page objects. */ async fetchWiki() { const wikiRequestData = { endpoint: `/api/v4/projects/${this.projectId}/wikis`, queryParams: { with_content: "1", }, }; const wikiPages = await this.fetchNextPage(wikiRequestData); if (!Array.isArray(wikiPages)) return []; console.log(`Total wiki pages fetched: ${wikiPages.length}`); return wikiPages; } /** * Fetches the content of a single file from the repository. * @param {string} sourceFilePath - The path to the file in the repository. * @returns {Promise<string|null>} The content of the file, or null if fetching fails. */ async fetchSingleFileContents(sourceFilePath) { try { const data = await fetch( `${this.apiBase}/api/v4/projects/${ this.projectId }/repository/files/${encodeURIComponent(sourceFilePath)}/raw?ref=${ this.branch }`, { method: "GET", headers: this.accessToken ? { "PRIVATE-TOKEN": this.accessToken } : {}, } ).then((res) => { if (res.ok) return res.text(); throw new Error(`Failed to fetch single file ${sourceFilePath}`); }); return data; } catch (e) { console.error(`RepoLoader.fetchSingleFileContents`, e); return null; } } /** * Fetches the next page of data from the API. * @param {Object} requestData - The request data. * @returns {Promise<Array<Object>|null>} The next page of data, or null if no more pages. */ async fetchNextPage(requestData) { try { if (requestData.page === -1) return null; if (!requestData.page) requestData.page = 1; const { endpoint, perPage = 100, queryParams = {} } = requestData; const params = new URLSearchParams({ ...queryParams, per_page: perPage, page: requestData.page, }); const url = `${this.apiBase}${endpoint}?${params.toString()}`; const response = await fetch(url, { method: "GET", headers: this.accessToken ? { "PRIVATE-TOKEN": this.accessToken } : {}, }); // Rate limits get hit very often if no PAT is provided if (response.status === 401) { console.warn(`Rate limit hit for ${endpoint}. Skipping.`); return null; } const totalPages = Number(response.headers.get("x-total-pages")); const data = await response.json(); if (!Array.isArray(data)) { console.warn(`Unexpected response format for ${endpoint}:`, data); return []; } console.log( `Gitlab RepoLoader: fetched ${endpoint} page ${requestData.page}/${totalPages} with ${data.length} records.` ); if (totalPages === requestData.page) { requestData.page = -1; } else { requestData.page = Number(response.headers.get("x-next-page")); } return data; } catch (e) { console.error(`RepoLoader.fetchNextPage`, e); return null; } } } module.exports = GitLabRepoLoader;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/tokenizer/index.js
collector/utils/tokenizer/index.js
const { getEncoding } = require("js-tiktoken"); class TikTokenTokenizer { static MAX_KB_ESTIMATE = 10; static DIVISOR = 8; constructor() { if (TikTokenTokenizer.instance) { this.log( "Singleton instance already exists. Returning existing instance." ); return TikTokenTokenizer.instance; } this.encoder = getEncoding("cl100k_base"); TikTokenTokenizer.instance = this; this.log("Initialized new TikTokenTokenizer instance."); } log(text, ...args) { console.log(`\x1b[35m[TikTokenTokenizer]\x1b[0m ${text}`, ...args); } /** * Check if the input is too long to encode * this is more of a rough estimate and a sanity check to prevent * CPU issues from encoding too large of strings * Assumes 1 character = 2 bytes in JS * @param {string} input * @returns {boolean} */ #isTooLong(input) { const bytesEstimate = input.length * 2; const kbEstimate = Math.floor(bytesEstimate / 1024); return kbEstimate >= TikTokenTokenizer.MAX_KB_ESTIMATE; } /** * Encode a string into tokens for rough token count estimation. * @param {string} input * @returns {number} */ tokenizeString(input = "") { try { if (this.#isTooLong(input)) { this.log("Input will take too long to encode - estimating"); return Math.ceil(input.length / TikTokenTokenizer.DIVISOR); } return this.encoder.encode(input).length; } catch (e) { this.log("Could not tokenize string! Estimating...", e.message, e.stack); return Math.ceil(input?.length / TikTokenTokenizer.DIVISOR) || 0; } } } const tokenizer = new TikTokenTokenizer(); module.exports = { /** * Encode a string into tokens for rough token count estimation. * @param {string} input * @returns {number} */ tokenizeString: (input) => tokenizer.tokenizeString(input), };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/comKey/index.js
collector/utils/comKey/index.js
const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); const keyPath = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../../server/storage/comkey`) : path.resolve( process.env.STORAGE_DIR ?? path.resolve(__dirname, `../../../server/storage`), `comkey` ); class CommunicationKey { #pubKeyName = "ipc-pub.pem"; #storageLoc = keyPath; constructor() {} log(text, ...args) { console.log(`\x1b[36m[CommunicationKeyVerify]\x1b[0m ${text}`, ...args); } #readPublicKey() { return fs.readFileSync(path.resolve(this.#storageLoc, this.#pubKeyName)); } // Given a signed payload from private key from /app/server/ this signature should // decode to match the textData provided. This class does verification only in collector. // Note: The textData is typically the JSON stringified body sent to the document processor API. verify(signature = "", textData = "") { try { let data = textData; if (typeof textData !== "string") data = JSON.stringify(data); return crypto.verify( "RSA-SHA256", Buffer.from(data), this.#readPublicKey(), Buffer.from(signature, "hex") ); } catch {} return false; } // Use the rolling public-key to decrypt arbitrary data that was encrypted via the private key on the server side CommunicationKey class // that we know was done with the same key-pair and the given input is in base64 format already. // Returns plaintext string of the data that was encrypted. decrypt(base64String = "") { return crypto .publicDecrypt(this.#readPublicKey(), Buffer.from(base64String, "base64")) .toString(); } } module.exports = { CommunicationKey };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/url/index.js
collector/utils/url/index.js
const RuntimeSettings = require("../runtimeSettings"); /** ATTN: SECURITY RESEARCHERS * To Security researchers about to submit an SSRF report CVE - please don't. * We are aware that the code below is does not defend against any of the thousands of ways * you can map a hostname to another IP via tunneling, hosts editing, etc. The code below does not have intention of blocking this * and is simply to prevent the user from accidentally putting in non-valid websites, which is all this protects * since _all urls must be submitted by the user anyway_ and cannot be done with authentication and manager or admin roles. * If an attacker has those roles then the system is already vulnerable and this is not a primary concern. * * We have gotten this report may times, marked them as duplicate or information and continue to get them. We communicate * already that deployment (and security) of an instance is on the deployer and system admin deploying it. This would include * isolation, firewalls, and the general security of the instance. */ const VALID_PROTOCOLS = ["https:", "http:"]; const INVALID_OCTETS = [192, 172, 10, 127]; const runtimeSettings = new RuntimeSettings(); /** * If an ip address is passed in the user is attempting to collector some internal service running on internal/private IP. * This is not a security feature and simply just prevents the user from accidentally entering invalid IP addresses. * Can be bypassed via COLLECTOR_ALLOW_ANY_IP environment variable. * @param {URL} param0 * @param {URL['hostname']} param0.hostname * @returns {boolean} */ function isInvalidIp({ hostname }) { if (runtimeSettings.get("allowAnyIp")) { if (!runtimeSettings.get("seenAnyIpWarning")) { console.log( "\x1b[33mURL IP local address restrictions have been disabled by administrator!\x1b[0m" ); runtimeSettings.set("seenAnyIpWarning", true); } return false; } const IPRegex = new RegExp( /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gi ); // Not an IP address at all - passthrough if (!IPRegex.test(hostname)) return false; const [octetOne, ..._rest] = hostname.split("."); // If fails to validate to number - abort and return as invalid. if (isNaN(Number(octetOne))) return true; // Allow localhost loopback and 0.0.0.0 for scraping convenience // for locally hosted services or websites if (["127.0.0.1", "0.0.0.0"].includes(hostname)) return false; return INVALID_OCTETS.includes(Number(octetOne)); } /** * Validates a URL strictly * - Checks the URL forms a valid URL * - Checks the URL is at least HTTP(S) * - Checks the URL is not an internal IP - can be bypassed via COLLECTOR_ALLOW_ANY_IP * @param {string} url * @returns {boolean} */ function validURL(url) { try { const destination = new URL(url); if (!VALID_PROTOCOLS.includes(destination.protocol)) return false; if (isInvalidIp(destination)) return false; return true; } catch {} return false; } /** * Modifies a URL to be valid: * - Checks the URL is at least HTTP(S) so that protocol exists * - Checks the URL forms a valid URL * @param {string} url * @returns {string} */ function validateURL(url) { try { let destination = url.trim(); // If the URL has a protocol, just pass through // If the URL doesn't have a protocol, assume https:// if (destination.includes("://")) destination = new URL(destination).toString(); else destination = new URL(`https://${destination}`).toString(); // If the URL ends with a slash, remove it return destination.endsWith("/") ? destination.slice(0, -1) : destination; } catch { if (typeof url !== "string") return ""; return url.trim(); } } /** * Validate if a link is a valid YouTube video URL * - Checks youtu.be, youtube.com, m.youtube.com, music.youtube.com * - Embed video URLs * - Short URLs * - Live URLs * - Regular watch URLs * - Optional query parameters (including ?v parameter) * * Can be used to extract the video ID from a YouTube video URL via the returnVideoId parameter. * @param {string} link - The link to validate * @param {boolean} returnVideoId - Whether to return the video ID if the link is a valid YouTube video URL * @returns {boolean|string} - Whether the link is a valid YouTube video URL or the video ID if returnVideoId is true */ function validYoutubeVideoUrl(link, returnVideoId = false) { try { if (!link || typeof link !== "string") return false; let urlToValidate = link; if (!link.startsWith("http://") && !link.startsWith("https://")) { urlToValidate = "https://" + link; urlToValidate = new URL(urlToValidate).toString(); } const regex = /^(?:https?:\/\/)?(?:www\.|m\.|music\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?(?:.*&)?v=|(?:live\/)?|shorts\/))([\w-]{11})(?:\S+)?$/; const match = urlToValidate.match(regex); if (returnVideoId) return match?.[1] ?? null; return !!match?.[1]; } catch (error) { console.error("Error validating YouTube video URL", error); return returnVideoId ? null : false; } } module.exports = { validURL, validateURL, validYoutubeVideoUrl, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/files/mime.js
collector/utils/files/mime.js
const MimeLib = require("mime"); class MimeDetector { nonTextTypes = ["multipart", "model", "audio", "video", "font"]; badMimes = [ "application/octet-stream", "application/zip", "application/pkcs8", "application/vnd.microsoft.portable-executable", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // XLSX are binaries and need to be handled explicitly. "application/x-msdownload", ]; constructor() { this.lib = MimeLib; this.setOverrides(); } setOverrides() { // the .ts extension maps to video/mp2t because of https://en.wikipedia.org/wiki/MPEG_transport_stream // which has had this extension far before TS was invented. So need to force re-map this MIME map. this.lib.define( { "text/plain": [ "ts", "tsx", "py", "opts", "lock", "jsonl", "qml", "sh", "c", "cs", "h", "js", "lua", "pas", "r", "go", "ino", "hpp", "linq", "cs", ], }, true ); } /** * Returns the MIME type of the file. If the file has no extension found, it will be processed as a text file. * @param {string} filepath * @returns {string} */ getType(filepath) { const parsedMime = this.lib.getType(filepath); if (!!parsedMime) return parsedMime; return null; } } module.exports = { MimeDetector, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/files/index.js
collector/utils/files/index.js
const fs = require("fs"); const path = require("path"); const { MimeDetector } = require("./mime"); /** * The folder where documents are stored to be stored when * processed by the collector. */ const documentsFolder = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../../server/storage/documents`) : path.resolve(process.env.STORAGE_DIR, `documents`); /** * The folder where direct uploads are stored to be stored when * processed by the collector. These are files that were DnD'd into UI * and are not to be embedded or selectable from the file picker. */ const directUploadsFolder = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../../server/storage/direct-uploads`) : path.resolve(process.env.STORAGE_DIR, `direct-uploads`); /** * Checks if a file is text by checking the mime type and then falling back to buffer inspection. * This way we can capture all the cases where the mime type is not known but still parseable as text * without having to constantly add new mime type overrides. * @param {string} filepath - The path to the file. * @returns {boolean} - Returns true if the file is text, false otherwise. */ function isTextType(filepath) { if (!fs.existsSync(filepath)) return false; const result = isKnownTextMime(filepath); if (result.valid) return true; // Known text type - return true. if (result.reason !== "generic") return false; // If any other reason than generic - return false. return parseableAsText(filepath); // Fallback to parsing as text via buffer inspection. } /** * Checks if a file is known to be text by checking the mime type. * @param {string} filepath - The path to the file. * @returns {boolean} - Returns true if the file is known to be text, false otherwise. */ function isKnownTextMime(filepath) { try { const mimeLib = new MimeDetector(); const mime = mimeLib.getType(filepath); if (mimeLib.badMimes.includes(mime)) return { valid: false, reason: "bad_mime" }; const type = mime.split("/")[0]; if (mimeLib.nonTextTypes.includes(type)) return { valid: false, reason: "non_text_mime" }; return { valid: true, reason: "valid_mime" }; } catch (e) { return { valid: false, reason: "generic" }; } } /** * Checks if a file is parseable as text by forcing it to be read as text in utf8 encoding. * If the file looks too much like a binary file, it will return false. * @param {string} filepath - The path to the file. * @returns {boolean} - Returns true if the file is parseable as text, false otherwise. */ function parseableAsText(filepath) { try { const fd = fs.openSync(filepath, "r"); const buffer = Buffer.alloc(1024); // Read first 1KB of the file synchronously const bytesRead = fs.readSync(fd, buffer, 0, 1024, 0); fs.closeSync(fd); const content = buffer.subarray(0, bytesRead).toString("utf8"); const nullCount = (content.match(/\0/g) || []).length; const controlCount = (content.match(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g) || []) .length; const threshold = bytesRead * 0.1; return nullCount + controlCount < threshold; } catch { return false; } } function trashFile(filepath) { if (!fs.existsSync(filepath)) return; try { const isDir = fs.lstatSync(filepath).isDirectory(); if (isDir) return; } catch { return; } fs.rmSync(filepath); return; } function createdDate(filepath) { try { const { birthtimeMs, birthtime } = fs.statSync(filepath); if (birthtimeMs === 0) throw new Error("Invalid stat for file!"); return birthtime.toLocaleString(); } catch { return "unknown"; } } /** * Writes a document to the server documents folder. * @param {Object} params - The parameters for the function. * @param {Object} params.data - The data to write to the file. Must look like a document object. * @param {string} params.filename - The name of the file to write to. * @param {string|null} params.destinationOverride - A forced destination to write to - will be honored if provided. * @param {Object} params.options - The options for the function. * @param {boolean} params.options.parseOnly - If true, the file will be written to the direct uploads folder instead of the documents folder. Will be ignored if destinationOverride is provided. * @returns {Object} - The data with the location added. */ function writeToServerDocuments({ data = {}, filename, destinationOverride = null, options = {}, }) { if (!filename) throw new Error("Filename is required!"); let destination = null; if (destinationOverride) destination = path.resolve(destinationOverride); else if (options.parseOnly) destination = path.resolve(directUploadsFolder); else destination = path.resolve(documentsFolder, "custom-documents"); if (!fs.existsSync(destination)) fs.mkdirSync(destination, { recursive: true }); const destinationFilePath = normalizePath( path.resolve(destination, filename) + ".json" ); fs.writeFileSync(destinationFilePath, JSON.stringify(data, null, 4), { encoding: "utf-8", }); return { ...data, // relative location string that can be passed into the /update-embeddings api // that will work since we know the location exists and since we only allow // 1-level deep folders this will always work. This still works for integrations like GitHub and YouTube. location: destinationFilePath.split("/").slice(-2).join("/"), isDirectUpload: options.parseOnly || false, }; } // When required we can wipe the entire collector hotdir and tmp storage in case // there were some large file failures that we unable to be removed a reboot will // force remove them. async function wipeCollectorStorage() { const cleanHotDir = new Promise((resolve) => { const directory = path.resolve(__dirname, "../../hotdir"); fs.readdir(directory, (err, files) => { if (err) resolve(); for (const file of files) { if (file === "__HOTDIR__.md") continue; try { fs.rmSync(path.join(directory, file)); } catch {} } resolve(); }); }); const cleanTmpDir = new Promise((resolve) => { const directory = path.resolve(__dirname, "../../storage/tmp"); fs.readdir(directory, (err, files) => { if (err) resolve(); for (const file of files) { if (file === ".placeholder") continue; try { fs.rmSync(path.join(directory, file)); } catch {} } resolve(); }); }); await Promise.all([cleanHotDir, cleanTmpDir]); console.log(`Collector hot directory and tmp storage wiped!`); return; } /** * Checks if a given path is within another path. * @param {string} outer - The outer path (should be resolved). * @param {string} inner - The inner path (should be resolved). * @returns {boolean} - Returns true if the inner path is within the outer path, false otherwise. */ function isWithin(outer, inner) { if (outer === inner) return false; const rel = path.relative(outer, inner); return !rel.startsWith("../") && rel !== ".."; } function normalizePath(filepath = "") { const result = path .normalize(filepath.trim()) .replace(/^(\.\.(\/|\\|$))+/, "") .trim(); if (["..", ".", "/"].includes(result)) throw new Error("Invalid path."); return result; } function sanitizeFileName(fileName) { if (!fileName) return fileName; return fileName.replace(/[<>:"\/\\|?*]/g, ""); } module.exports = { trashFile, isTextType, createdDate, writeToServerDocuments, wipeCollectorStorage, normalizePath, isWithin, sanitizeFileName, documentsFolder, directUploadsFolder, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/downloadURIToFile/index.js
collector/utils/downloadURIToFile/index.js
const { WATCH_DIRECTORY } = require("../constants"); const fs = require("fs"); const path = require("path"); const { pipeline } = require("stream/promises"); const { validURL } = require("../url"); const { default: slugify } = require("slugify"); /** * Download a file to the hotdir * @param {string} url - The URL of the file to download * @param {number} maxTimeout - The maximum timeout in milliseconds * @returns {Promise<{success: boolean, fileLocation: string|null, reason: string|null}>} - The path to the downloaded file */ async function downloadURIToFile(url, maxTimeout = 10_000) { if (!url || typeof url !== "string" || !validURL(url)) return { success: false, reason: "Not a valid URL.", fileLocation: null }; try { const abortController = new AbortController(); const timeout = setTimeout(() => { abortController.abort(); console.error( `Timeout ${maxTimeout}ms reached while downloading file for URL:`, url.toString() ); }, maxTimeout); const res = await fetch(url, { signal: abortController.signal }) .then((res) => { if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`); return res; }) .finally(() => clearTimeout(timeout)); const urlObj = new URL(url); const filename = `${urlObj.hostname}-${slugify( urlObj.pathname.replace(/\//g, "-"), { lower: true } )}`; const localFilePath = path.join(WATCH_DIRECTORY, filename); const writeStream = fs.createWriteStream(localFilePath); await pipeline(res.body, writeStream); console.log(`[SUCCESS]: File ${localFilePath} downloaded to hotdir.`); return { success: true, fileLocation: localFilePath, reason: null }; } catch (error) { console.error(`Error writing to hotdir: ${error} for URL: ${url}`); return { success: false, reason: error.message, fileLocation: null }; } } module.exports = { downloadURIToFile, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/WhisperProviders/OpenAiWhisper.js
collector/utils/WhisperProviders/OpenAiWhisper.js
const fs = require("fs"); class OpenAiWhisper { constructor({ options }) { const { OpenAI: OpenAIApi } = require("openai"); if (!options.openAiKey) throw new Error("No OpenAI API key was set."); this.openai = new OpenAIApi({ apiKey: options.openAiKey, }); this.model = "whisper-1"; this.temperature = 0; this.#log("Initialized."); } #log(text, ...args) { console.log(`\x1b[32m[OpenAiWhisper]\x1b[0m ${text}`, ...args); } async processFile(fullFilePath) { return await this.openai.audio.transcriptions .create({ file: fs.createReadStream(fullFilePath), model: this.model, temperature: this.temperature, }) .then((response) => { if (!response) { return { content: "", error: "No content was able to be transcribed.", }; } return { content: response.text, error: null }; }) .catch((error) => { this.#log( `Could not get any response from openai whisper`, error.message ); return { content: "", error: error.message }; }); } } module.exports = { OpenAiWhisper, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/WhisperProviders/localWhisper.js
collector/utils/WhisperProviders/localWhisper.js
const fs = require("fs"); const path = require("path"); const { v4 } = require("uuid"); const defaultWhisper = "Xenova/whisper-small"; // Model Card: https://huggingface.co/Xenova/whisper-small const fileSize = { "Xenova/whisper-small": "250mb", "Xenova/whisper-large": "1.56GB", }; class LocalWhisper { constructor({ options }) { this.model = options?.WhisperModelPref ?? defaultWhisper; this.fileSize = fileSize[this.model]; this.cacheDir = path.resolve( process.env.STORAGE_DIR ? path.resolve(process.env.STORAGE_DIR, `models`) : path.resolve(__dirname, `../../../server/storage/models`) ); this.modelPath = path.resolve(this.cacheDir, ...this.model.split("/")); // Make directory when it does not exist in existing installations if (!fs.existsSync(this.cacheDir)) fs.mkdirSync(this.cacheDir, { recursive: true }); this.#log("Initialized."); } #log(text, ...args) { console.log(`\x1b[32m[LocalWhisper]\x1b[0m ${text}`, ...args); } #validateAudioFile(wavFile) { const sampleRate = wavFile.fmt.sampleRate; const duration = wavFile.data.samples / sampleRate; // Most speech recognition systems expect minimum 8kHz // But we'll set it lower to be safe if (sampleRate < 4000) { // 4kHz minimum throw new Error( "Audio file sample rate is too low for accurate transcription. Minimum required is 4kHz." ); } // Typical audio file duration limits const MAX_DURATION_SECONDS = 4 * 60 * 60; // 4 hours if (duration > MAX_DURATION_SECONDS) { throw new Error("Audio file duration exceeds maximum limit of 4 hours."); } // Check final sample count after upsampling to prevent memory issues const targetSampleRate = 16000; const upsampledSamples = duration * targetSampleRate; const MAX_SAMPLES = 230_400_000; // ~4 hours at 16kHz if (upsampledSamples > MAX_SAMPLES) { throw new Error("Audio file exceeds maximum allowed length."); } return true; } async #convertToWavAudioData(sourcePath) { try { let buffer; const wavefile = require("wavefile"); const { FFMPEGWrapper } = require("./ffmpeg"); const ffmpeg = new FFMPEGWrapper(); const outFolder = path.resolve(__dirname, `../../storage/tmp`); if (!fs.existsSync(outFolder)) fs.mkdirSync(outFolder, { recursive: true }); const outputFile = path.resolve(outFolder, `${v4()}.wav`); const success = ffmpeg.convertAudioToWav(sourcePath, outputFile); if (!success) throw new Error( "[Conversion Failed]: Could not convert file to .wav format!" ); buffer = fs.readFileSync(outputFile); fs.rmSync(outputFile); const wavFile = new wavefile.WaveFile(buffer); try { this.#validateAudioFile(wavFile); } catch (error) { this.#log(`Audio validation failed: ${error.message}`); throw new Error(`Invalid audio file: ${error.message}`); } // Although we use ffmpeg to convert to the correct format (16k hz 32f), // different versions of ffmpeg produce different results based on the // environment. To ensure consistency, we convert to the correct format again. wavFile.toBitDepth("32f"); wavFile.toSampleRate(16000); let audioData = wavFile.getSamples(); if (Array.isArray(audioData)) { if (audioData.length > 1) { const SCALING_FACTOR = Math.sqrt(2); // Merge channels into first channel to save memory for (let i = 0; i < audioData[0].length; ++i) { audioData[0][i] = (SCALING_FACTOR * (audioData[0][i] + audioData[1][i])) / 2; } } audioData = audioData[0]; } return audioData; } catch (error) { console.error(`convertToWavAudioData`, error); return null; } } async client() { if (!fs.existsSync(this.modelPath)) { this.#log( `The native whisper model has never been run and will be downloaded right now. Subsequent runs will be faster. (~${this.fileSize})` ); } try { // Convert ESM to CommonJS via import so we can load this library. const pipeline = (...args) => import("@xenova/transformers").then(({ pipeline }) => { return pipeline(...args); }); return await pipeline("automatic-speech-recognition", this.model, { cache_dir: this.cacheDir, ...(!fs.existsSync(this.modelPath) ? { // Show download progress if we need to download any files progress_callback: (data) => { if (!data.hasOwnProperty("progress")) return; console.log( `\x1b[34m[Embedding - Downloading Model Files]\x1b[0m ${ data.file } ${~~data?.progress}%` ); }, } : {}), }); } catch (error) { let errMsg = error.message; if (errMsg.includes("Could not locate file")) { errMsg = "The native whisper model failed to download from the huggingface.co CDN. Your internet connection may be unstable or blocked by Huggingface.co - you will need to download the model manually and place it in the storage/models folder to use local Whisper transcription."; } this.#log( `Failed to load the native whisper model: ${errMsg}`, error.stack ); throw new Error(errMsg); } } async processFile(fullFilePath, filename) { try { const audioDataPromise = new Promise((resolve) => this.#convertToWavAudioData(fullFilePath).then((audioData) => resolve(audioData) ) ); const [audioData, transcriber] = await Promise.all([ audioDataPromise, this.client(), ]); if (!audioData) { this.#log(`Failed to parse content from ${filename}.`); return { content: null, error: `Failed to parse content from ${filename}.`, }; } this.#log(`Transcribing audio data to text...`); const { text } = await transcriber(audioData, { chunk_length_s: 30, stride_length_s: 5, }); return { content: text, error: null }; } catch (error) { return { content: null, error: error.message }; } } } module.exports = { LocalWhisper, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/WhisperProviders/ffmpeg/index.js
collector/utils/WhisperProviders/ffmpeg/index.js
const fs = require("fs"); const path = require("path"); const { execSync, spawnSync } = require("child_process"); /** * Custom FFMPEG wrapper class for audio file conversion. * Replaces deprecated fluent-ffmpeg package. * Locates ffmpeg binary and converts audio files to required * WAV format (16k hz mono 32f) for Whisper transcription. * * @class FFMPEGWrapper */ class FFMPEGWrapper { static _instance; constructor() { if (FFMPEGWrapper._instance) return FFMPEGWrapper._instance; FFMPEGWrapper._instance = this; this._ffmpegPath = null; } log(text, ...args) { console.log(`\x1b[35m[FFMPEG]\x1b[0m ${text}`, ...args); } /** * Locates ffmpeg binary. * Uses fix-path on non-Windows platforms to ensure we can find ffmpeg. * * @returns {string} Path to ffmpeg binary * @throws {Error} */ get ffmpegPath() { if (this._ffmpegPath) return this._ffmpegPath; if (process.platform !== "win32") { try { const fixPath = require("fix-path"); fixPath(); } catch (error) { this.log("Could not load fix-path, using system PATH"); } } try { const which = process.platform === "win32" ? "where" : "which"; const result = execSync(`${which} ffmpeg`, { encoding: "utf8" }).trim(); const candidatePath = result?.split("\n")?.[0]?.trim(); if (!candidatePath) throw new Error("FFMPEG candidate path not found."); if (!this.isValidFFMPEG(candidatePath)) throw new Error("FFMPEG candidate path is not valid ffmpeg binary."); this.log(`Found FFMPEG binary at ${candidatePath}`); this._ffmpegPath = candidatePath; return this._ffmpegPath; } catch (error) { this.log(error.message); } throw new Error("FFMPEG binary not found."); } /** * Validates that path points to a valid ffmpeg binary. * Runs ffmpeg -version command. * * @param {string} pathToTest - Path of ffmpeg binary * @returns {boolean} */ isValidFFMPEG(pathToTest) { try { if (!pathToTest || !fs.existsSync(pathToTest)) return false; execSync(`"${pathToTest}" -version`, { encoding: "utf8", stdio: "pipe" }); return true; } catch { return false; } } /** * Converts audio file to WAV format with required parameters for Whisper. * Output: 16k hz, mono, 32bit float. * * @param {string} inputPath - Input path for audio file (any format supported by ffmpeg) * @param {string} outputPath - Output path for converted file * @returns {boolean} * @throws {Error} If ffmpeg binary cannot be found or conversion fails */ convertAudioToWav(inputPath, outputPath) { if (!fs.existsSync(inputPath)) throw new Error(`Input file ${inputPath} does not exist.`); const outputDir = path.dirname(outputPath); if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true }); this.log(`Converting ${path.basename(inputPath)} to WAV format...`); // Convert to 16k hz mono 32f const result = spawnSync( this.ffmpegPath, [ "-i", inputPath, "-ar", "16000", "-ac", "1", "-acodec", "pcm_f32le", "-y", outputPath, ], { encoding: "utf8" } ); // ffmpeg writes progress to stderr if (result.stderr) this.log(result.stderr.trim()); if (result.status !== 0) throw new Error(`FFMPEG conversion failed`); this.log(`Conversion complete: ${path.basename(outputPath)}`); return true; } } module.exports = { FFMPEGWrapper };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/EncryptionWorker/index.js
collector/utils/EncryptionWorker/index.js
const crypto = require("crypto"); // Differs from EncryptionManager in that is does not set or define the keys that will be used // to encrypt or read data and it must be told the key (as base64 string) explicitly that will be used and is provided to // the class on creation. This key should be the same `key` that is used by the EncryptionManager class. class EncryptionWorker { constructor(presetKeyBase64 = "") { this.key = Buffer.from(presetKeyBase64, "base64"); this.algorithm = "aes-256-cbc"; this.separator = ":"; } log(text, ...args) { console.log(`\x1b[36m[EncryptionManager]\x1b[0m ${text}`, ...args); } /** * Give a chunk source, parse its payload query param and expand that object back into the URL * as additional query params * @param {string} chunkSource * @returns {URL} Javascript URL object with query params decrypted from payload query param. */ expandPayload(chunkSource = "") { try { const url = new URL(chunkSource); if (!url.searchParams.has("payload")) return url; const decryptedPayload = this.decrypt(url.searchParams.get("payload")); const encodedParams = JSON.parse(decryptedPayload); url.searchParams.delete("payload"); // remove payload prop // Add all query params needed to replay as query params Object.entries(encodedParams).forEach(([key, value]) => url.searchParams.append(key, value) ); return url; } catch (e) { console.error(e); } return new URL(chunkSource); } encrypt(plainTextString = null) { try { if (!plainTextString) throw new Error("Empty string is not valid for this method."); const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv(this.algorithm, this.key, iv); const encrypted = cipher.update(plainTextString, "utf8", "hex"); return [ encrypted + cipher.final("hex"), Buffer.from(iv).toString("hex"), ].join(this.separator); } catch (e) { this.log(e); return null; } } decrypt(encryptedString) { try { const [encrypted, iv] = encryptedString.split(this.separator); if (!iv) throw new Error("IV not found"); const decipher = crypto.createDecipheriv( this.algorithm, this.key, Buffer.from(iv, "hex") ); return decipher.update(encrypted, "hex", "utf8") + decipher.final("utf8"); } catch (e) { this.log(e); return null; } } } module.exports = { EncryptionWorker };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/http/index.js
collector/utils/http/index.js
process.env.NODE_ENV === "development" ? require("dotenv").config({ path: `.env.${process.env.NODE_ENV}` }) : require("dotenv").config(); function reqBody(request) { return typeof request.body === "string" ? JSON.parse(request.body) : request.body; } function queryParams(request) { return request.query; } /** * Validates if the provided baseUrl is a valid URL at all. * - Does not validate if the URL is reachable or accessible. * - Does not do any further validation of the URL like `validURL` in `utils/url/index.js` * @param {string} baseUrl * @returns {boolean} */ function validBaseUrl(baseUrl) { try { new URL(baseUrl); return true; } catch (e) { return false; } } module.exports = { reqBody, queryParams, validBaseUrl, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/__tests__/utils/url/index.test.js
collector/__tests__/utils/url/index.test.js
process.env.STORAGE_DIR = "test-storage"; // needed for tests to run const { validURL, validateURL, validYoutubeVideoUrl } = require("../../../utils/url"); // Mock the RuntimeSettings module jest.mock("../../../utils/runtimeSettings", () => { const mockInstance = { get: jest.fn(), set: jest.fn(), }; return jest.fn().mockImplementation(() => mockInstance); }); describe("validURL", () => { let mockRuntimeSettings; beforeEach(() => { const RuntimeSettings = require("../../../utils/runtimeSettings"); mockRuntimeSettings = new RuntimeSettings(); jest.clearAllMocks(); }); it("should validate a valid URL", () => { mockRuntimeSettings.get.mockImplementation((key) => { if (key === "allowAnyIp") return false; if (key === "seenAnyIpWarning") return true; // silence the warning for tests return false; }); expect(validURL("https://www.google.com")).toBe(true); expect(validURL("http://www.google.com")).toBe(true); // JS URL does not require extensions, so in theory // these should be valid expect(validURL("https://random")).toBe(true); expect(validURL("http://123")).toBe(true); // missing protocols expect(validURL("www.google.com")).toBe(false); expect(validURL("google.com")).toBe(false); // invalid protocols expect(validURL("ftp://www.google.com")).toBe(false); expect(validURL("mailto://www.google.com")).toBe(false); expect(validURL("tel://www.google.com")).toBe(false); expect(validURL("data://www.google.com")).toBe(false); }); it("should block private/local IPs when allowAnyIp is false (default behavior)", () => { mockRuntimeSettings.get.mockImplementation((key) => { if (key === "allowAnyIp") return false; if (key === "seenAnyIpWarning") return true; // silence the warning for tests return false; }); expect(validURL("http://192.168.1.1")).toBe(false); expect(validURL("http://10.0.0.1")).toBe(false); expect(validURL("http://172.16.0.1")).toBe(false); // But localhost should still be allowed expect(validURL("http://127.0.0.1")).toBe(true); expect(validURL("http://0.0.0.0")).toBe(true); }); it("should allow any IP when allowAnyIp is true", () => { mockRuntimeSettings.get.mockImplementation((key) => { if (key === "allowAnyIp") return true; if (key === "seenAnyIpWarning") return true; // silence the warning for tests return false; }); expect(validURL("http://192.168.1.1")).toBe(true); expect(validURL("http://10.0.0.1")).toBe(true); expect(validURL("http://172.16.0.1")).toBe(true); }); }); describe("validateURL", () => { it("should return the same URL if it's already valid", () => { expect(validateURL("https://www.google.com")).toBe( "https://www.google.com" ); expect(validateURL("http://www.google.com")).toBe("http://www.google.com"); expect(validateURL("https://random")).toBe("https://random"); // With numbers as a url this will turn into an ip expect(validateURL("123")).toBe("https://0.0.0.123"); expect(validateURL("123.123.123.123")).toBe("https://123.123.123.123"); expect(validateURL("http://127.0.123.45")).toBe("http://127.0.123.45"); }); it("should assume https:// if the URL doesn't have a protocol", () => { expect(validateURL("www.google.com")).toBe("https://www.google.com"); expect(validateURL("google.com")).toBe("https://google.com"); expect(validateURL("EXAMPLE.com/ABCDEF/q1=UPPER")).toBe("https://example.com/ABCDEF/q1=UPPER"); expect(validateURL("ftp://www.google.com")).toBe("ftp://www.google.com"); expect(validateURL("mailto://www.google.com")).toBe( "mailto://www.google.com" ); expect(validateURL("tel://www.google.com")).toBe("tel://www.google.com"); expect(validateURL("data://www.google.com")).toBe("data://www.google.com"); }); it("should remove trailing slashes post-validation", () => { expect(validateURL("https://www.google.com/")).toBe( "https://www.google.com" ); expect(validateURL("http://www.google.com/")).toBe("http://www.google.com"); expect(validateURL("https://random/")).toBe("https://random"); expect(validateURL("https://example.com/ABCDEF/")).toBe("https://example.com/ABCDEF"); }); it("should handle edge cases and bad data inputs", () => { expect(validateURL({})).toBe(""); expect(validateURL(null)).toBe(""); expect(validateURL(undefined)).toBe(""); expect(validateURL(124512)).toBe(""); expect(validateURL("")).toBe(""); expect(validateURL(" ")).toBe(""); expect(validateURL(" look here! ")).toBe("look here!"); }); it("should preserve case of characters in URL pathname", () => { expect(validateURL("https://example.com/To/ResOURce?q1=Value&qZ22=UPPE!R")) .toBe("https://example.com/To/ResOURce?q1=Value&qZ22=UPPE!R"); expect(validateURL("https://sample.com/uPeRCaSe")) .toBe("https://sample.com/uPeRCaSe"); expect(validateURL("Example.com/PATH/To/Resource?q2=Value&q1=UPPER")) .toBe("https://example.com/PATH/To/Resource?q2=Value&q1=UPPER"); }); }); describe("validYoutubeVideoUrl", () => { const ID = "dQw4w9WgXcQ"; // 11-char valid video id it("returns true for youtube watch URLs with v param", () => { expect(validYoutubeVideoUrl(`https://www.youtube.com/watch?v=${ID}`)).toBe( true ); expect(validYoutubeVideoUrl(`https://youtube.com/watch?v=${ID}&t=10s`)).toBe( true ); expect(validYoutubeVideoUrl(`https://m.youtube.com/watch?v=${ID}`)).toBe(true); expect(validYoutubeVideoUrl(`youtube.com/watch?v=${ID}`)).toBe(true); }); it("returns true for youtu.be short URLs", () => { expect(validYoutubeVideoUrl(`https://youtu.be/${ID}`)).toBe(true); expect(validYoutubeVideoUrl(`https://youtu.be/${ID}?si=abc`)).toBe(true); // extra path segments after id should still validate the id component expect(validYoutubeVideoUrl(`https://youtu.be/${ID}/extra`)).toBe(true); }); it("returns true for embed and v path formats", () => { expect(validYoutubeVideoUrl(`https://www.youtube.com/embed/${ID}`)).toBe(true); expect(validYoutubeVideoUrl(`https://youtube.com/v/${ID}`)).toBe(true); }); it("returns false for non-YouTube hosts", () => { expect(validYoutubeVideoUrl("https://example.com/watch?v=dQw4w9WgXcQ")).toBe( false ); expect(validYoutubeVideoUrl("https://vimeo.com/123456")).toBe(false); }); it("returns false for unrelated YouTube paths without a video id", () => { expect(validYoutubeVideoUrl("https://www.youtube.com/user/somechannel")).toBe( false ); expect(validYoutubeVideoUrl("https://www.youtube.com/")).toBe(false); }); it("returns false for empty or bad inputs", () => { expect(validYoutubeVideoUrl("")).toBe(false); expect(validYoutubeVideoUrl(null)).toBe(false); expect(validYoutubeVideoUrl(undefined)).toBe(false); }); it("returns the video ID for valid YouTube video URLs", () => { expect(validYoutubeVideoUrl(`https://www.youtube.com/watch?v=${ID}`, true)).toBe(ID); expect(validYoutubeVideoUrl(`https://youtube.com/watch?v=${ID}&t=10s`, true)).toBe(ID); expect(validYoutubeVideoUrl(`https://m.youtube.com/watch?v=${ID}`, true)).toBe(ID); expect(validYoutubeVideoUrl(`youtube.com/watch?v=${ID}`, true)).toBe(ID); expect(validYoutubeVideoUrl(`https://youtu.be/${ID}`, true)).toBe(ID); expect(validYoutubeVideoUrl(`https://youtu.be/${ID}?si=abc`, true)).toBe(ID); expect(validYoutubeVideoUrl(`https://youtu.be/${ID}/extra`, true)).toBe(ID); expect(validYoutubeVideoUrl(`https://www.youtube.com/embed/${ID}`, true)).toBe(ID); expect(validYoutubeVideoUrl(`https://youtube.com/v/${ID}`, true)).toBe(ID); // invalid video IDs expect(validYoutubeVideoUrl(`https://www.youtube.com/watch?v=invalid`, true)).toBe(null); expect(validYoutubeVideoUrl(`https://youtube.com/watch?v=invalid`, true)).toBe(null); expect(validYoutubeVideoUrl(`https://m.youtube.com/watch?v=invalid`, true)).toBe(null); expect(validYoutubeVideoUrl(`youtube.com/watch`, true)).toBe(null); expect(validYoutubeVideoUrl(`https://youtu.be/invalid`, true)).toBe(null); expect(validYoutubeVideoUrl(`https://youtu.be/invalid?si=abc`, true)).toBe(null); }); });
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/__tests__/utils/WhisperProviders/ffmpeg/index.test.js
collector/__tests__/utils/WhisperProviders/ffmpeg/index.test.js
process.env.STORAGE_DIR = "test-storage"; const fs = require("fs"); const path = require("path"); // Mock fix-path as a noop to prevent SIGSEGV (segfault) jest.mock("fix-path", () => jest.fn()); const { FFMPEGWrapper } = require("../../../../utils/WhisperProviders/ffmpeg"); const describeRunner = process.env.GITHUB_ACTIONS ? describe.skip : describe; describeRunner("FFMPEGWrapper", () => { /** @type { import("../../../../utils/WhisperProviders/ffmpeg/index").FFMPEGWrapper } */ let ffmpeg; const testDir = path.resolve(__dirname, "../../../../storage/tmp"); const inputPath = path.resolve(testDir, "test-input.wav"); const outputPath = path.resolve(testDir, "test-output.wav"); beforeEach(() => { ffmpeg = new FFMPEGWrapper(); }); afterEach(() => { if (fs.existsSync(inputPath)) fs.rmSync(inputPath); if (fs.existsSync(outputPath)) fs.rmSync(outputPath); }); it("should find ffmpeg executable", async () => { const knownPath = ffmpeg.ffmpegPath; expect(knownPath).toBeDefined(); expect(typeof knownPath).toBe("string"); expect(knownPath.length).toBeGreaterThan(0); }); it("should validate ffmpeg executable", async () => { const knownPath = ffmpeg.ffmpegPath; expect(ffmpeg.isValidFFMPEG(knownPath)).toBe(true); }); it("should return false for invalid ffmpeg path", () => { expect(ffmpeg.isValidFFMPEG("/invalid/path/to/ffmpeg")).toBe(false); }); it("should convert audio file to wav format", async () => { if (!fs.existsSync(testDir)) fs.mkdirSync(testDir, { recursive: true }); const sampleUrl = "https://github.com/ringcentral/ringcentral-api-docs/blob/main/resources/sample1.wav?raw=true"; const response = await fetch(sampleUrl); if (!response.ok) throw new Error( `Failed to download sample file: ${response.statusText}` ); const buffer = await response.arrayBuffer(); fs.writeFileSync(inputPath, Buffer.from(buffer)); const result = ffmpeg.convertAudioToWav(inputPath, outputPath); expect(result).toBe(true); expect(fs.existsSync(outputPath)).toBe(true); const stats = fs.statSync(outputPath); expect(stats.size).toBeGreaterThan(0); }, 30000); it("should throw error when conversion fails", () => { const nonExistentFile = path.resolve(testDir, "non-existent-file.wav"); const outputPath = path.resolve(testDir, "test-output-fail.wav"); expect(() => { ffmpeg.convertAudioToWav(nonExistentFile, outputPath) }).toThrow(`Input file ${nonExistentFile} does not exist.`); }); });
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processRawText/index.js
collector/processRawText/index.js
const { v4 } = require("uuid"); const { writeToServerDocuments } = require("../utils/files"); const { tokenizeString } = require("../utils/tokenizer"); const { default: slugify } = require("slugify"); // Will remove the last .extension from the input // and stringify the input + move to lowercase. function stripAndSlug(input) { if (!input.includes('.')) return slugify(input, { lower: true }); return slugify(input.split('.').slice(0, -1).join('-'), { lower: true }) } const METADATA_KEYS = { possible: { url: ({ url, title }) => { let validUrl; try { const u = new URL(url); validUrl = ["https:", "http:"].includes(u.protocol); } catch { } if (validUrl) return `web://${url.toLowerCase()}.website`; return `file://${stripAndSlug(title)}.txt`; }, title: ({ title }) => `${stripAndSlug(title)}.txt`, docAuthor: ({ docAuthor }) => { return typeof docAuthor === 'string' ? docAuthor : 'no author specified' }, description: ({ description }) => { return typeof description === 'string' ? description : 'no description found' }, docSource: ({ docSource }) => { return typeof docSource === 'string' ? docSource : 'no source set' }, chunkSource: ({ chunkSource, title }) => { return typeof chunkSource === 'string' ? chunkSource : `${stripAndSlug(title)}.txt` }, published: ({ published }) => { if (isNaN(Number(published))) return new Date().toLocaleString(); return new Date(Number(published)).toLocaleString() }, } } async function processRawText(textContent, metadata) { console.log(`-- Working Raw Text doc ${metadata.title} --`); if (!textContent || textContent.length === 0) { return { success: false, reason: "textContent was empty - nothing to process.", documents: [], }; } const data = { id: v4(), url: METADATA_KEYS.possible.url(metadata), title: METADATA_KEYS.possible.title(metadata), docAuthor: METADATA_KEYS.possible.docAuthor(metadata), description: METADATA_KEYS.possible.description(metadata), docSource: METADATA_KEYS.possible.docSource(metadata), chunkSource: METADATA_KEYS.possible.chunkSource(metadata), published: METADATA_KEYS.possible.published(metadata), wordCount: textContent.split(" ").length, pageContent: textContent, token_count_estimate: tokenizeString(textContent), }; const document = writeToServerDocuments({ data, filename: `raw-${stripAndSlug(metadata.title)}-${data.id}`, }); console.log(`[SUCCESS]: Raw text and metadata saved & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; } module.exports = { processRawText }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/tailwind.config.js
frontend/tailwind.config.js
/** @type {import('tailwindcss').Config} */ export default { darkMode: "class", content: { relative: true, files: [ "./src/components/**/*.{js,jsx}", "./src/hooks/**/*.js", "./src/models/**/*.js", "./src/pages/**/*.{js,jsx}", "./src/utils/**/*.js", "./src/*.jsx", "./index.html", "./node_modules/@tremor/**/*.{js,ts,jsx,tsx}" ] }, theme: { extend: { rotate: { "270": "270deg", "360": "360deg" }, colors: { "black-900": "#141414", accent: "#3D4147", "sidebar-button": "#31353A", sidebar: "#25272C", "historical-msg-system": "rgba(255, 255, 255, 0.05);", "historical-msg-user": "#2C2F35", outline: "#4E5153", "primary-button": "var(--theme-button-primary)", "cta-button": "var(--theme-button-cta)", secondary: "#2C2F36", "dark-input": "#18181B", "mobile-onboarding": "#2C2F35", "dark-highlight": "#1C1E21", "dark-text": "#222628", description: "#D2D5DB", "x-button": "#9CA3AF", royalblue: "#065986", purple: "#4A1FB8", magenta: "#9E165F", danger: "#F04438", error: "#B42318", warn: "#854708", success: "#05603A", darker: "#F4F4F4", teal: "#0BA5EC", // Generic theme colors theme: { bg: { primary: 'var(--theme-bg-primary)', secondary: 'var(--theme-bg-secondary)', sidebar: 'var(--theme-bg-sidebar)', container: 'var(--theme-bg-container)', chat: 'var(--theme-bg-chat)', "chat-input": 'var(--theme-bg-chat-input)', "popup-menu": 'var(--theme-popup-menu-bg)', }, text: { primary: 'var(--theme-text-primary)', secondary: 'var(--theme-text-secondary)', placeholder: 'var(--theme-placeholder)', }, sidebar: { item: { default: 'var(--theme-sidebar-item-default)', selected: 'var(--theme-sidebar-item-selected)', hover: 'var(--theme-sidebar-item-hover)', }, subitem: { default: 'var(--theme-sidebar-subitem-default)', selected: 'var(--theme-sidebar-subitem-selected)', hover: 'var(--theme-sidebar-subitem-hover)', }, footer: { icon: 'var(--theme-sidebar-footer-icon)', 'icon-hover': 'var(--theme-sidebar-footer-icon-hover)', }, border: 'var(--theme-sidebar-border)', }, "chat-input": { border: 'var(--theme-chat-input-border)', }, "action-menu": { bg: 'var(--theme-action-menu-bg)', "item-hover": 'var(--theme-action-menu-item-hover)', }, settings: { input: { bg: 'var(--theme-settings-input-bg)', active: 'var(--theme-settings-input-active)', placeholder: 'var(--theme-settings-input-placeholder)', text: 'var(--theme-settings-input-text)', } }, modal: { border: 'var(--theme-modal-border)', }, "file-picker": { hover: 'var(--theme-file-picker-hover)', }, attachment: { bg: 'var(--theme-attachment-bg)', 'error-bg': 'var(--theme-attachment-error-bg)', 'success-bg': 'var(--theme-attachment-success-bg)', text: 'var(--theme-attachment-text)', 'text-secondary': 'var(--theme-attachment-text-secondary)', 'icon': 'var(--theme-attachment-icon)', 'icon-spinner': 'var(--theme-attachment-icon-spinner)', 'icon-spinner-bg': 'var(--theme-attachment-icon-spinner-bg)', }, home: { text: 'var(--theme-home-text)', "text-secondary": 'var(--theme-home-text-secondary)', "bg-card": 'var(--theme-home-bg-card)', "bg-button": 'var(--theme-home-bg-button)', border: 'var(--theme-home-border)', "button-primary": 'var(--theme-home-button-primary)', "button-primary-hover": 'var(--theme-home-button-primary-hover)', "button-secondary": 'var(--theme-home-button-secondary)', "button-secondary-hover": 'var(--theme-home-button-secondary-hover)', "button-secondary-text": 'var(--theme-home-button-secondary-text)', "button-secondary-hover-text": 'var(--theme-home-button-secondary-hover-text)', "button-secondary-border": 'var(--theme-home-button-secondary-border)', "button-secondary-border-hover": 'var(--theme-home-button-secondary-border-hover)', "update-card-bg": 'var(--theme-home-update-card-bg)', "update-card-hover": 'var(--theme-home-update-card-hover)', "update-source": 'var(--theme-home-update-source)', }, checklist: { "item-bg": 'var(--theme-checklist-item-bg)', "item-bg-hover": 'var(--theme-checklist-item-bg-hover)', "item-text": 'var(--theme-checklist-item-text)', "item-completed-bg": 'var(--theme-checklist-item-completed-bg)', "item-completed-text": 'var(--theme-checklist-item-completed-text)', "item-hover": 'var(--theme-checklist-item-hover)', "checkbox-border": 'var(--theme-checklist-checkbox-border)', "checkbox-fill": 'var(--theme-checklist-checkbox-fill)', "checkbox-text": 'var(--theme-checklist-checkbox-text)', "button-border": 'var(--theme-checklist-button-border)', "button-text": 'var(--theme-checklist-button-text)', "button-hover-bg": 'var(--theme-checklist-button-hover-bg)', "button-hover-border": 'var(--theme-checklist-button-hover-border)', }, button: { text: 'var(--theme-button-text)', 'code-hover-text': 'var(--theme-button-code-hover-text)', 'code-hover-bg': 'var(--theme-button-code-hover-bg)', 'disable-hover-text': 'var(--theme-button-disable-hover-text)', 'disable-hover-bg': 'var(--theme-button-disable-hover-bg)', 'delete-hover-text': 'var(--theme-button-delete-hover-text)', 'delete-hover-bg': 'var(--theme-button-delete-hover-bg)', }, }, }, backgroundImage: { "preference-gradient": "linear-gradient(180deg, #5A5C63 0%, rgba(90, 92, 99, 0.28) 100%);", "chat-msg-user-gradient": "linear-gradient(180deg, #3D4147 0%, #2C2F35 100%);", "selected-preference-gradient": "linear-gradient(180deg, #313236 0%, rgba(63.40, 64.90, 70.13, 0) 100%);", "main-gradient": "linear-gradient(180deg, #3D4147 0%, #2C2F35 100%)", "modal-gradient": "linear-gradient(180deg, #3D4147 0%, #2C2F35 100%)", "sidebar-gradient": "linear-gradient(90deg, #5B616A 0%, #3F434B 100%)", "login-gradient": "linear-gradient(180deg, #3D4147 0%, #2C2F35 100%)", "menu-item-gradient": "linear-gradient(90deg, #3D4147 0%, #2C2F35 100%)", "menu-item-selected-gradient": "linear-gradient(90deg, #5B616A 0%, #3F434B 100%)", "workspace-item-gradient": "linear-gradient(90deg, #3D4147 0%, #2C2F35 100%)", "workspace-item-selected-gradient": "linear-gradient(90deg, #5B616A 0%, #3F434B 100%)", "switch-selected": "linear-gradient(146deg, #5B616A 0%, #3F434B 100%)" }, fontFamily: { sans: [ "plus-jakarta-sans", "ui-sans-serif", "system-ui", "-apple-system", "BlinkMacSystemFont", '"Segoe UI"', "Roboto", '"Helvetica Neue"', "Arial", '"Noto Sans"', "sans-serif", '"Apple Color Emoji"', '"Segoe UI Emoji"', '"Segoe UI Symbol"', '"Noto Color Emoji"' ] }, animation: { sweep: "sweep 0.5s ease-in-out", "pulse-glow": "pulse-glow 1.5s infinite", 'fade-in': 'fade-in 0.3s ease-out', 'slide-up': 'slide-up 0.4s ease-out forwards', 'bounce-subtle': 'bounce-subtle 2s ease-in-out infinite' }, keyframes: { sweep: { "0%": { transform: "scaleX(0)", transformOrigin: "bottom left" }, "100%": { transform: "scaleX(1)", transformOrigin: "bottom left" } }, fadeIn: { "0%": { opacity: 0 }, "100%": { opacity: 1 } }, fadeOut: { "0%": { opacity: 1 }, "100%": { opacity: 0 } }, "pulse-glow": { "0%": { opacity: 1, transform: "scale(1)", boxShadow: "0 0 0 rgba(255, 255, 255, 0.0)", backgroundColor: "rgba(255, 255, 255, 0.0)" }, "50%": { opacity: 1, transform: "scale(1.1)", boxShadow: "0 0 15px rgba(255, 255, 255, 0.2)", backgroundColor: "rgba(255, 255, 255, 0.1)" }, "100%": { opacity: 1, transform: "scale(1)", boxShadow: "0 0 0 rgba(255, 255, 255, 0.0)", backgroundColor: "rgba(255, 255, 255, 0.0)" } }, 'fade-in': { '0%': { opacity: '0' }, '100%': { opacity: '1' } }, 'slide-up': { '0%': { transform: 'translateY(10px)', opacity: '0' }, '100%': { transform: 'translateY(0)', opacity: '1' } }, 'bounce-subtle': { '0%, 100%': { transform: 'translateY(0)' }, '50%': { transform: 'translateY(-2px)' } } } } }, variants: { extend: { backgroundColor: ['light'], textColor: ['light'], } }, // Required for rechart styles to show since they can be rendered dynamically and will be tree-shaken if not safe-listed. safelist: [ { pattern: /^(bg-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/, variants: ["hover", "ui-selected"] }, { pattern: /^(text-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/, variants: ["hover", "ui-selected"] }, { pattern: /^(border-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/, variants: ["hover", "ui-selected"] }, { pattern: /^(ring-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/ }, { pattern: /^(stroke-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/ }, { pattern: /^(fill-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/ } ], plugins: [ function ({ addVariant }) { addVariant('light', '.light &') // Add the `light:` variant addVariant('pwa', '.pwa &') // Add the `pwa:` variant }, ] }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/postcss.config.js
frontend/postcss.config.js
import tailwind from 'tailwindcss' import autoprefixer from 'autoprefixer' import tailwindConfig from './tailwind.config.js' export default { plugins: [tailwind(tailwindConfig), autoprefixer], }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/vite.config.js
frontend/vite.config.js
import { defineConfig } from "vite" import { fileURLToPath, URL } from "url" import postcss from "./postcss.config.js" import react from "@vitejs/plugin-react" import dns from "dns" import { visualizer } from "rollup-plugin-visualizer" dns.setDefaultResultOrder("verbatim") // https://vitejs.dev/config/ export default defineConfig({ assetsInclude: [ './public/piper/ort-wasm-simd-threaded.wasm', './public/piper/piper_phonemize.wasm', './public/piper/piper_phonemize.data', ], worker: { format: 'es' }, server: { port: 3000, host: "localhost" }, define: { "process.env": process.env }, css: { postcss }, plugins: [ react(), visualizer({ template: "treemap", // or sunburst open: false, gzipSize: true, brotliSize: true, filename: "bundleinspector.html" // will be saved in project's root }) ], resolve: { alias: [ { find: "@", replacement: fileURLToPath(new URL("./src", import.meta.url)) }, { process: "process/browser", stream: "stream-browserify", zlib: "browserify-zlib", util: "util", find: /^~.+/, replacement: (val) => { return val.replace(/^~/, "") } } ] }, build: { rollupOptions: { output: { // These settings ensure the primary JS and CSS file references are always index.{js,css} // so we can SSR the index.html as text response from server/index.js without breaking references each build. entryFileNames: 'index.js', assetFileNames: (assetInfo) => { if (assetInfo.name === 'index.css') return `index.css`; return assetInfo.name; }, }, external: [ // Reduces transformation time by 50% and we don't even use this variant, so we can ignore. /@phosphor-icons\/react\/dist\/ssr/, ] }, commonjsOptions: { transformMixedEsModules: true } }, optimizeDeps: { include: ["@mintplex-labs/piper-tts-web"], esbuildOptions: { define: { global: "globalThis" }, plugins: [] } } })
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/eslint.config.js
frontend/eslint.config.js
import js from "@eslint/js" import globals from "globals" import pluginReact from "eslint-plugin-react" import pluginReactHooks from "eslint-plugin-react-hooks" import pluginPrettier from "eslint-plugin-prettier" import configPrettier from "eslint-config-prettier" import { defineConfig } from "eslint/config" export default defineConfig([ { ignores: ["**/*.min.js", "src/media/**/*"] }, { files: ["src/**/*.{js,jsx}"], plugins: { js }, extends: ["js/recommended"], languageOptions: { globals: globals.browser } }, { files: ["src/**/*.{js,jsx}"], ...pluginReact.configs.flat.recommended, plugins: { "react-hooks": pluginReactHooks, prettier: pluginPrettier }, settings: { react: { version: "detect" } }, rules: { ...configPrettier.rules, "prettier/prettier": "error", "react/react-in-jsx-scope": "off", "react-hooks/exhaustive-deps": "off", "no-extra-boolean-cast": "off", "no-prototype-builtins": "off", "no-unused-vars": "off", "no-empty": "off", "no-useless-escape": "off", "no-undef": "off", "no-unsafe-optional-chaining": "off", "no-constant-binary-expression": "off" } } ])
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/frontend/scripts/postbuild.js
frontend/scripts/postbuild.js
import { renameSync } from 'fs'; import { fileURLToPath } from 'url'; import path from 'path'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); console.log(`Running frontend post build script...`) renameSync(path.resolve(__dirname, '../dist/index.html'), path.resolve(__dirname, '../dist/_index.html')); console.log(`index.html renamed to _index.html so SSR of the index page can be assumed.`);
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/AuthContext.jsx
frontend/src/AuthContext.jsx
import React, { useState, createContext, useEffect } from "react"; import { AUTH_TIMESTAMP, AUTH_TOKEN, AUTH_USER, USER_PROMPT_INPUT_MAP, } from "@/utils/constants"; import System from "./models/system"; import { useNavigate } from "react-router-dom"; import { safeJsonParse } from "@/utils/request"; export const AuthContext = createContext(null); export function AuthProvider(props) { const localUser = localStorage.getItem(AUTH_USER); const localAuthToken = localStorage.getItem(AUTH_TOKEN); const [store, setStore] = useState({ user: localUser ? safeJsonParse(localUser, null) : null, authToken: localAuthToken ? localAuthToken : null, }); const navigate = useNavigate(); /* NOTE: * 1. There's no reason for these helper functions to be stateful. They could * just be regular funcs or methods on a basic object. * 2. These actions are not being invoked anywhere in the * codebase, dead code. */ const [actions] = useState({ updateUser: (user, authToken = "") => { localStorage.setItem(AUTH_USER, JSON.stringify(user)); localStorage.setItem(AUTH_TOKEN, authToken); setStore({ user, authToken }); }, unsetUser: () => { localStorage.removeItem(AUTH_USER); localStorage.removeItem(AUTH_TOKEN); localStorage.removeItem(AUTH_TIMESTAMP); localStorage.removeItem(USER_PROMPT_INPUT_MAP); setStore({ user: null, authToken: null }); }, }); /* * On initial mount and whenever the token changes, fetch a new user object * If the user is suspended, (success === false and data === null) logout the user and redirect to the login page * If success is true and data is not null, update the user object in the store (multi-user mode only) * If success is true and data is null, do nothing (single-user mode only) with or without password protection */ useEffect(() => { async function refreshUser() { const { success, user: refreshedUser } = await System.refreshUser(); if (success && refreshedUser === null) return; if (!success) { localStorage.removeItem(AUTH_USER); localStorage.removeItem(AUTH_TOKEN); localStorage.removeItem(AUTH_TIMESTAMP); localStorage.removeItem(USER_PROMPT_INPUT_MAP); setStore({ user: null, authToken: null }); navigate("/login"); return; } localStorage.setItem(AUTH_USER, JSON.stringify(refreshedUser)); setStore((prev) => ({ ...prev, user: refreshedUser, })); } if (store.authToken) refreshUser(); }, [store.authToken]); return ( <AuthContext.Provider value={{ store, actions }}> {props.children} </AuthContext.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/i18n.js
frontend/src/i18n.js
import i18next from "i18next"; import { initReactI18next } from "react-i18next"; import LanguageDetector from "i18next-browser-languagedetector"; import { defaultNS, resources } from "./locales/resources"; i18next // https://github.com/i18next/i18next-browser-languageDetector/blob/9efebe6ca0271c3797bc09b84babf1ba2d9b4dbb/src/index.js#L11 .use(initReactI18next) // Initialize i18n for React .use(LanguageDetector) .init({ fallbackLng: "en", debug: import.meta.env.DEV, defaultNS, resources, lowerCaseLng: true, interpolation: { escapeValue: false, }, }); export default i18next;
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/LogoContext.jsx
frontend/src/LogoContext.jsx
import { createContext, useEffect, useState } from "react"; import AnythingLLM from "./media/logo/anything-llm.png"; import AnythingLLMDark from "./media/logo/anything-llm-dark.png"; import DefaultLoginLogoLight from "./media/illustrations/login-logo.svg"; import DefaultLoginLogoDark from "./media/illustrations/login-logo-light.svg"; import System from "./models/system"; export const REFETCH_LOGO_EVENT = "refetch-logo"; export const LogoContext = createContext(); export function LogoProvider({ children }) { const [logo, setLogo] = useState(""); const [loginLogo, setLoginLogo] = useState(""); const [isCustomLogo, setIsCustomLogo] = useState(false); const DefaultLoginLogo = localStorage.getItem("theme") !== "default" ? DefaultLoginLogoDark : DefaultLoginLogoLight; async function fetchInstanceLogo() { try { const { isCustomLogo, logoURL } = await System.fetchLogo(); if (logoURL) { setLogo(logoURL); setLoginLogo(isCustomLogo ? logoURL : DefaultLoginLogo); setIsCustomLogo(isCustomLogo); } else { localStorage.getItem("theme") !== "default" ? setLogo(AnythingLLMDark) : setLogo(AnythingLLM); setLoginLogo(DefaultLoginLogo); setIsCustomLogo(false); } } catch (err) { localStorage.getItem("theme") !== "default" ? setLogo(AnythingLLMDark) : setLogo(AnythingLLM); setLoginLogo(DefaultLoginLogo); setIsCustomLogo(false); console.error("Failed to fetch logo:", err); } } useEffect(() => { fetchInstanceLogo(); window.addEventListener(REFETCH_LOGO_EVENT, fetchInstanceLogo); return () => { window.removeEventListener(REFETCH_LOGO_EVENT, fetchInstanceLogo); }; }, []); return ( <LogoContext.Provider value={{ logo, setLogo, loginLogo, isCustomLogo }}> {children} </LogoContext.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/main.jsx
frontend/src/main.jsx
import React from "react"; import ReactDOM from "react-dom/client"; import { createBrowserRouter, RouterProvider } from "react-router-dom"; import App from "@/App.jsx"; import PrivateRoute, { AdminRoute, ManagerRoute, } from "@/components/PrivateRoute"; import Login from "@/pages/Login"; import SimpleSSOPassthrough from "@/pages/Login/SSO/simple"; import OnboardingFlow from "@/pages/OnboardingFlow"; import "@/index.css"; const isDev = process.env.NODE_ENV !== "production"; const REACTWRAP = isDev ? React.Fragment : React.StrictMode; const router = createBrowserRouter([ { path: "/", element: <App />, children: [ { path: "/", lazy: async () => { const { default: Main } = await import("@/pages/Main"); return { element: <PrivateRoute Component={Main} /> }; }, }, { path: "/login", element: <Login />, }, { path: "/sso/simple", element: <SimpleSSOPassthrough />, }, { path: "/workspace/:slug/settings/:tab", lazy: async () => { const { default: WorkspaceSettings } = await import( "@/pages/WorkspaceSettings" ); return { element: <ManagerRoute Component={WorkspaceSettings} /> }; }, }, { path: "/workspace/:slug", lazy: async () => { const { default: WorkspaceChat } = await import( "@/pages/WorkspaceChat" ); return { element: <PrivateRoute Component={WorkspaceChat} /> }; }, }, { path: "/workspace/:slug/t/:threadSlug", lazy: async () => { const { default: WorkspaceChat } = await import( "@/pages/WorkspaceChat" ); return { element: <PrivateRoute Component={WorkspaceChat} /> }; }, }, { path: "/accept-invite/:code", lazy: async () => { const { default: InvitePage } = await import("@/pages/Invite"); return { element: <InvitePage /> }; }, }, // Admin routes { path: "/settings/llm-preference", lazy: async () => { const { default: GeneralLLMPreference } = await import( "@/pages/GeneralSettings/LLMPreference" ); return { element: <AdminRoute Component={GeneralLLMPreference} /> }; }, }, { path: "/settings/transcription-preference", lazy: async () => { const { default: GeneralTranscriptionPreference } = await import( "@/pages/GeneralSettings/TranscriptionPreference" ); return { element: <AdminRoute Component={GeneralTranscriptionPreference} />, }; }, }, { path: "/settings/audio-preference", lazy: async () => { const { default: GeneralAudioPreference } = await import( "@/pages/GeneralSettings/AudioPreference" ); return { element: <AdminRoute Component={GeneralAudioPreference} />, }; }, }, { path: "/settings/embedding-preference", lazy: async () => { const { default: GeneralEmbeddingPreference } = await import( "@/pages/GeneralSettings/EmbeddingPreference" ); return { element: <AdminRoute Component={GeneralEmbeddingPreference} />, }; }, }, { path: "/settings/text-splitter-preference", lazy: async () => { const { default: EmbeddingTextSplitterPreference } = await import( "@/pages/GeneralSettings/EmbeddingTextSplitterPreference" ); return { element: <AdminRoute Component={EmbeddingTextSplitterPreference} />, }; }, }, { path: "/settings/vector-database", lazy: async () => { const { default: GeneralVectorDatabase } = await import( "@/pages/GeneralSettings/VectorDatabase" ); return { element: <AdminRoute Component={GeneralVectorDatabase} />, }; }, }, { path: "/settings/agents", lazy: async () => { const { default: AdminAgents } = await import("@/pages/Admin/Agents"); return { element: <AdminRoute Component={AdminAgents} /> }; }, }, { path: "/settings/agents/builder", lazy: async () => { const { default: AgentBuilder } = await import( "@/pages/Admin/AgentBuilder" ); return { element: ( <AdminRoute Component={AgentBuilder} hideUserMenu={true} /> ), }; }, }, { path: "/settings/agents/builder/:flowId", lazy: async () => { const { default: AgentBuilder } = await import( "@/pages/Admin/AgentBuilder" ); return { element: ( <AdminRoute Component={AgentBuilder} hideUserMenu={true} /> ), }; }, }, { path: "/settings/event-logs", lazy: async () => { const { default: AdminLogs } = await import("@/pages/Admin/Logging"); return { element: <AdminRoute Component={AdminLogs} /> }; }, }, { path: "/settings/embed-chat-widgets", lazy: async () => { const { default: ChatEmbedWidgets } = await import( "@/pages/GeneralSettings/ChatEmbedWidgets" ); return { element: <AdminRoute Component={ChatEmbedWidgets} /> }; }, }, // Manager routes { path: "/settings/security", lazy: async () => { const { default: GeneralSecurity } = await import( "@/pages/GeneralSettings/Security" ); return { element: <ManagerRoute Component={GeneralSecurity} /> }; }, }, { path: "/settings/privacy", lazy: async () => { const { default: PrivacyAndData } = await import( "@/pages/GeneralSettings/PrivacyAndData" ); return { element: <AdminRoute Component={PrivacyAndData} /> }; }, }, { path: "/settings/interface", lazy: async () => { const { default: InterfaceSettings } = await import( "@/pages/GeneralSettings/Settings/Interface" ); return { element: <ManagerRoute Component={InterfaceSettings} /> }; }, }, { path: "/settings/branding", lazy: async () => { const { default: BrandingSettings } = await import( "@/pages/GeneralSettings/Settings/Branding" ); return { element: <ManagerRoute Component={BrandingSettings} /> }; }, }, { path: "/settings/default-system-prompt", lazy: async () => { const { default: DefaultSystemPrompt } = await import( "@/pages/Admin/DefaultSystemPrompt" ); return { element: <AdminRoute Component={DefaultSystemPrompt} /> }; }, }, { path: "/settings/chat", lazy: async () => { const { default: ChatSettings } = await import( "@/pages/GeneralSettings/Settings/Chat" ); return { element: <ManagerRoute Component={ChatSettings} /> }; }, }, { path: "/settings/beta-features", lazy: async () => { const { default: ExperimentalFeatures } = await import( "@/pages/Admin/ExperimentalFeatures" ); return { element: <AdminRoute Component={ExperimentalFeatures} /> }; }, }, { path: "/settings/api-keys", lazy: async () => { const { default: GeneralApiKeys } = await import( "@/pages/GeneralSettings/ApiKeys" ); return { element: <AdminRoute Component={GeneralApiKeys} /> }; }, }, { path: "/settings/system-prompt-variables", lazy: async () => { const { default: SystemPromptVariables } = await import( "@/pages/Admin/SystemPromptVariables" ); return { element: <AdminRoute Component={SystemPromptVariables} />, }; }, }, { path: "/settings/browser-extension", lazy: async () => { const { default: GeneralBrowserExtension } = await import( "@/pages/GeneralSettings/BrowserExtensionApiKey" ); return { element: <ManagerRoute Component={GeneralBrowserExtension} />, }; }, }, { path: "/settings/workspace-chats", lazy: async () => { const { default: GeneralChats } = await import( "@/pages/GeneralSettings/Chats" ); return { element: <ManagerRoute Component={GeneralChats} /> }; }, }, { path: "/settings/invites", lazy: async () => { const { default: AdminInvites } = await import( "@/pages/Admin/Invitations" ); return { element: <ManagerRoute Component={AdminInvites} /> }; }, }, { path: "/settings/users", lazy: async () => { const { default: AdminUsers } = await import("@/pages/Admin/Users"); return { element: <ManagerRoute Component={AdminUsers} /> }; }, }, { path: "/settings/workspaces", lazy: async () => { const { default: AdminWorkspaces } = await import( "@/pages/Admin/Workspaces" ); return { element: <ManagerRoute Component={AdminWorkspaces} /> }; }, }, // Onboarding Flow { path: "/onboarding", element: <OnboardingFlow />, }, { path: "/onboarding/:step", element: <OnboardingFlow />, }, // Experimental feature pages { path: "/settings/beta-features/live-document-sync/manage", lazy: async () => { const { default: LiveDocumentSyncManage } = await import( "@/pages/Admin/ExperimentalFeatures/Features/LiveSync/manage" ); return { element: <AdminRoute Component={LiveDocumentSyncManage} />, }; }, }, { path: "/settings/community-hub/trending", lazy: async () => { const { default: CommunityHubTrending } = await import( "@/pages/GeneralSettings/CommunityHub/Trending" ); return { element: <AdminRoute Component={CommunityHubTrending} /> }; }, }, { path: "/settings/community-hub/authentication", lazy: async () => { const { default: CommunityHubAuthentication } = await import( "@/pages/GeneralSettings/CommunityHub/Authentication" ); return { element: <AdminRoute Component={CommunityHubAuthentication} />, }; }, }, { path: "/settings/community-hub/import-item", lazy: async () => { const { default: CommunityHubImportItem } = await import( "@/pages/GeneralSettings/CommunityHub/ImportItem" ); return { element: <AdminRoute Component={CommunityHubImportItem} />, }; }, }, { path: "/settings/mobile-connections", lazy: async () => { const { default: MobileConnections } = await import( "@/pages/GeneralSettings/MobileConnections" ); return { element: <ManagerRoute Component={MobileConnections} /> }; }, }, // Catch-all route for 404s { path: "*", lazy: async () => { const { default: NotFound } = await import("@/pages/404"); return { element: <NotFound /> }; }, }, ], }, ]); ReactDOM.createRoot(document.getElementById("root")).render( <REACTWRAP> <RouterProvider router={router} /> </REACTWRAP> );
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/ThemeContext.jsx
frontend/src/ThemeContext.jsx
import React, { createContext, useContext } from "react"; import { useTheme } from "./hooks/useTheme"; const ThemeContext = createContext(); export function ThemeProvider({ children }) { const themeValue = useTheme(); return ( <ThemeContext.Provider value={themeValue}>{children}</ThemeContext.Provider> ); } export function useThemeContext() { return useContext(ThemeContext); }
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/PWAContext.jsx
frontend/src/PWAContext.jsx
import React, { createContext, useContext, useEffect, useMemo, useState, } from "react"; /** * Detects if the application is running as a standalone PWA * @returns {boolean} True if running as standalone PWA */ function isStandalonePWA() { if (typeof window === "undefined") return false; const matchesStandaloneDisplayMode = typeof window.matchMedia === "function" ? window.matchMedia("(display-mode: standalone)")?.matches : false; const isIOSStandalone = window.navigator?.standalone === true; // iOS Safari const androidReferrer = typeof document !== "undefined" && document?.referrer ? document.referrer.includes("android-app://") : false; return Boolean( matchesStandaloneDisplayMode || isIOSStandalone || androidReferrer ); } const PWAModeContext = createContext({ isPWA: false }); export function PWAModeProvider({ children }) { const [isPWA, setIsPWA] = useState(() => isStandalonePWA()); useEffect(() => { if (typeof window === "undefined") return undefined; const mediaQuery = typeof window.matchMedia === "function" ? window.matchMedia("(display-mode: standalone)") : null; const updateStatus = () => setIsPWA(isStandalonePWA()); updateStatus(); if (mediaQuery?.addEventListener) { mediaQuery.addEventListener("change", updateStatus); } else if (mediaQuery?.addListener) { mediaQuery.addListener(updateStatus); } window.addEventListener("appinstalled", updateStatus); window.addEventListener("visibilitychange", updateStatus); return () => { if (mediaQuery?.removeEventListener) { mediaQuery.removeEventListener("change", updateStatus); } else if (mediaQuery?.removeListener) { mediaQuery.removeListener(updateStatus); } window.removeEventListener("appinstalled", updateStatus); window.removeEventListener("visibilitychange", updateStatus); }; }, []); useEffect(() => { if (typeof document === "undefined") return undefined; document.body.classList.toggle("pwa", isPWA); document.documentElement?.setAttribute( "data-pwa", isPWA ? "true" : "false" ); return () => { document.body.classList.remove("pwa"); document.documentElement?.removeAttribute("data-pwa"); }; }, [isPWA]); const value = useMemo(() => ({ isPWA }), [isPWA]); return ( <PWAModeContext.Provider value={value}>{children}</PWAModeContext.Provider> ); } export function usePWAMode() { return useContext(PWAModeContext); }
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/PfpContext.jsx
frontend/src/PfpContext.jsx
import React, { createContext, useState, useEffect } from "react"; import useUser from "./hooks/useUser"; import System from "./models/system"; export const PfpContext = createContext(); export function PfpProvider({ children }) { const [pfp, setPfp] = useState(null); const { user } = useUser(); useEffect(() => { async function fetchPfp() { if (!user?.id) return; try { const pfpUrl = await System.fetchPfp(user.id); setPfp(pfpUrl); } catch (err) { setPfp(null); console.error("Failed to fetch pfp:", err); } } fetchPfp(); }, [user?.id]); return ( <PfpContext.Provider value={{ pfp, setPfp }}> {children} </PfpContext.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/App.jsx
frontend/src/App.jsx
import React, { Suspense } from "react"; import { Outlet, useLocation } from "react-router-dom"; import { I18nextProvider } from "react-i18next"; import { AuthProvider } from "@/AuthContext"; import { ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import i18n from "./i18n"; import { PfpProvider } from "./PfpContext"; import { LogoProvider } from "./LogoContext"; import { FullScreenLoader } from "./components/Preloader"; import { ThemeProvider } from "./ThemeContext"; import { PWAModeProvider } from "./PWAContext"; import KeyboardShortcutsHelp from "@/components/KeyboardShortcutsHelp"; import { ErrorBoundary } from "react-error-boundary"; import ErrorBoundaryFallback from "./components/ErrorBoundaryFallback"; export default function App() { const location = useLocation(); return ( <ErrorBoundary FallbackComponent={ErrorBoundaryFallback} onError={console.error} resetKeys={[location.pathname]} > <ThemeProvider> <PWAModeProvider> <Suspense fallback={<FullScreenLoader />}> <AuthProvider> <LogoProvider> <PfpProvider> <I18nextProvider i18n={i18n}> <Outlet /> <ToastContainer /> <KeyboardShortcutsHelp /> </I18nextProvider> </PfpProvider> </LogoProvider> </AuthProvider> </Suspense> </PWAModeProvider> </ThemeProvider> </ErrorBoundary> ); }
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/hooks/useCommunityHubAuth.js
frontend/src/hooks/useCommunityHubAuth.js
import { useState, useEffect } from "react"; import CommunityHub from "@/models/communityHub"; /** * Hook to check if the user is authenticated with the community hub by checking * the user defined connection key in the settings. * @returns {{isAuthenticated: boolean, loading: boolean}} An object containing the authentication status and loading state. */ export function useCommunityHubAuth() { const [isAuthenticated, setIsAuthenticated] = useState(false); const [loading, setLoading] = useState(true); useEffect(() => { async function checkCommunityHubAuth() { setLoading(true); try { const { connectionKey } = await CommunityHub.getSettings(); setIsAuthenticated(!!connectionKey); } catch (error) { console.error("Error checking hub auth:", error); setIsAuthenticated(false); } finally { setLoading(false); } } checkCommunityHubAuth(); }, []); return { isAuthenticated, loading }; }
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/hooks/usePrefersDarkMode.js
frontend/src/hooks/usePrefersDarkMode.js
export default function usePrefersDarkMode() { if (window?.matchMedia) { if (window?.matchMedia("(prefers-color-scheme: dark)")?.matches) { return true; } return false; } return false; }
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/hooks/useGetProvidersModels.js
frontend/src/hooks/useGetProvidersModels.js
import System from "@/models/system"; import { useEffect, useState } from "react"; // Providers which cannot use this feature for workspace<>model selection export const DISABLED_PROVIDERS = [ "azure", "textgenwebui", "generic-openai", "bedrock", ]; const PROVIDER_DEFAULT_MODELS = { openai: [], gemini: [], anthropic: [], azure: [], lmstudio: [], localai: [], ollama: [], togetherai: [], fireworksai: [], "nvidia-nim": [], groq: [], cohere: [ "command-r", "command-r-plus", "command", "command-light", "command-nightly", "command-light-nightly", ], textgenwebui: [], "generic-openai": [], bedrock: [], xai: ["grok-beta"], }; // For providers with large model lists (e.g. togetherAi) - we subgroup the options // by their creator organization (eg: Meta, Mistral, etc) // which makes selection easier to read. function groupModels(models) { return models.reduce((acc, model) => { acc[model.organization] = acc[model.organization] || []; acc[model.organization].push(model); return acc; }, {}); } const groupedProviders = [ "togetherai", "fireworksai", "openai", "novita", "openrouter", "ppio", ]; export default function useGetProviderModels(provider = null) { const [defaultModels, setDefaultModels] = useState([]); const [customModels, setCustomModels] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchProviderModels() { if (!provider) return; setLoading(true); const { models = [] } = await System.customModels(provider); if ( PROVIDER_DEFAULT_MODELS.hasOwnProperty(provider) && !groupedProviders.includes(provider) ) { setDefaultModels(PROVIDER_DEFAULT_MODELS[provider]); } else { setDefaultModels([]); } groupedProviders.includes(provider) ? setCustomModels(groupModels(models)) : setCustomModels(models); setLoading(false); } fetchProviderModels(); }, [provider]); return { defaultModels, customModels, loading }; }
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/hooks/useAppVersion.js
frontend/src/hooks/useAppVersion.js
import { useEffect, useState } from "react"; import System from "../models/system"; /** * Hook to fetch the app version. * @returns {Object} The app version. * @returns {string | null} version - The app version. * @returns {boolean} isLoading - Whether the app version is loading. */ export default function useAppVersion() { const [version, setVersion] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { System.fetchAppVersion() .then(setVersion) .finally(() => setIsLoading(false)); }, []); return { version, isLoading }; }
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/hooks/useModal.js
frontend/src/hooks/useModal.js
import { useState } from "react"; export function useModal() { const [isOpen, setIsOpen] = useState(false); const openModal = () => setIsOpen(true); const closeModal = () => setIsOpen(false); return { isOpen, openModal, closeModal }; }
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/hooks/useSimpleSSO.js
frontend/src/hooks/useSimpleSSO.js
import { useEffect, useState } from "react"; import System from "@/models/system"; /** * Checks if Simple SSO is enabled and if the user should be redirected to the SSO login page. * @returns {{loading: boolean, ssoConfig: {enabled: boolean, noLogin: boolean, noLoginRedirect: string | null}}} */ export default function useSimpleSSO() { const [loading, setLoading] = useState(true); const [ssoConfig, setSsoConfig] = useState({ enabled: false, noLogin: false, noLoginRedirect: null, }); useEffect(() => { async function checkSsoConfig() { try { const settings = await System.keys(); setSsoConfig({ enabled: settings?.SimpleSSOEnabled, noLogin: settings?.SimpleSSONoLogin, noLoginRedirect: settings?.SimpleSSONoLoginRedirect, }); } catch (e) { console.error(e); } finally { setLoading(false); } } checkSsoConfig(); }, []); return { loading, ssoConfig }; }
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/hooks/usePromptInputStorage.js
frontend/src/hooks/usePromptInputStorage.js
import { USER_PROMPT_INPUT_MAP } from "@/utils/constants"; import { useEffect, useMemo } from "react"; import { useParams } from "react-router-dom"; import debounce from "lodash.debounce"; import { safeJsonParse } from "@/utils/request"; /** * Synchronizes prompt input value with localStorage, scoped to the current thread. * * Persists unsent prompt text across page refreshes and navigation. Each thread/workspace maintains * its own draft state independently. Storage key is determined by thread slug (if in a thread) or * workspace slug (if in default chat). * * Storage format (stored under USER_PROMPT_INPUT_MAP key): * ```json * { * "thread-slug": "user's draft message...", * "workspace-slug": "another draft message..." * } * ``` * * @param {Object} props * @param {Function} props.onChange - Callback invoked when restoring saved value, receives `{ target: { value: string } }` * @param {string} props.promptInput - Current prompt input value to sync * @param {Function} props.setPromptInput - State setter function for prompt input * @returns {void} */ export default function usePromptInputStorage({ onChange, promptInput, setPromptInput, }) { const { threadSlug = null, slug: workspaceSlug } = useParams(); useEffect(() => { const serializedPromptInputMap = localStorage.getItem(USER_PROMPT_INPUT_MAP) || "{}"; const promptInputMap = safeJsonParse(serializedPromptInputMap, {}); const userPromptInputValue = promptInputMap[threadSlug ?? workspaceSlug]; if (userPromptInputValue) { setPromptInput(userPromptInputValue); // Notify parent component so message state is synchronized onChange({ target: { value: userPromptInputValue } }); } }, []); const debouncedWriteToStorage = useMemo( () => debounce((value, slug) => { const serializedPromptInputMap = localStorage.getItem(USER_PROMPT_INPUT_MAP) || "{}"; const promptInputMap = safeJsonParse(serializedPromptInputMap, {}); promptInputMap[slug] = value; localStorage.setItem( USER_PROMPT_INPUT_MAP, JSON.stringify(promptInputMap) ); }, 500), [] ); useEffect(() => { debouncedWriteToStorage(promptInput, threadSlug ?? workspaceSlug); return () => { debouncedWriteToStorage.cancel(); }; }, [promptInput, threadSlug, workspaceSlug, debouncedWriteToStorage]); }
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/hooks/usePfp.js
frontend/src/hooks/usePfp.js
import { useContext } from "react"; import { PfpContext } from "../PfpContext"; export default function usePfp() { const { pfp, setPfp } = useContext(PfpContext); return { pfp, setPfp }; }
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/hooks/useChatMessageAlignment.js
frontend/src/hooks/useChatMessageAlignment.js
import { useState, useEffect, useCallback } from "react"; const ALIGNMENT_STORAGE_KEY = "anythingllm-chat-message-alignment"; /** * Store the message alignment in localStorage as well as provide a function to get the alignment of a message via role. * @returns {{msgDirection: 'left'|'left_right', setMsgDirection: (direction: string) => void, getMessageAlignment: (role: string) => string}} - The message direction and the class name for the direction. */ export function useChatMessageAlignment() { const [msgDirection, setMsgDirection] = useState( () => localStorage.getItem(ALIGNMENT_STORAGE_KEY) ?? "left" ); useEffect(() => { if (msgDirection) localStorage.setItem(ALIGNMENT_STORAGE_KEY, msgDirection); }, [msgDirection]); const getMessageAlignment = useCallback( (role) => { const isLeftToRight = role === "user" && msgDirection === "left_right"; return isLeftToRight ? "flex-row-reverse" : ""; }, [msgDirection] ); return { msgDirection, setMsgDirection, getMessageAlignment, }; }
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/hooks/useTheme.js
frontend/src/hooks/useTheme.js
import { REFETCH_LOGO_EVENT } from "@/LogoContext"; import { useState, useEffect } from "react"; const availableThemes = { default: "Default", light: "Light", }; /** * Determines the current theme of the application * @returns {{theme: ('default' | 'light'), setTheme: function, availableThemes: object}} The current theme, a function to set the theme, and the available themes */ export function useTheme() { const [theme, _setTheme] = useState(() => { return localStorage.getItem("theme") || "default"; }); useEffect(() => { if (localStorage.getItem("theme") !== null) return; if (!window.matchMedia) return; if (window.matchMedia("(prefers-color-scheme: light)").matches) return _setTheme("light"); _setTheme("default"); }, []); useEffect(() => { document.documentElement.setAttribute("data-theme", theme); document.body.classList.toggle("light", theme === "light"); localStorage.setItem("theme", theme); window.dispatchEvent(new Event(REFETCH_LOGO_EVENT)); }, [theme]); // In development, attach keybind combinations to toggle theme useEffect(() => { if (!import.meta.env.DEV) return; function toggleOnKeybind(e) { if (e.metaKey && e.key === ".") { e.preventDefault(); setTheme((prev) => (prev === "light" ? "default" : "light")); } } document.addEventListener("keydown", toggleOnKeybind); return () => document.removeEventListener("keydown", toggleOnKeybind); }, []); /** * Sets the theme of the application and runs any * other necessary side effects * @param {string} newTheme The new theme to set */ function setTheme(newTheme) { _setTheme(newTheme); } return { theme, setTheme, availableThemes }; }
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/hooks/useQuery.js
frontend/src/hooks/useQuery.js
export default function useQuery() { return new URLSearchParams(window.location.search); }
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/hooks/useTextSize.js
frontend/src/hooks/useTextSize.js
import { useState, useEffect } from "react"; export default function useTextSize() { const [textSize, setTextSize] = useState("normal"); const [textSizeClass, setTextSizeClass] = useState("text-[14px]"); const getTextSizeClass = (size) => { switch (size) { case "small": return "text-[12px]"; case "large": return "text-[18px]"; default: return "text-[14px]"; } }; useEffect(() => { const storedTextSize = window.localStorage.getItem("anythingllm_text_size"); if (storedTextSize) { setTextSize(storedTextSize); setTextSizeClass(getTextSizeClass(storedTextSize)); } const handleTextSizeChange = (event) => { const size = event.detail; setTextSize(size); setTextSizeClass(getTextSizeClass(size)); }; window.addEventListener("textSizeChange", handleTextSizeChange); return () => { window.removeEventListener("textSizeChange", handleTextSizeChange); }; }, []); return { textSize, textSizeClass }; }
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/hooks/useLoginMode.js
frontend/src/hooks/useLoginMode.js
import { useEffect, useState } from "react"; import { AUTH_TOKEN, AUTH_USER } from "@/utils/constants"; export default function useLoginMode() { const [mode, setMode] = useState(null); useEffect(() => { if (!window) return; const user = !!window.localStorage.getItem(AUTH_USER); const token = !!window.localStorage.getItem(AUTH_TOKEN); let _mode = null; if (user && token) _mode = "multi"; if (!user && token) _mode = "single"; setMode(_mode); }, [window]); return mode; }
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/hooks/useLogo.js
frontend/src/hooks/useLogo.js
import { useContext } from "react"; import { LogoContext } from "../LogoContext"; export default function useLogo() { const { logo, setLogo, loginLogo, isCustomLogo } = useContext(LogoContext); return { logo, setLogo, loginLogo, isCustomLogo }; }
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/hooks/useProviderEndpointAutoDiscovery.js
frontend/src/hooks/useProviderEndpointAutoDiscovery.js
import { useEffect, useState } from "react"; import System from "@/models/system"; import showToast from "@/utils/toast"; export default function useProviderEndpointAutoDiscovery({ provider = null, initialBasePath = "", initialAuthToken = null, ENDPOINTS = [], }) { const [loading, setLoading] = useState(false); const [basePath, setBasePath] = useState(initialBasePath); const [basePathValue, setBasePathValue] = useState(initialBasePath); const [authToken, setAuthToken] = useState(initialAuthToken); const [authTokenValue, setAuthTokenValue] = useState(initialAuthToken); const [autoDetectAttempted, setAutoDetectAttempted] = useState(false); const [showAdvancedControls, setShowAdvancedControls] = useState(true); async function autoDetect(isInitialAttempt = false) { setLoading(true); setAutoDetectAttempted(true); const possibleEndpoints = []; ENDPOINTS.forEach((endpoint) => { possibleEndpoints.push( new Promise((resolve, reject) => { System.customModels(provider, authTokenValue, endpoint, 2_000) .then((results) => { if (!results?.models || results.models.length === 0) throw new Error("No models"); resolve({ endpoint, models: results.models }); }) .catch(() => { reject(`${provider} @ ${endpoint} did not resolve.`); }); }) ); }); const { endpoint, models } = await Promise.any(possibleEndpoints) .then((resolved) => resolved) .catch(() => { console.error("All endpoints failed to resolve."); return { endpoint: null, models: null }; }); if (models !== null) { setBasePath(endpoint); setBasePathValue(endpoint); setLoading(false); showToast("Provider endpoint discovered automatically.", "success", { clear: true, }); setShowAdvancedControls(false); return; } setLoading(false); setShowAdvancedControls(true); showToast( "Couldn't automatically discover the provider endpoint. Please enter it manually.", "info", { clear: true } ); } function handleAutoDetectClick(e) { e.preventDefault(); autoDetect(); } function handleBasePathChange(e) { const value = e.target.value; setBasePathValue(value); } function handleBasePathBlur() { setBasePath(basePathValue); } function handleAuthTokenChange(e) { const value = e.target.value; setAuthTokenValue(value); } function handleAuthTokenBlur() { setAuthToken(authTokenValue); } useEffect(() => { if (!initialBasePath && !autoDetectAttempted) autoDetect(true); }, [initialBasePath, initialAuthToken, autoDetectAttempted]); return { autoDetecting: loading, autoDetectAttempted, showAdvancedControls, setShowAdvancedControls, basePath: { value: basePath, set: setBasePathValue, onChange: handleBasePathChange, onBlur: handleBasePathBlur, }, basePathValue: { value: basePathValue, set: setBasePathValue, }, authToken: { value: authToken, set: setAuthTokenValue, onChange: handleAuthTokenChange, onBlur: handleAuthTokenBlur, }, authTokenValue: { value: authTokenValue, set: setAuthTokenValue, }, handleAutoDetectClick, runAutoDetect: autoDetect, }; }
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/hooks/useLanguageOptions.js
frontend/src/hooks/useLanguageOptions.js
import i18n from "@/i18n"; import { resources as languages } from "@/locales/resources"; export function useLanguageOptions() { const supportedLanguages = Object.keys(languages); const languageNames = new Intl.DisplayNames(supportedLanguages, { type: "language", }); const changeLanguage = (newLang = "en") => { if (!Object.keys(languages).includes(newLang)) return false; i18n.changeLanguage(newLang); }; return { currentLanguage: i18n.language || "en", supportedLanguages, getLanguageName: (lang = "en") => languageNames.of(lang), changeLanguage, }; }
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/hooks/useCopyText.js
frontend/src/hooks/useCopyText.js
import { useState } from "react"; export default function useCopyText(delay = 2500) { const [copied, setCopied] = useState(false); const copyText = async (content) => { if (!content) return; navigator?.clipboard?.writeText(content); setCopied(content); setTimeout(() => { setCopied(false); }, delay); }; return { copyText, copied }; }
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/hooks/useSlashCommandKeyboardNavigation.js
frontend/src/hooks/useSlashCommandKeyboardNavigation.js
import { useEffect, useRef } from "react"; /** * Handles keyboard navigation for the slash commands menu is presented in the UI. * @param {boolean} showing - Whether the slash commands menu is showing * @returns {void} */ export function useSlashCommandKeyboardNavigation({ showing }) { const focusedCommandRef = useRef(null); const availableCommands = useRef([]); useEffect(() => { const commands = document.querySelectorAll("[data-slash-command]"); availableCommands.current = Array.from(commands).map( (cmd) => cmd.dataset.slashCommand ); }, [showing]); useEffect(() => { if (!showing) return; document.addEventListener("keydown", handleKeyboardNavigation); return () => document.removeEventListener("keydown", handleKeyboardNavigation); }, [showing]); useEffect(() => { // Reset the focused command when the slash commands menu is closed or opened focusedCommandRef.current = null; }, [showing]); function handleKeyboardNavigation(event) { event.preventDefault(); if (!availableCommands.current.length) return; let currentIndex = availableCommands.current.indexOf( focusedCommandRef.current ); // If the enter key is pressed, click the focused command if it exists // This will also trigger the onClick event of the focused command // to cleanup everything on hide if (event.key === "Enter" && !!focusedCommandRef.current) { document .querySelector(`[data-slash-command="${focusedCommandRef.current}"]`) ?.click(); return; } // If the current index is -1, set it to the last command, otherwise inc/dec by 1 if (currentIndex === -1) currentIndex = availableCommands.current.length - 1; else currentIndex += event.key === "ArrowUp" ? -1 : 1; // Wrap around the array both ways if index is out of bounds if (currentIndex < 0) currentIndex = availableCommands.current.length - 1; else if (currentIndex >= availableCommands.current.length) currentIndex = 0; focusedCommandRef.current = availableCommands.current[currentIndex]; document .querySelector(`[data-slash-command="${focusedCommandRef.current}"]`) ?.focus(); } }
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/hooks/useUser.js
frontend/src/hooks/useUser.js
import { useContext } from "react"; import { AuthContext } from "@/AuthContext"; // interface IStore { // store: { // user: { // id: string; // username: string | null; // role: string; // }; // }; // } export default function useUser() { const context = useContext(AuthContext); return { ...context.store }; }
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/pages/404.jsx
frontend/src/pages/404.jsx
import { NavLink } from "react-router-dom"; import { House, MagnifyingGlass } from "@phosphor-icons/react"; export default function NotFound() { 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"> <MagnifyingGlass className="w-16 h-16 text-theme-text-secondary" /> <h1 className="text-xl md:text-2xl font-bold text-center"> 404 - Page Not Found </h1> <p className="text-theme-text-secondary text-center px-4"> The page you're looking for doesn't exist or has been moved. </p> <div className="flex flex-col md:flex-row gap-3 md:gap-4 mt-4 w-full md:w-auto"> <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" /> Go 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/pages/Main/index.jsx
frontend/src/pages/Main/index.jsx
import React from "react"; import PasswordModal, { usePasswordModal } from "@/components/Modals/Password"; import { FullScreenLoader } from "@/components/Preloader"; import Home from "./Home"; import DefaultChatContainer from "@/components/DefaultChat"; import { isMobile } from "react-device-detect"; import Sidebar, { SidebarMobileHeader } from "@/components/Sidebar"; import { userFromStorage } from "@/utils/request"; export default function Main() { const { loading, requiresAuth, mode } = usePasswordModal(); if (loading) return <FullScreenLoader />; if (requiresAuth !== false) return <>{requiresAuth !== null && <PasswordModal mode={mode} />}</>; const user = userFromStorage(); return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex"> {!isMobile ? <Sidebar /> : <SidebarMobileHeader />} {!!user && user?.role !== "admin" ? <DefaultChatContainer /> : <Home />} </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/pages/Main/Home/index.jsx
frontend/src/pages/Main/Home/index.jsx
import React from "react"; import QuickLinks from "./QuickLinks"; import ExploreFeatures from "./ExploreFeatures"; import Updates from "./Updates"; import Resources from "./Resources"; import Checklist from "./Checklist"; import { isMobile } from "react-device-detect"; export default function Home() { return ( <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] bg-theme-bg-container w-full h-full" > <div className="w-full h-full flex flex-col items-center overflow-y-auto no-scroll"> <div className="w-full max-w-[1200px] flex flex-col gap-y-[24px] p-4 pt-16 md:p-12 md:pt-11"> <Checklist /> <QuickLinks /> <ExploreFeatures /> <Updates /> <Resources /> </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/pages/Main/Home/QuickLinks/index.jsx
frontend/src/pages/Main/Home/QuickLinks/index.jsx
import { ChatCenteredDots, FileArrowDown, Plus } from "@phosphor-icons/react"; import { useNavigate } from "react-router-dom"; import Workspace from "@/models/workspace"; import paths from "@/utils/paths"; import { useManageWorkspaceModal } from "@/components/Modals/ManageWorkspace"; import ManageWorkspace from "@/components/Modals/ManageWorkspace"; import { useState } from "react"; import { useNewWorkspaceModal } from "@/components/Modals/NewWorkspace"; import NewWorkspaceModal from "@/components/Modals/NewWorkspace"; import showToast from "@/utils/toast"; import { useTranslation } from "react-i18next"; export default function QuickLinks() { const { t } = useTranslation(); const navigate = useNavigate(); const { showModal } = useManageWorkspaceModal(); const [selectedWorkspace, setSelectedWorkspace] = useState(null); const { showing: showingNewWsModal, showModal: showNewWsModal, hideModal: hideNewWsModal, } = useNewWorkspaceModal(); const sendChat = async () => { const workspaces = await Workspace.all(); if (workspaces.length > 0) { const firstWorkspace = workspaces[0]; navigate(paths.workspace.chat(firstWorkspace.slug)); } else { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); } }; const embedDocument = async () => { const workspaces = await Workspace.all(); if (workspaces.length > 0) { const firstWorkspace = workspaces[0]; setSelectedWorkspace(firstWorkspace); showModal(); } else { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); } }; const createWorkspace = () => { showNewWsModal(); }; return ( <div> <h1 className="text-theme-home-text uppercase text-sm font-semibold mb-4"> {t("main-page.quickLinks.title")} </h1> <div className="w-full grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"> <button onClick={sendChat} className="h-[45px] text-sm font-semibold bg-theme-home-button-secondary rounded-lg text-theme-home-button-secondary-text flex items-center justify-center gap-x-2.5 transition-all duration-200 hover:bg-theme-home-button-secondary-hover hover:text-theme-home-button-secondary-hover-text" > <ChatCenteredDots size={16} /> {t("main-page.quickLinks.sendChat")} </button> <button onClick={embedDocument} className="h-[45px] text-sm font-semibold bg-theme-home-button-secondary rounded-lg text-theme-home-button-secondary-text flex items-center justify-center gap-x-2.5 transition-all duration-200 hover:bg-theme-home-button-secondary-hover hover:text-theme-home-button-secondary-hover-text" > <FileArrowDown size={16} /> {t("main-page.quickLinks.embedDocument")} </button> <button onClick={createWorkspace} className="h-[45px] text-sm font-semibold bg-theme-home-button-secondary rounded-lg text-theme-home-button-secondary-text flex items-center justify-center gap-x-2.5 transition-all duration-200 hover:bg-theme-home-button-secondary-hover hover:text-theme-home-button-secondary-hover-text" > <Plus size={16} /> {t("main-page.quickLinks.createWorkspace")} </button> </div> {selectedWorkspace && ( <ManageWorkspace providedSlug={selectedWorkspace.slug} hideModal={() => { setSelectedWorkspace(null); }} /> )} {showingNewWsModal && <NewWorkspaceModal hideModal={hideNewWsModal} />} </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/pages/Main/Home/ExploreFeatures/index.jsx
frontend/src/pages/Main/Home/ExploreFeatures/index.jsx
import { useNavigate } from "react-router-dom"; import paths from "@/utils/paths"; import Workspace from "@/models/workspace"; import { useTranslation } from "react-i18next"; export default function ExploreFeatures() { const { t } = useTranslation(); const navigate = useNavigate(); const chatWithAgent = async () => { const workspaces = await Workspace.all(); if (workspaces.length > 0) { const firstWorkspace = workspaces[0]; navigate( paths.workspace.chat(firstWorkspace.slug, { search: { action: "set-agent-chat" }, }) ); } }; const buildAgentFlow = () => navigate(paths.agents.builder()); const setSlashCommand = async () => { const workspaces = await Workspace.all(); if (workspaces.length > 0) { const firstWorkspace = workspaces[0]; navigate( paths.workspace.chat(firstWorkspace.slug, { search: { action: "open-new-slash-command-modal" }, }) ); } }; const exploreSlashCommands = () => { window.open(paths.communityHub.viewMoreOfType("slash-commands"), "_blank"); }; const setSystemPrompt = async () => { const workspaces = await Workspace.all(); if (workspaces.length > 0) { const firstWorkspace = workspaces[0]; navigate( paths.workspace.settings.chatSettings(firstWorkspace.slug, { search: { action: "focus-system-prompt" }, }) ); } }; const managePromptVariables = () => { navigate(paths.settings.systemPromptVariables()); }; return ( <div> <h1 className="text-theme-home-text uppercase text-sm font-semibold mb-4"> {t("main-page.exploreMore.title")} </h1> <div className="w-full grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"> <FeatureCard title={t("main-page.exploreMore.features.customAgents.title")} description={t( "main-page.exploreMore.features.customAgents.description" )} primaryAction={t( "main-page.exploreMore.features.customAgents.primaryAction" )} secondaryAction={t( "main-page.exploreMore.features.customAgents.secondaryAction" )} onPrimaryAction={chatWithAgent} onSecondaryAction={buildAgentFlow} isNew={true} /> <FeatureCard title={t("main-page.exploreMore.features.slashCommands.title")} description={t( "main-page.exploreMore.features.slashCommands.description" )} primaryAction={t( "main-page.exploreMore.features.slashCommands.primaryAction" )} secondaryAction={t( "main-page.exploreMore.features.slashCommands.secondaryAction" )} onPrimaryAction={setSlashCommand} onSecondaryAction={exploreSlashCommands} isNew={false} /> <FeatureCard title={t("main-page.exploreMore.features.systemPrompts.title")} description={t( "main-page.exploreMore.features.systemPrompts.description" )} primaryAction={t( "main-page.exploreMore.features.systemPrompts.primaryAction" )} secondaryAction={t( "main-page.exploreMore.features.systemPrompts.secondaryAction" )} onPrimaryAction={setSystemPrompt} onSecondaryAction={managePromptVariables} isNew={true} /> </div> </div> ); } function FeatureCard({ title, description, primaryAction, secondaryAction, onPrimaryAction, onSecondaryAction, isNew, }) { return ( <div className="border border-theme-home-border rounded-lg py-4 px-5 flex flex-col justify-between gap-y-4"> <div className="flex flex-col gap-y-2"> <h2 className="text-theme-home-text font-semibold flex items-center gap-x-2"> {title} </h2> <p className="text-theme-home-text-secondary text-sm">{description}</p> </div> <div className="flex flex-col gap-y-[10px]"> <button onClick={onPrimaryAction} className="w-full h-[36px] border border-white/20 light:border-theme-home-button-secondary-border light:hover:border-theme-home-button-secondary-border-hover text-white rounded-lg text-theme-home-button-primary-text text-sm font-medium flex items-center justify-center gap-x-2.5 transition-all duration-200 light:hover:bg-transparent hover:bg-theme-home-button-secondary-hover hover:text-theme-home-button-secondary-hover-text" > {primaryAction} </button> {secondaryAction && ( <div className="relative w-full"> {isNew && ( <div className="absolute left-3 top-1/2 -translate-y-1/2 px-2 font-semibold rounded-md text-[10px] text-theme-checklist-item-text bg-theme-checklist-item-bg light:bg-white/60"> New </div> )} <button onClick={onSecondaryAction} className="w-full h-[36px] bg-theme-home-button-secondary rounded-lg text-theme-home-button-secondary-text text-sm font-medium flex items-center justify-center transition-all duration-200 hover:bg-theme-home-button-secondary-hover hover:text-theme-home-button-secondary-hover-text" > {secondaryAction} </button> </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/pages/Main/Home/Updates/index.jsx
frontend/src/pages/Main/Home/Updates/index.jsx
import { useEffect, useState } from "react"; import { safeJsonParse } from "@/utils/request"; import { Link } from "react-router-dom"; import PlaceholderOne from "@/media/announcements/placeholder-1.png"; import PlaceholderTwo from "@/media/announcements/placeholder-2.png"; import PlaceholderThree from "@/media/announcements/placeholder-3.png"; import { useTranslation } from "react-i18next"; /** * @typedef {Object} NewsItem * @property {string} title * @property {string|null} thumbnail_url * @property {string} short_description * @property {string|null} goto * @property {string|null} source * @property {string|null} date */ const NEWS_CACHE_CONFIG = { articles: "https://cdn.anythingllm.com/support/announcements/list.txt", announcementsDir: "https://cdn.anythingllm.com/support/announcements", cacheKey: "anythingllm_announcements", ttl: 7 * 24 * 60 * 60 * 1000, // 1 week }; const PLACEHOLDERS = [PlaceholderOne, PlaceholderTwo, PlaceholderThree]; function randomPlaceholder() { return PLACEHOLDERS[Math.floor(Math.random() * PLACEHOLDERS.length)]; } export default function Updates() { const { t } = useTranslation(); const { isLoading, news } = useNewsItems(); if (isLoading || !news?.length) return null; return ( <div> <h1 className="text-theme-home-text uppercase text-sm font-semibold mb-4"> {t("main-page.announcements.title")} </h1> <div className="w-full grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"> {news.map((item, index) => ( <AnnouncementCard key={index} thumbnail_url={item.thumbnail_url} title={item.title} subtitle={item.short_description} source={item.source} date={item.date} goto={item.goto} /> ))} </div> </div> ); } function isExternal(goto) { if (!goto) return false; const url = new URL(goto); return url.hostname !== window.location.hostname; } function AnnouncementCard({ thumbnail_url = null, title = "", subtitle = "", author = "AnythingLLM", date = null, goto = "#", }) { const placeHolderImage = randomPlaceholder(); const isExternalLink = isExternal(goto); return ( <Link to={goto} target={isExternalLink ? "_blank" : "_self"} rel="noopener noreferrer" className="block" > <div className="bg-theme-home-update-card-bg rounded-xl p-4 flex gap-x-4 hover:bg-theme-home-update-card-hover transition-colors"> <img src={thumbnail_url ?? placeHolderImage} alt={title} loading="lazy" onError={(e) => (e.target.src = placeHolderImage)} className="w-[80px] h-[80px] rounded-lg flex-shrink-0 object-cover" /> <div className="flex flex-col gap-y-1"> <h3 className="text-theme-home-text font-medium text-sm">{title}</h3> <p className="text-theme-home-text-secondary text-xs line-clamp-2"> {subtitle} </p> <div className="flex items-center gap-x-4 text-xs text-theme-home-text-secondary"> <span className="text-theme-home-update-source">{author}</span> <span>{date ?? "Recently"}</span> </div> </div> </div> </Link> ); } /** * Get cached news from localStorage if it exists and is valid by ttl timestamp * @returns {null|NewsItem[]} - Array of news items */ function getCachedNews() { try { const cachedNews = localStorage.getItem(NEWS_CACHE_CONFIG.cacheKey); if (!cachedNews) return null; /** @type {{news: NewsItem[]|null, timestamp: number|null}|null} */ const parsedNews = safeJsonParse(cachedNews, null); if (!parsedNews || !parsedNews?.news?.length || !parsedNews.timestamp) return null; const now = new Date(); const cacheExpiration = new Date( parsedNews.timestamp + NEWS_CACHE_CONFIG.ttl ); if (now < cacheExpiration) return parsedNews.news; return null; } catch (error) { console.error("Error fetching cached news:", error); return null; } } /** * Fetch news from remote source and cache it in localStorage * @returns {Promise<NewsItem[]|null>} - Array of news items */ async function fetchRemoteNews() { try { const latestArticleDateRef = await fetch(NEWS_CACHE_CONFIG.articles) .then((res) => { if (!res.ok) throw new Error( `${res.status} - Failed to fetch remote news from ${NEWS_CACHE_CONFIG.articles}` ); return res.text(); }) .then((text) => text?.split("\n")?.shift()?.trim()) .catch((err) => { console.error(err.message); return null; }); if (!latestArticleDateRef) return null; const dataURL = `${NEWS_CACHE_CONFIG.announcementsDir}/${latestArticleDateRef}${latestArticleDateRef.endsWith(".json") ? "" : ".json"}`; /** @type {NewsItem[]|null} */ const announcementData = await fetch(dataURL) .then((res) => { if (!res.ok) throw new Error( `${res.status} - Failed to fetch remote news from ${dataURL}` ); return res.json(); }) .catch((err) => { console.error(err.message); return []; }); if (!announcementData?.length) return null; localStorage.setItem( NEWS_CACHE_CONFIG.cacheKey, JSON.stringify({ news: announcementData, timestamp: Date.now(), }) ); return announcementData; } catch (error) { console.error("Error fetching remote news:", error); return null; } } /** * @returns {{news: NewsItem[], isLoading: boolean}} */ function useNewsItems() { const [news, setNews] = useState([]); const [isLoading, setIsLoading] = useState(true); useEffect(() => { async function fetchAnnouncements() { try { const cachedNews = getCachedNews(); if (cachedNews) return setNews(cachedNews); const remoteNews = await fetchRemoteNews(); if (remoteNews) return setNews(remoteNews); } catch (error) { console.error("Error fetching cached news:", error); } finally { setIsLoading(false); } } fetchAnnouncements(); }, []); return { news, isLoading }; }
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/pages/Main/Home/Resources/index.jsx
frontend/src/pages/Main/Home/Resources/index.jsx
import paths from "@/utils/paths"; import { ArrowCircleUpRight } from "@phosphor-icons/react"; import { useTranslation } from "react-i18next"; import { KEYBOARD_SHORTCUTS_HELP_EVENT } from "@/utils/keyboardShortcuts"; export default function Resources() { const { t } = useTranslation(); const showKeyboardShortcuts = () => { window.dispatchEvent( new CustomEvent(KEYBOARD_SHORTCUTS_HELP_EVENT, { detail: { show: true } }) ); }; return ( <div> <h1 className="text-theme-home-text uppercase text-sm font-semibold mb-4"> {t("main-page.resources.title")} </h1> <div className="flex gap-x-6"> <a target="_blank" rel="noopener noreferrer " href={paths.docs()} className="text-theme-home-text text-sm flex items-center gap-x-2 hover:opacity-70" > {t("main-page.resources.links.docs")} <ArrowCircleUpRight weight="fill" size={16} /> </a> <a href={paths.github()} target="_blank" rel="noopener noreferrer" className="text-theme-home-text text-sm flex items-center gap-x-2 hover:opacity-70" > {t("main-page.resources.links.star")} <ArrowCircleUpRight weight="fill" size={16} /> </a> <button onClick={showKeyboardShortcuts} className="text-theme-home-text text-sm flex items-center gap-x-2 hover:opacity-70" > {t("main-page.resources.keyboardShortcuts")} <ArrowCircleUpRight weight="fill" size={16} /> </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/pages/Main/Home/Checklist/index.jsx
frontend/src/pages/Main/Home/Checklist/index.jsx
import React, { useState, useEffect, useRef, useCallback } from "react"; import ManageWorkspace, { useManageWorkspaceModal, } from "@/components/Modals/ManageWorkspace"; import NewWorkspaceModal, { useNewWorkspaceModal, } from "@/components/Modals/NewWorkspace"; import Workspace from "@/models/workspace"; import { useNavigate } from "react-router-dom"; import { ChecklistItem } from "./ChecklistItem"; import showToast from "@/utils/toast"; import { CHECKLIST_HIDDEN, CHECKLIST_STORAGE_KEY, CHECKLIST_ITEMS, CHECKLIST_UPDATED_EVENT, } from "./constants"; import ConfettiExplosion from "react-confetti-explosion"; import { safeJsonParse } from "@/utils/request"; import { useTranslation } from "react-i18next"; const MemoizedChecklistItem = React.memo(ChecklistItem); export default function Checklist() { const { t } = useTranslation(); const [loading, setLoading] = useState(true); const [isHidden, setIsHidden] = useState(false); const [completedCount, setCompletedCount] = useState(0); const [isCompleted, setIsCompleted] = useState(false); const [selectedWorkspace, setSelectedWorkspace] = useState(null); const [workspaces, setWorkspaces] = useState([]); const navigate = useNavigate(); const containerRef = useRef(null); const { showModal: showNewWsModal, hideModal: hideNewWsModal, showing: showingNewWsModal, } = useNewWorkspaceModal(); const { showModal: showManageWsModal, hideModal: hideManageWsModal } = useManageWorkspaceModal(); const createItemHandler = useCallback( (item) => { return () => item.handler({ workspaces, navigate, setSelectedWorkspace, showManageWsModal, showToast, showNewWsModal, }); }, [ workspaces, navigate, setSelectedWorkspace, showManageWsModal, showToast, showNewWsModal, ] ); useEffect(() => { async function initialize() { try { const hidden = window.localStorage.getItem(CHECKLIST_HIDDEN); setIsHidden(!!hidden); // If the checklist is hidden, don't bother evaluating it. if (hidden) return; // If the checklist is completed then dont continue and just show the completed state. const checklist = window.localStorage.getItem(CHECKLIST_STORAGE_KEY); const existingChecklist = checklist ? safeJsonParse(checklist, {}) : {}; const isCompleted = Object.keys(existingChecklist).length === CHECKLIST_ITEMS().length; setIsCompleted(isCompleted); if (isCompleted) return; // Otherwise, we can fetch workspaces for our checklist tasks as well // as determine if the create_workspace task is completed for pre-checking. const workspaces = await Workspace.all(); setWorkspaces(workspaces); if (workspaces.length > 0) { existingChecklist["create_workspace"] = true; window.localStorage.setItem( CHECKLIST_STORAGE_KEY, JSON.stringify(existingChecklist) ); } evaluateChecklist(); // Evaluate checklist on mount. window.addEventListener(CHECKLIST_UPDATED_EVENT, evaluateChecklist); } catch (error) { console.error(error); } finally { setLoading(false); } } initialize(); return () => { window.removeEventListener(CHECKLIST_UPDATED_EVENT, evaluateChecklist); }; }, []); useEffect(() => { const fetchWorkspaces = async () => { const workspaces = await Workspace.all(); setWorkspaces(workspaces); }; fetchWorkspaces(); }, []); useEffect(() => { if (isCompleted) { setTimeout(() => { handleClose(); }, 5_000); } }, [isCompleted]); const evaluateChecklist = useCallback(() => { try { const checklist = window.localStorage.getItem(CHECKLIST_STORAGE_KEY); if (!checklist) return; const completedItems = safeJsonParse(checklist, {}); setCompletedCount(Object.keys(completedItems).length); setIsCompleted( Object.keys(completedItems).length === CHECKLIST_ITEMS().length ); } catch (error) { console.error(error); } }, []); const handleClose = useCallback(() => { window.localStorage.setItem(CHECKLIST_HIDDEN, "true"); if (containerRef?.current) containerRef.current.style.height = "0px"; }, []); if (isHidden || loading) return null; return ( <div ref={containerRef} className="transition-height duration-300 h-[100%] overflow-y-hidden relative" > <div className={`${isCompleted ? "checklist-completed" : "hidden"} absolute top-0 left-0 w-full h-full p-2 z-10 transition-all duration-300`} > {isCompleted && ( <div className="flex w-full items-center justify-center"> <ConfettiExplosion force={0.25} duration={3000} /> </div> )} <div style={{}} className="bg-[rgba(54,70,61,0.5)] light:bg-[rgba(216,243,234,0.5)] w-full h-full flex items-center justify-center bg-theme-checklist-item-completed-bg/50 rounded-lg" > <p className="text-theme-checklist-item-completed-text text-lg font-bold"> {t("main-page.checklist.completed")} </p> </div> </div> <div className={`rounded-lg p-4 lg:p-6 bg-theme-home-bg-card relative ${isCompleted ? "blur-sm" : ""}`} > <div className="flex justify-between items-center mb-4"> <div className="flex items-center gap-x-3"> <h1 className="text-theme-home-text uppercase text-sm font-semibold"> {t("main-page.checklist.title")} </h1> {CHECKLIST_ITEMS().length - completedCount > 0 && ( <p className="text-theme-home-text-secondary text-xs"> {CHECKLIST_ITEMS().length - completedCount}{" "} {t("main-page.checklist.tasksLeft")} </p> )} </div> <div className="flex items-center gap-x-2"> <button onClick={handleClose} className="text-theme-home-text-secondary bg-theme-home-bg-button px-3 py-1 rounded-xl hover:bg-white/10 transition-colors text-xs light:bg-black-100" > {t("main-page.checklist.dismiss")} </button> </div> </div> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"> {CHECKLIST_ITEMS().map((item) => ( <MemoizedChecklistItem key={item.id} id={item.id} title={item.title} action={item.action} icon={item.icon} completed={item.completed} onAction={createItemHandler(item)} /> ))} </div> </div> {showingNewWsModal && <NewWorkspaceModal hideModal={hideNewWsModal} />} {selectedWorkspace && ( <ManageWorkspace providedSlug={selectedWorkspace.slug} hideModal={() => { setSelectedWorkspace(null); hideManageWsModal(); }} /> )} </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/pages/Main/Home/Checklist/constants.js
frontend/src/pages/Main/Home/Checklist/constants.js
import { SquaresFour, ChatDots, Files, ChatCenteredText, UsersThree, } from "@phosphor-icons/react"; import SlashCommandIcon from "./ChecklistItem/icons/SlashCommand"; import paths from "@/utils/paths"; import { t } from "i18next"; const noop = () => {}; export const CHECKLIST_UPDATED_EVENT = "anythingllm_checklist_updated"; export const CHECKLIST_STORAGE_KEY = "anythingllm_checklist_completed"; export const CHECKLIST_HIDDEN = "anythingllm_checklist_dismissed"; /** * @typedef {Object} ChecklistItemHandlerParams * @property {Object[]} workspaces - Array of workspaces * @property {Function} navigate - Function to navigate to a path * @property {Function} setSelectedWorkspace - Function to set the selected workspace * @property {Function} showManageWsModal - Function to show the manage workspace modal * @property {Function} showToast - Function to show a toast * @property {Function} showNewWsModal - Function to show the new workspace modal */ /** * @typedef {Object} ChecklistItem * @property {string} id * @property {string} title * @property {string} description * @property {string} action * @property {(params: ChecklistItemHandlerParams) => boolean} handler * @property {string} icon * @property {boolean} completed */ /** * Function to generate the checklist items * @returns {ChecklistItem[]} */ export const CHECKLIST_ITEMS = () => [ { id: "create_workspace", title: t("main-page.checklist.tasks.create_workspace.title"), description: t("main-page.checklist.tasks.create_workspace.description"), action: t("main-page.checklist.tasks.create_workspace.action"), handler: ({ showNewWsModal = noop }) => { showNewWsModal(); return true; }, icon: SquaresFour, }, { id: "send_chat", title: t("main-page.checklist.tasks.send_chat.title"), description: t("main-page.checklist.tasks.send_chat.description"), action: t("main-page.checklist.tasks.send_chat.action"), handler: ({ workspaces = [], navigate = noop, showToast = noop, showNewWsModal = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } navigate(paths.workspace.chat(workspaces[0].slug)); return true; }, icon: ChatDots, }, { id: "embed_document", title: t("main-page.checklist.tasks.embed_document.title"), description: t("main-page.checklist.tasks.embed_document.description"), action: t("main-page.checklist.tasks.embed_document.action"), handler: ({ workspaces = [], setSelectedWorkspace = noop, showManageWsModal = noop, showToast = noop, showNewWsModal = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } setSelectedWorkspace(workspaces[0]); showManageWsModal(); return true; }, icon: Files, }, { id: "setup_system_prompt", title: t("main-page.checklist.tasks.setup_system_prompt.title"), description: t("main-page.checklist.tasks.setup_system_prompt.description"), action: t("main-page.checklist.tasks.setup_system_prompt.action"), handler: ({ workspaces = [], navigate = noop, showNewWsModal = noop, showToast = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } navigate( paths.workspace.settings.chatSettings(workspaces[0].slug, { search: { action: "focus-system-prompt" }, }) ); return true; }, icon: ChatCenteredText, }, { id: "define_slash_command", title: t("main-page.checklist.tasks.define_slash_command.title"), description: t( "main-page.checklist.tasks.define_slash_command.description" ), action: t("main-page.checklist.tasks.define_slash_command.action"), handler: ({ workspaces = [], navigate = noop, showNewWsModal = noop, showToast = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true }); showNewWsModal(); return false; } navigate( paths.workspace.chat(workspaces[0].slug, { search: { action: "open-new-slash-command-modal" }, }) ); return true; }, icon: SlashCommandIcon, }, { id: "visit_community", title: t("main-page.checklist.tasks.visit_community.title"), description: t("main-page.checklist.tasks.visit_community.description"), action: t("main-page.checklist.tasks.visit_community.action"), handler: () => { window.open(paths.communityHub.website(), "_blank"); return true; }, icon: UsersThree, }, ];
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/pages/Main/Home/Checklist/ChecklistItem/index.jsx
frontend/src/pages/Main/Home/Checklist/ChecklistItem/index.jsx
import { useState } from "react"; import { CHECKLIST_STORAGE_KEY, CHECKLIST_UPDATED_EVENT } from "../constants"; import { Check } from "@phosphor-icons/react"; import { safeJsonParse } from "@/utils/request"; export function ChecklistItem({ id, title, action, onAction, icon: Icon }) { const [isCompleted, setIsCompleted] = useState(() => { const stored = window.localStorage.getItem(CHECKLIST_STORAGE_KEY); if (!stored) return false; const completedItems = safeJsonParse(stored, {}); return completedItems[id] || false; }); const handleClick = async (e) => { e.preventDefault(); if (!isCompleted) { const shouldComplete = await onAction(); if (shouldComplete) { const stored = window.localStorage.getItem(CHECKLIST_STORAGE_KEY); const completedItems = safeJsonParse(stored, {}); completedItems[id] = true; window.localStorage.setItem( CHECKLIST_STORAGE_KEY, JSON.stringify(completedItems) ); setIsCompleted(true); window.dispatchEvent(new CustomEvent(CHECKLIST_UPDATED_EVENT)); } } else { await onAction(); } }; return ( <div className={`flex items-center gap-x-4 transition-colors cursor-pointer rounded-lg p-3 group hover:bg-theme-checklist-item-bg-hover ${ isCompleted ? "bg-theme-checklist-item-completed-bg" : "bg-theme-checklist-item-bg" }`} onClick={handleClick} > {Icon && ( <div className="flex-shrink-0"> <Icon size={18} className={ isCompleted ? "text-theme-checklist-item-completed-text" : "text-theme-checklist-item-text" } /> </div> )} <div className="flex-1"> <h3 className={`text-sm font-medium transition-colors duration-200 ${ isCompleted ? "text-theme-checklist-item-completed-text line-through" : "text-theme-checklist-item-text" }`} > {title} </h3> </div> {isCompleted ? ( <div className="w-5 h-5 rounded-full bg-theme-checklist-checkbox-fill flex items-center justify-center"> <Check size={14} weight="bold" className="text-theme-checklist-checkbox-text" /> </div> ) : ( <button className="w-[64px] h-[24px] rounded-md bg-white/10 light:bg-white/70 text-theme-checklist-item-text font-semibold text-xs transition-all duration-200 flex items-center justify-center hover:bg-white/20 light:hover:bg-white/60"> {action} </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/pages/Main/Home/Checklist/ChecklistItem/icons/SlashCommand.jsx
frontend/src/pages/Main/Home/Checklist/ChecklistItem/icons/SlashCommand.jsx
import React from "react"; export default function SlashCommandIcon({ className }) { return ( <svg width={16} height={16} viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg" className={className} > <rect x="0.5" y="1" width="13" height="13" rx="3.5" stroke="currentColor" /> <path d="M4.18103 10.7974L9.8189 4.20508" stroke="currentColor" 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/pages/Invite/index.jsx
frontend/src/pages/Invite/index.jsx
import React, { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { FullScreenLoader } from "@/components/Preloader"; import Invite from "@/models/invite"; import NewUserModal from "./NewUserModal"; import ModalWrapper from "@/components/ModalWrapper"; export default function InvitePage() { const { code } = useParams(); const [result, setResult] = useState({ status: "loading", message: null, }); useEffect(() => { async function checkInvite() { if (!code) { setResult({ status: "invalid", message: "No invite code provided.", }); return; } const { invite, error } = await Invite.checkInvite(code); setResult({ status: invite ? "valid" : "invalid", message: error, }); } checkInvite(); }, []); if (result.status === "loading") { return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex"> <FullScreenLoader /> </div> ); } if (result.status === "invalid") { return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex items-center justify-center"> <p className="text-red-400 text-lg">{result.message}</p> </div> ); } return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex items-center justify-center"> <ModalWrapper isOpen={true}> <NewUserModal /> </ModalWrapper> </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/pages/Invite/NewUserModal/index.jsx
frontend/src/pages/Invite/NewUserModal/index.jsx
import React, { useState } from "react"; import Invite from "@/models/invite"; import paths from "@/utils/paths"; import { useParams } from "react-router-dom"; import { AUTH_TOKEN, AUTH_USER } from "@/utils/constants"; import System from "@/models/system"; export default function NewUserModal() { const { code } = useParams(); const [error, setError] = useState(null); const handleCreate = async (e) => { setError(null); e.preventDefault(); const data = {}; const form = new FormData(e.target); for (var [key, value] of form.entries()) data[key] = value; const { success, error } = await Invite.acceptInvite(code, data); if (success) { const { valid, user, token, message } = await System.requestToken(data); if (valid && !!token && !!user) { window.localStorage.setItem(AUTH_USER, JSON.stringify(user)); window.localStorage.setItem(AUTH_TOKEN, token); window.location = paths.home(); } else { setError(message); } return; } setError(error); }; return ( <div className="relative w-full max-w-2xl max-h-full"> <div className="relative w-full max-w-2xl bg-theme-bg-secondary rounded-lg shadow border-2 border-theme-modal-border"> <div className="flex items-start justify-between p-4 border-b rounded-t border-theme-modal-border"> <h3 className="text-xl font-semibold text-theme-text-primary"> Create a new account </h3> </div> <form onSubmit={handleCreate}> <div className="p-6 space-y-6 flex h-full w-full"> <div className="w-full flex flex-col gap-y-4"> <div> <label htmlFor="username" className="block mb-2 text-sm font-medium text-theme-text-primary" > Username </label> <input name="username" type="text" className="border-none bg-theme-settings-input-bg text-theme-text-primary 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="My username" minLength={2} required={true} autoComplete="off" /> </div> <div> <label htmlFor="password" className="block mb-2 text-sm font-medium text-theme-text-primary" > Password </label> <input name="password" type="password" className="border-none bg-theme-settings-input-bg text-theme-text-primary 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="Your password" required={true} minLength={8} autoComplete="off" /> </div> {error && <p className="text-red-400 text-sm">Error: {error}</p>} <p className="text-theme-text-secondary text-xs md:text-sm"> After creating your account you will be able to login with these credentials and start using workspaces. </p> </div> </div> <div className="flex w-full justify-between items-center p-6 space-x-2 border-t rounded-b border-theme-modal-border"> <button type="submit" className="w-full transition-all duration-300 border border-theme-text-primary px-4 py-2 rounded-lg text-theme-text-primary text-sm items-center flex gap-x-2 hover:bg-theme-text-primary hover:text-theme-bg-primary focus:ring-gray-800 text-center justify-center" > Accept Invitation </button> </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/pages/Admin/Workspaces/index.jsx
frontend/src/pages/Admin/Workspaces/index.jsx
import { useEffect, useState } from "react"; import Sidebar from "@/components/SettingsSidebar"; import { isMobile } from "react-device-detect"; import * as Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; import { BookOpen } from "@phosphor-icons/react"; import Admin from "@/models/admin"; import WorkspaceRow from "./WorkspaceRow"; import NewWorkspaceModal from "./NewWorkspaceModal"; import { useModal } from "@/hooks/useModal"; import ModalWrapper from "@/components/ModalWrapper"; import CTAButton from "@/components/lib/CTAButton"; export default function AdminWorkspaces() { const { isOpen, openModal, closeModal } = useModal(); return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex"> <Sidebar /> <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] bg-theme-bg-secondary w-full h-full overflow-y-scroll p-4 md:p-0" > <div className="flex flex-col w-full px-1 md:pl-6 md:pr-[50px] md:py-6 py-16"> <div className="w-full flex flex-col gap-y-1 pb-6 border-white/10 border-b-2"> <div className="items-center flex gap-x-4"> <p className="text-lg leading-6 font-bold text-theme-text-primary"> Instance Workspaces </p> </div> <p className="text-xs leading-[18px] font-base text-theme-text-secondary"> These are all the workspaces that exist on this instance. Removing a workspace will delete all of its associated chats and settings. </p> </div> <div className="w-full justify-end flex"> <CTAButton onClick={openModal} className="mt-3 mr-0 mb-4 md:-mb-14 z-10" > <BookOpen className="h-4 w-4" weight="bold" /> New Workspace </CTAButton> </div> <div className="overflow-x-auto"> <WorkspacesContainer /> </div> </div> <ModalWrapper isOpen={isOpen}> <NewWorkspaceModal closeModal={closeModal} /> </ModalWrapper> </div> </div> ); } function WorkspacesContainer() { const [loading, setLoading] = useState(true); const [users, setUsers] = useState([]); const [workspaces, setWorkspaces] = useState([]); useEffect(() => { async function fetchData() { const _users = await Admin.users(); const _workspaces = await Admin.workspaces(); setUsers(_users); setWorkspaces(_workspaces); setLoading(false); } fetchData(); }, []); if (loading) { return ( <Skeleton.default height="80vh" width="100%" highlightColor="var(--theme-bg-primary)" baseColor="var(--theme-bg-secondary)" count={1} className="w-full p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm mt-6" containerClassName="flex w-full" /> ); } return ( <table className="w-full text-xs text-left rounded-lg mt-6 min-w-[640px] border-spacing-0"> <thead className="text-theme-text-secondary text-xs leading-[18px] font-bold uppercase border-white/10 border-b"> <tr> <th scope="col" className="px-6 py-3 rounded-tl-lg"> Name </th> <th scope="col" className="px-6 py-3"> Link </th> <th scope="col" className="px-6 py-3"> Users </th> <th scope="col" className="px-6 py-3"> Created On </th> <th scope="col" className="px-6 py-3 rounded-tr-lg"> {" "} </th> </tr> </thead> <tbody> {workspaces.map((workspace) => ( <WorkspaceRow key={workspace.id} workspace={workspace} users={users} /> ))} </tbody> </table> ); }
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/pages/Admin/Workspaces/NewWorkspaceModal/index.jsx
frontend/src/pages/Admin/Workspaces/NewWorkspaceModal/index.jsx
import React, { useState } from "react"; import { X } from "@phosphor-icons/react"; import Admin from "@/models/admin"; import { useTranslation } from "react-i18next"; export default function NewWorkspaceModal({ closeModal }) { const [error, setError] = useState(null); const { t } = useTranslation(); const handleCreate = async (e) => { setError(null); e.preventDefault(); const form = new FormData(e.target); const { workspace, error } = await Admin.newWorkspace(form.get("name")); if (!!workspace) window.location.reload(); setError(error); }; 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 workspace </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="name" className="block mb-2 text-sm font-medium text-white" > {t("common.workspaces-name")} </label> <input name="name" 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="My workspace" minLength={4} required={true} autoComplete="off" /> </div> {error && <p className="text-red-400 text-sm">Error: {error}</p>} <p className="text-white text-opacity-60 text-xs md:text-sm"> After creating this workspace only admins will be able to see it. You can add users after it has been created. </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 workspace </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/pages/Admin/Workspaces/WorkspaceRow/index.jsx
frontend/src/pages/Admin/Workspaces/WorkspaceRow/index.jsx
import { useRef } from "react"; import Admin from "@/models/admin"; import paths from "@/utils/paths"; import { LinkSimple, Trash } from "@phosphor-icons/react"; export default function WorkspaceRow({ workspace, users }) { const rowRef = useRef(null); const handleDelete = async () => { if ( !window.confirm( `Are you sure you want to delete ${workspace.name}?\nAfter you do this it will be unavailable in this instance of AnythingLLM.\n\nThis action is irreversible.` ) ) return false; rowRef?.current?.remove(); await Admin.deleteWorkspace(workspace.id); }; return ( <> <tr ref={rowRef} className="bg-transparent text-white text-opacity-80 text-xs font-medium border-b border-white/10 h-10" > <th scope="row" className="px-6 whitespace-nowrap"> {workspace.name} </th> <td className="px-6 flex items-center"> <a href={paths.workspace.chat(workspace.slug)} target="_blank" rel="noreferrer" className="text-white flex items-center hover:underline" > <LinkSimple className="mr-2 w-4 h-4" /> {workspace.slug} </a> </td> <td className="px-6"> <a href={paths.workspace.settings.members(workspace.slug)} className="text-white flex items-center underline" > {workspace.userIds?.length} </a> </td> <td className="px-6">{workspace.createdAt}</td> <td className="px-6 flex items-center gap-x-6 h-full mt-1"> <button onClick={handleDelete} className="text-xs font-medium text-white/80 light:text-black/80 hover:light:text-red-500 hover:text-red-300 rounded-lg px-2 py-1 hover:bg-white hover:light:bg-red-50 hover:bg-opacity-10" > <Trash className="h-5 w-5" /> </button> </td> </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/pages/Admin/Users/index.jsx
frontend/src/pages/Admin/Users/index.jsx
import { useEffect, useState } from "react"; import Sidebar from "@/components/SettingsSidebar"; import { isMobile } from "react-device-detect"; import * as Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; import { UserPlus } from "@phosphor-icons/react"; import Admin from "@/models/admin"; import UserRow from "./UserRow"; import useUser from "@/hooks/useUser"; import NewUserModal from "./NewUserModal"; import { useModal } from "@/hooks/useModal"; import ModalWrapper from "@/components/ModalWrapper"; import CTAButton from "@/components/lib/CTAButton"; export default function AdminUsers() { const { isOpen, openModal, closeModal } = useModal(); return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex"> <Sidebar /> <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] bg-theme-bg-secondary w-full h-full overflow-y-scroll p-4 md:p-0" > <div className="flex flex-col w-full px-1 md:pl-6 md:pr-[50px] md:py-6 py-16"> <div className="w-full flex flex-col gap-y-1 pb-6 border-white/10 border-b-2"> <div className="items-center flex gap-x-4"> <p className="text-lg leading-6 font-bold text-theme-text-primary"> Users </p> </div> <p className="text-xs leading-[18px] font-base text-theme-text-secondary"> These are all the accounts which have an account on this instance. Removing an account will instantly remove their access to this instance. </p> </div> <div className="w-full justify-end flex"> <CTAButton onClick={openModal} className="mt-3 mr-0 mb-4 md:-mb-6 z-10" > <UserPlus className="h-4 w-4" weight="bold" /> Add user </CTAButton> </div> <div className="overflow-x-auto"> <UsersContainer /> </div> </div> <ModalWrapper isOpen={isOpen}> <NewUserModal closeModal={closeModal} /> </ModalWrapper> </div> </div> ); } function UsersContainer() { const { user: currUser } = useUser(); const [loading, setLoading] = useState(true); const [users, setUsers] = useState([]); useEffect(() => { async function fetchUsers() { const _users = await Admin.users(); setUsers(_users); setLoading(false); } fetchUsers(); }, []); if (loading) { return ( <Skeleton.default height="80vh" width="100%" highlightColor="var(--theme-bg-primary)" baseColor="var(--theme-bg-secondary)" count={1} className="w-full p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm mt-8" containerClassName="flex w-full" /> ); } return ( <table className="w-full text-xs text-left rounded-lg min-w-[640px] border-spacing-0"> <thead className="text-theme-text-secondary text-xs leading-[18px] font-bold uppercase border-white/10 border-b"> <tr> <th scope="col" className="px-6 py-3 rounded-tl-lg"> Username </th> <th scope="col" className="px-6 py-3"> Role </th> <th scope="col" className="px-6 py-3"> Date Added </th> <th scope="col" className="px-6 py-3 rounded-tr-lg"> {" "} </th> </tr> </thead> <tbody> {users.map((user) => ( <UserRow key={user.id} currUser={currUser} user={user} /> ))} </tbody> </table> ); } const ROLE_HINT = { default: [ "Can only send chats with workspaces they are added to by admin or managers.", "Cannot modify any settings at all.", ], manager: [ "Can view, create, and delete any workspaces and modify workspace-specific settings.", "Can create, update and invite new users to the instance.", "Cannot modify LLM, vectorDB, embedding, or other connections.", ], admin: [ "Highest user level privilege.", "Can see and do everything across the system.", ], }; export function RoleHintDisplay({ role }) { return ( <div className="flex flex-col gap-y-1 py-1 pb-4"> <p className="text-sm font-medium text-theme-text-primary">Permissions</p> <ul className="flex flex-col gap-y-1 list-disc px-4"> {ROLE_HINT[role ?? "default"].map((hints, i) => { return ( <li key={i} className="text-xs text-theme-text-secondary"> {hints} </li> ); })} </ul> </div> ); } export function MessageLimitInput({ enabled, limit, updateState, role }) { if (role === "admin") return null; return ( <div className="mt-4 mb-8"> <div className="flex flex-col gap-y-1"> <div className="flex items-center gap-x-2"> <h2 className="text-base leading-6 font-bold text-white"> Limit messages per day </h2> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={enabled} onChange={(e) => { updateState((prev) => ({ ...prev, enabled: e.target.checked, })); }} className="peer sr-only" /> <div className="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> </label> </div> <p className="text-xs leading-[18px] font-base text-white/60"> Restrict this user to a number of successful queries or chats within a 24 hour window. </p> </div> {enabled && ( <div className="mt-4"> <label className="text-white text-sm font-semibold block mb-4"> Message limit per day </label> <div className="relative mt-2"> <input type="number" onScroll={(e) => e.target.blur()} onChange={(e) => { updateState({ enabled: true, limit: Number(e?.target?.value || 0), }); }} value={limit} 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" /> </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/pages/Admin/Users/NewUserModal/index.jsx
frontend/src/pages/Admin/Users/NewUserModal/index.jsx
import React, { useState } from "react"; import { X } from "@phosphor-icons/react"; import Admin from "@/models/admin"; import { userFromStorage } from "@/utils/request"; import { MessageLimitInput, RoleHintDisplay } from ".."; export default function NewUserModal({ closeModal }) { const [error, setError] = useState(null); const [role, setRole] = useState("default"); const [messageLimit, setMessageLimit] = useState({ enabled: false, limit: 10, }); const handleCreate = async (e) => { setError(null); e.preventDefault(); const data = {}; const form = new FormData(e.target); for (var [key, value] of form.entries()) data[key] = value; data.dailyMessageLimit = messageLimit.enabled ? messageLimit.limit : null; const { user, error } = await Admin.newUser(data); if (!!user) window.location.reload(); setError(error); }; const user = userFromStorage(); 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"> Add user to instance </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="username" className="block mb-2 text-sm font-medium text-white" > Username </label> <input name="username" 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="User's username" minLength={2} required={true} autoComplete="off" /> <p className="mt-2 text-xs text-white/60"> Username must only contain lowercase letters, periods, numbers, underscores, and hyphens with no spaces </p> </div> <div> <label htmlFor="password" className="block mb-2 text-sm font-medium text-white" > Password </label> <input name="password" 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="User's initial password" required={true} autoComplete="off" minLength={8} /> <p className="mt-2 text-xs text-white/60"> Password must be at least 8 characters long </p> </div> <div> <label htmlFor="bio" className="block mb-2 text-sm font-medium text-white" > Bio </label> <textarea name="bio" 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="User's bio" autoComplete="off" rows={3} /> </div> <div> <label htmlFor="role" className="block mb-2 text-sm font-medium text-white" > Role </label> <select name="role" required={true} defaultValue={"default"} onChange={(e) => setRole(e.target.value)} 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" > <option value="default">Default</option> <option value="manager">Manager</option> {user?.role === "admin" && ( <option value="admin">Administrator</option> )} </select> <RoleHintDisplay role={role} /> </div> <MessageLimitInput role={role} enabled={messageLimit.enabled} limit={messageLimit.limit} updateState={setMessageLimit} /> {error && <p className="text-red-400 text-sm">Error: {error}</p>} <p className="text-white text-xs md:text-sm"> After creating a user they will need to login with their initial login to get access. </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" > Add user </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/pages/Admin/Users/UserRow/index.jsx
frontend/src/pages/Admin/Users/UserRow/index.jsx
import { useRef, useState } from "react"; import { titleCase } from "text-case"; import Admin from "@/models/admin"; import EditUserModal from "./EditUserModal"; import showToast from "@/utils/toast"; import { useModal } from "@/hooks/useModal"; import ModalWrapper from "@/components/ModalWrapper"; const ModMap = { admin: ["admin", "manager", "default"], manager: ["manager", "default"], default: [], }; export default function UserRow({ currUser, user }) { const rowRef = useRef(null); const canModify = ModMap[currUser?.role || "default"].includes(user.role); const [suspended, setSuspended] = useState(user.suspended === 1); const { isOpen, openModal, closeModal } = useModal(); const handleSuspend = async () => { if ( !window.confirm( `Are you sure you want to suspend ${user.username}?\nAfter you do this they will be logged out and unable to log back into this instance of AnythingLLM until unsuspended by an admin.` ) ) return false; const { success, error } = await Admin.updateUser(user.id, { suspended: suspended ? 0 : 1, }); if (!success) showToast(error, "error", { clear: true }); if (success) { showToast( `User ${!suspended ? "has been suspended" : "is no longer suspended"}.`, "success", { clear: true } ); setSuspended(!suspended); } }; const handleDelete = async () => { if ( !window.confirm( `Are you sure you want to delete ${user.username}?\nAfter you do this they will be logged out and unable to use this instance of AnythingLLM.\n\nThis action is irreversible.` ) ) return false; const { success, error } = await Admin.deleteUser(user.id); if (!success) showToast(error, "error", { clear: true }); if (success) { rowRef?.current?.remove(); showToast("User deleted from system.", "success", { clear: true }); } }; return ( <> <tr ref={rowRef} className="bg-transparent text-white text-opacity-80 text-xs font-medium border-b border-white/10 h-10" > <th scope="row" className="px-6 whitespace-nowrap"> {user.username} </th> <td className="px-6">{titleCase(user.role)}</td> <td className="px-6">{user.createdAt}</td> <td className="px-6 flex items-center gap-x-6 h-full mt-2"> {canModify && ( <button onClick={openModal} className="text-xs font-medium text-white/80 light:text-black/80 rounded-lg hover:text-white hover:light:text-gray-500 px-2 py-1 hover:bg-white hover:bg-opacity-10" > Edit </button> )} {currUser?.id !== user.id && canModify && ( <> <button onClick={handleSuspend} className="text-xs font-medium text-white/80 light:text-black/80 hover:light:text-orange-500 hover:text-orange-300 rounded-lg px-2 py-1 hover:bg-white hover:light:bg-orange-50 hover:bg-opacity-10" > {suspended ? "Unsuspend" : "Suspend"} </button> <button onClick={handleDelete} className="text-xs font-medium text-white/80 light:text-black/80 hover:light:text-red-500 hover:text-red-300 rounded-lg px-2 py-1 hover:bg-white hover:light:bg-red-50 hover:bg-opacity-10" > Delete </button> </> )} </td> </tr> <ModalWrapper isOpen={isOpen}> <EditUserModal currentUser={currUser} user={user} closeModal={closeModal} /> </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/pages/Admin/Users/UserRow/EditUserModal/index.jsx
frontend/src/pages/Admin/Users/UserRow/EditUserModal/index.jsx
import React, { useState } from "react"; import { X } from "@phosphor-icons/react"; import Admin from "@/models/admin"; import { MessageLimitInput, RoleHintDisplay } from "../.."; import { AUTH_USER } from "@/utils/constants"; export default function EditUserModal({ currentUser, user, closeModal }) { const [role, setRole] = useState(user.role); const [error, setError] = useState(null); const [messageLimit, setMessageLimit] = useState({ enabled: user.dailyMessageLimit !== null, limit: user.dailyMessageLimit || 10, }); const handleUpdate = async (e) => { setError(null); e.preventDefault(); const data = {}; const form = new FormData(e.target); for (var [key, value] of form.entries()) { if (!value || value === null) continue; data[key] = value; } if (messageLimit.enabled) { data.dailyMessageLimit = messageLimit.limit; } else { data.dailyMessageLimit = null; } const { success, error } = await Admin.updateUser(user.id, data); if (success) { // Update local storage if we're editing our own user if (currentUser && currentUser.id === user.id) { currentUser.username = data.username; currentUser.bio = data.bio; currentUser.role = data.role; localStorage.setItem(AUTH_USER, JSON.stringify(currentUser)); } window.location.reload(); } setError(error); }; 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"> Edit {user.username} </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={handleUpdate}> <div className="space-y-4"> <div> <label htmlFor="username" className="block mb-2 text-sm font-medium text-white" > Username </label> <input name="username" 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="User's username" defaultValue={user.username} minLength={2} required={true} autoComplete="off" /> <p className="mt-2 text-xs text-white/60"> Username must only contain lowercase letters, periods, numbers, underscores, and hyphens with no spaces </p> </div> <div> <label htmlFor="password" className="block mb-2 text-sm font-medium text-white" > New Password </label> <input name="password" 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={`${user.username}'s new password`} autoComplete="off" minLength={8} /> <p className="mt-2 text-xs text-white/60"> Password must be at least 8 characters long </p> </div> <div> <label htmlFor="bio" className="block mb-2 text-sm font-medium text-white" > Bio </label> <textarea name="bio" 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="User's bio" defaultValue={user.bio} autoComplete="off" rows={3} /> </div> <div> <label htmlFor="role" className="block mb-2 text-sm font-medium text-white" > Role </label> <select name="role" required={true} defaultValue={user.role} onChange={(e) => setRole(e.target.value)} 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" > <option value="default">Default</option> <option value="manager">Manager</option> {currentUser?.role === "admin" && ( <option value="admin">Administrator</option> )} </select> <RoleHintDisplay role={role} /> </div> <MessageLimitInput role={role} enabled={messageLimit.enabled} limit={messageLimit.limit} updateState={setMessageLimit} /> {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" > Update user </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/pages/Admin/ExperimentalFeatures/index.jsx
frontend/src/pages/Admin/ExperimentalFeatures/index.jsx
import { useEffect, useState } from "react"; import Sidebar from "@/components/SettingsSidebar"; import { isMobile } from "react-device-detect"; import Admin from "@/models/admin"; import { FullScreenLoader } from "@/components/Preloader"; import { CaretRight, Flask } from "@phosphor-icons/react"; import { configurableFeatures } from "./features"; import ModalWrapper from "@/components/ModalWrapper"; import paths from "@/utils/paths"; import showToast from "@/utils/toast"; export default function ExperimentalFeatures() { const [featureFlags, setFeatureFlags] = useState({}); const [loading, setLoading] = useState(true); const [selectedFeature, setSelectedFeature] = useState( "experimental_live_file_sync" ); useEffect(() => { async function fetchSettings() { setLoading(true); const { settings } = await Admin.systemPreferences(); setFeatureFlags(settings?.feature_flags ?? {}); setLoading(false); } fetchSettings(); }, []); const refresh = async () => { const { settings } = await Admin.systemPreferences(); setFeatureFlags(settings?.feature_flags ?? {}); }; if (loading) { return ( <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] w-full h-full flex justify-center items-center" > <FullScreenLoader /> </div> ); } return ( <FeatureLayout> <div className="flex-1 flex gap-x-6 p-4 mt-10"> {/* Feature settings nav */} <div className="flex flex-col gap-y-[18px]"> <div className="text-white flex items-center gap-x-2"> <Flask size={24} /> <p className="text-lg font-medium">Experimental Features</p> </div> {/* Feature list */} <div className="bg-theme-bg-secondary text-white rounded-xl min-w-[360px] w-fit"> {Object.values(configurableFeatures).map((feature, index) => { const isFirst = index === 0; const isLast = index === Object.values(configurableFeatures).length - 1; return ( <FeatureItem key={feature.key} feature={feature} isSelected={selectedFeature === feature.key} isActive={featureFlags[feature.key]} handleClick={setSelectedFeature} borderClass={[ ...(isFirst ? ["rounded-t-xl"] : []), ...(isLast ? ["rounded-b-xl"] : ["border-b border-white/10"]), ].join(" ")} /> ); })} </div> </div> {/* Selected feature setting panel */} <FeatureVerification> <div className="flex-[2] flex flex-col gap-y-[18px] mt-10"> <div className="bg-theme-bg-secondary text-white rounded-xl flex-1 p-4"> {selectedFeature ? ( <SelectedFeatureComponent feature={configurableFeatures[selectedFeature]} settings={featureFlags} refresh={refresh} /> ) : ( <div className="flex flex-col items-center justify-center h-full text-white/60"> <Flask size={40} /> <p className="font-medium">Select an experimental feature</p> </div> )} </div> </div> </FeatureVerification> </div> </FeatureLayout> ); } function FeatureLayout({ children }) { return ( <div id="workspace-feature-settings-container" className="w-screen h-screen overflow-hidden bg-theme-bg-container flex md:mt-0 mt-6" > <Sidebar /> <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] w-full h-full flex" > {children} </div> </div> ); } function FeatureItem({ feature = {}, isSelected = false, isActive = false, handleClick = () => {}, borderClass = "border-b border-white/10", }) { return ( <div key={feature.key} className={`py-3 px-4 flex items-center justify-between cursor-pointer transition-all duration-300 hover:bg-white/5 ${borderClass} ${ isSelected ? "bg-white/10 light:bg-theme-bg-sidebar" : "" }`} onClick={() => { if (feature?.href) window.location = feature.href; else handleClick?.(feature.key); }} > <div className="text-sm font-light">{feature.title}</div> <div className="flex items-center gap-x-2"> {feature.autoEnabled ? ( <> <div className="text-sm text-theme-text-secondary font-medium"> On </div> <div className="w-[14px]" /> </> ) : ( <> <div className="text-sm text-theme-text-secondary font-medium"> {isActive ? "On" : "Off"} </div> <CaretRight size={14} weight="bold" className="text-theme-text-secondary" /> </> )} </div> </div> ); } function SelectedFeatureComponent({ feature, settings, refresh }) { const Component = feature?.component; return Component ? ( <Component enabled={settings[feature.key]} feature={feature.key} onToggle={refresh} /> ) : null; } function FeatureVerification({ children }) { if ( !window.localStorage.getItem("anythingllm_tos_experimental_feature_set") ) { function acceptTos(e) { e.preventDefault(); window.localStorage.setItem( "anythingllm_tos_experimental_feature_set", "accepted" ); showToast( "Experimental Feature set enabled. Reloading the page.", "success" ); setTimeout(() => { window.location.reload(); }, 2_500); return; } 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="flex items-center gap-2"> <Flask size={24} className="text-theme-text-primary" /> <h3 className="text-xl font-semibold text-white"> Terms of use for experimental features </h3> </div> </div> <form onSubmit={acceptTos}> <div className="py-7 px-9 space-y-4 flex-col"> <div className="w-full text-white text-md flex flex-col gap-y-4"> <p> Experimental features of AnythingLLM are features that we are piloting and are <b>opt-in</b>. We proactively will condition or warn you on any potential concerns should any exist prior to approval of any feature. </p> <div> <p> Use of any feature on this page can result in, but not limited to, the following possibilities. </p> <ul className="list-disc ml-6 text-sm font-mono mt-2"> <li>Loss of data.</li> <li>Change in quality of results.</li> <li>Increased storage.</li> <li>Increased resource consumption.</li> <li> Increased cost or use of any connected LLM or embedding provider. </li> <li>Potential bugs or issues using AnythingLLM.</li> </ul> </div> <div> <p> Use of an experimental feature also comes with the following list of non-exhaustive conditions. </p> <ul className="list-disc ml-6 text-sm font-mono mt-2"> <li>Feature may not exist in future updates.</li> <li>The feature being used is not currently stable.</li> <li> The feature may not be available in future versions, configurations, or subscriptions of AnythingLLM. </li> <li> Your privacy settings <b>will be honored</b> with use of any beta feature. </li> <li>These conditions may change in future updates.</li> </ul> </div> <p> Access to any features requires approval of this modal. If you would like to read more you can refer to{" "} <a href="https://docs.anythingllm.com/beta-preview/overview" className="underline text-blue-500" > docs.anythingllm.com </a>{" "} or email{" "} <a href="mailto:[email protected]" className="underline text-blue-500" > [email protected] </a> </p> </div> </div> <div className="flex w-full justify-between items-center p-6 space-x-2 border-t border-theme-modal-border rounded-b"> <a href={paths.home()} className="transition-all duration-300 bg-transparent text-white hover:bg-red-500/50 light:hover:bg-red-300/50 px-4 py-2 rounded-lg text-sm border border-theme-modal-border" > Reject & close </a> <button type="submit" className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm border border-theme-modal-border" > I understand </button> </div> </form> </div> </ModalWrapper> {children} </> ); } return <>{children}</>; }
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/pages/Admin/ExperimentalFeatures/features.js
frontend/src/pages/Admin/ExperimentalFeatures/features.js
import LiveSyncToggle from "./Features/LiveSync/toggle"; import paths from "@/utils/paths"; export const configurableFeatures = { experimental_live_file_sync: { title: "Live Document Sync", component: LiveSyncToggle, key: "experimental_live_file_sync", }, experimental_mobile_connections: { title: "AnythingLLM Mobile", href: paths.settings.mobileConnections(), key: "experimental_mobile_connections", autoEnabled: true, }, };
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/pages/Admin/ExperimentalFeatures/Features/LiveSync/toggle.jsx
frontend/src/pages/Admin/ExperimentalFeatures/Features/LiveSync/toggle.jsx
import System from "@/models/system"; import paths from "@/utils/paths"; import showToast from "@/utils/toast"; import { ArrowSquareOut } from "@phosphor-icons/react"; import { useState } from "react"; import { Link } from "react-router-dom"; export default function LiveSyncToggle({ enabled = false, onToggle }) { const [status, setStatus] = useState(enabled); async function toggleFeatureFlag() { const updated = await System.experimentalFeatures.liveSync.toggleFeature(!status); if (!updated) { showToast("Failed to update status of feature.", "error", { clear: true, }); return false; } setStatus(!status); showToast( `Live document content sync has been ${ !status ? "enabled" : "disabled" }.`, "success", { clear: true } ); onToggle(); } return ( <div className="p-4"> <div className="flex flex-col gap-y-6 max-w-[500px]"> <div className="flex items-center justify-between"> <h2 className="text-theme-text-primary text-md font-bold"> Automatic Document Content Sync </h2> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" onClick={toggleFeatureFlag} checked={status} className="peer sr-only pointer-events-none" /> <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> </label> </div> <div className="flex flex-col space-y-4"> <p className="text-theme-text-secondary text-sm"> Enable the ability to specify a document to be "watched". Watched document's content will be regularly fetched and updated in AnythingLLM. </p> <p className="text-theme-text-secondary text-sm"> Watched documents will automatically update in all workspaces they are referenced in at the same time of update. </p> <p className="text-theme-text-secondary text-xs italic"> This feature only applies to web-based content, such as websites, Confluence, YouTube, and GitHub files. </p> </div> </div> <div className="mt-8"> <ul className="space-y-2"> <li> <a href="https://docs.anythingllm.com/beta-preview/active-features/live-document-sync" target="_blank" className="text-sm text-blue-400 light:text-blue-500 hover:underline flex items-center gap-x-1" > <ArrowSquareOut size={14} /> <span>Feature Documentation and Warnings</span> </a> </li> <li> <Link to={paths.experimental.liveDocumentSync.manage()} className="text-sm text-blue-400 light:text-blue-500 hover:underline" > Manage Watched Documents &rarr; </Link> </li> </ul> </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/pages/Admin/ExperimentalFeatures/Features/LiveSync/manage/index.jsx
frontend/src/pages/Admin/ExperimentalFeatures/Features/LiveSync/manage/index.jsx
import { useEffect, useState } from "react"; import Sidebar from "@/components/Sidebar"; import { isMobile } from "react-device-detect"; import * as Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; import System from "@/models/system"; import DocumentSyncQueueRow from "./DocumentSyncQueueRow"; export default function LiveDocumentSyncManager() { return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex"> <Sidebar /> <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] bg-theme-bg-secondary w-full h-full overflow-y-scroll p-4 md:p-0" > <div className="flex flex-col w-full px-1 md:pl-6 md:pr-[50px] md:py-6 py-16"> <div className="w-full flex flex-col gap-y-1 pb-6 border-white/10 border-b-2"> <div className="items-center flex gap-x-4"> <p className="text-lg leading-6 font-bold text-theme-text-primary"> Watched documents </p> </div> <p className="text-xs leading-[18px] font-base text-theme-text-secondary"> These are all the documents that are currently being watched in your instance. The content of these documents will be periodically synced. </p> </div> <div className="overflow-x-auto"> <WatchedDocumentsContainer /> </div> </div> </div> </div> ); } function WatchedDocumentsContainer() { const [loading, setLoading] = useState(true); const [queues, setQueues] = useState([]); useEffect(() => { async function fetchData() { const _queues = await System.experimentalFeatures.liveSync.queues(); setQueues(_queues); setLoading(false); } fetchData(); }, []); if (loading) { return ( <Skeleton.default height="80vh" width="100%" highlightColor="var(--theme-bg-primary)" baseColor="var(--theme-bg-secondary)" count={1} className="w-full p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm mt-6" containerClassName="flex w-full" /> ); } return ( <table className="w-full text-sm text-left rounded-lg mt-6 min-w-[640px]"> <thead className="text-theme-text-secondary text-xs leading-[18px] font-bold uppercase border-white/10 border-b"> <tr> <th scope="col" className="px-6 py-3 rounded-tl-lg"> Document Name </th> <th scope="col" className="px-6 py-3"> Last Synced </th> <th scope="col" className="px-6 py-3"> Time until next refresh </th> <th scope="col" className="px-6 py-3"> Created On </th> <th scope="col" className="px-6 py-3 rounded-tr-lg"> {" "} </th> </tr> </thead> <tbody> {queues.map((queue) => ( <DocumentSyncQueueRow key={queue.id} queue={queue} /> ))} </tbody> </table> ); }
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/pages/Admin/ExperimentalFeatures/Features/LiveSync/manage/DocumentSyncQueueRow/index.jsx
frontend/src/pages/Admin/ExperimentalFeatures/Features/LiveSync/manage/DocumentSyncQueueRow/index.jsx
import { useRef } from "react"; import { Trash } from "@phosphor-icons/react"; import { stripUuidAndJsonFromString } from "@/components/Modals/ManageWorkspace/Documents/Directory/utils"; import moment from "moment"; import System from "@/models/system"; export default function DocumentSyncQueueRow({ queue }) { const rowRef = useRef(null); const handleDelete = async () => { rowRef?.current?.remove(); await System.experimentalFeatures.liveSync.setWatchStatusForDocument( queue.workspaceDoc.workspace.slug, queue.workspaceDoc.docpath, false ); }; return ( <> <tr ref={rowRef} className="bg-transparent text-white text-opacity-80 text-sm font-medium" > <td scope="row" className="px-6 py-4 whitespace-nowrap"> {stripUuidAndJsonFromString(queue.workspaceDoc.filename)} </td> <td className="px-6 py-4">{moment(queue.lastSyncedAt).fromNow()}</td> <td className="px-6 py-4"> {moment(queue.nextSyncAt).format("lll")} <i className="text-xs px-2">({moment(queue.nextSyncAt).fromNow()})</i> </td> <td className="px-6 py-4">{moment(queue.createdAt).format("lll")}</td> <td className="px-6 py-4 flex items-center gap-x-6"> <button onClick={handleDelete} className="border-none font-medium px-2 py-1 rounded-lg text-theme-text-primary hover:text-red-500" > <Trash className="h-5 w-5" /> </button> </td> </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/pages/Admin/DefaultSystemPrompt/index.jsx
frontend/src/pages/Admin/DefaultSystemPrompt/index.jsx
import SettingsSidebar from "@/components/SettingsSidebar"; import { useEffect, useState, Fragment } from "react"; import { isMobile } from "react-device-detect"; import System from "@/models/system"; import showToast from "@/utils/toast"; import * as Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; import Highlighter from "react-highlight-words"; import SystemPromptVariable from "@/models/systemPromptVariable"; import { Link } from "react-router-dom"; import paths from "@/utils/paths"; export default function DefaultSystemPrompt() { const [systemPromptForm, setSystemPromptForm] = useState({ value: "", default: "", isDirty: false, isSubmitting: false, isLoading: true, isEditing: false, }); const [saneDefaultSystemPrompt, setSaneDefaultSystemPrompt] = useState(""); const [availableVariables, setAvailableVariables] = useState([]); useEffect(() => { async function setupVariableHighlighting() { const { variables } = await SystemPromptVariable.getAll(); setAvailableVariables(variables); } setupVariableHighlighting(); }, []); useEffect(() => { async function fetchDefaultSystemPrompt() { setSystemPromptForm((prev) => ({ ...prev, isLoading: true, })); const { defaultSystemPrompt, saneDefaultSystemPrompt } = await System.fetchDefaultSystemPrompt(); setSaneDefaultSystemPrompt(saneDefaultSystemPrompt); if (!defaultSystemPrompt) return setSystemPromptForm((prev) => ({ ...prev, isLoading: false, })); setSystemPromptForm((prev) => ({ ...prev, default: defaultSystemPrompt, value: defaultSystemPrompt, isLoading: false, })); } fetchDefaultSystemPrompt(); }, []); const handleChange = (e) => { const value = e.target.value; const isDirty = value !== systemPromptForm.default; setSystemPromptForm((prev) => ({ ...prev, value, isDirty, isSubmitting: false, })); }; const handleSubmit = async (e) => { e.preventDefault(); setSystemPromptForm((prev) => ({ ...prev, isSubmitting: true, })); const newSystemPrompt = systemPromptForm.value.trim(); await System.updateDefaultSystemPrompt(newSystemPrompt) .then(({ success, message }) => { if (!success) throw new Error(message); // If the user has set the default system prompt to the sane default, reset the value to the sane default. if ( !newSystemPrompt || newSystemPrompt.trim() === saneDefaultSystemPrompt ) { return setSystemPromptForm((prev) => ({ ...prev, value: saneDefaultSystemPrompt, })); } showToast("Default system prompt updated successfully.", "success"); setSystemPromptForm((prev) => ({ ...prev, default: newSystemPrompt, isDirty: false, isSubmitting: false, })); }) .catch((error) => { showToast( `Failed to update default system prompt: ${error.message}`, "error" ); setSystemPromptForm((prev) => ({ ...prev, isSubmitting: false, })); }); }; return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex"> <SettingsSidebar /> <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] bg-theme-bg-secondary w-full h-full overflow-y-scroll p-4 md:p-0" > <div className="flex flex-col w-full px-1 md:pl-6 md:pr-[50px] md:py-6 py-16"> <div className="w-full flex flex-col gap-y-1 pb-6 border-white/10 border-b-2"> <div className="items-center flex gap-x-4"> <p className="text-lg leading-6 font-bold text-theme-text-primary"> Default System Prompt </p> </div> <p className="text-xs leading-[18px] font-base text-theme-text-secondary"> This is the default system prompt that will be used for new workspaces. </p> </div> <div> {systemPromptForm.isLoading ? ( <div className="mt-8 flex flex-col gap-y-4"> <Skeleton.default height={20} width={160} highlightColor="var(--theme-bg-primary)" baseColor="var(--theme-bg-secondary)" /> <Skeleton.default height={120} width="100%" highlightColor="var(--theme-bg-primary)" baseColor="var(--theme-bg-secondary)" className="rounded-lg" /> <Skeleton.default height={36} width={140} highlightColor="var(--theme-bg-primary)" baseColor="var(--theme-bg-secondary)" /> </div> ) : ( <div className="mt-6"> <form onSubmit={handleSubmit} className="space-y-3"> <label htmlFor="default-system-prompt" className=" text-base font-bold text-white" > System Prompt </label> <div className="space-y-1"> <p className="text-white text-opacity-60 text-xs font-medium"> A system prompt provides instructions that shape the AI’s responses and behavior. This prompt will be automatically applied to all newly created workspaces. To change the system prompt of a{" "} <span className="font-bold">specific workspace</span>, edit the prompt in the{" "} <span className="font-bold">workspace settings</span>. To restore the system prompt to our sane default, leave this field empty and save changes. </p> <p className="text-white text-opacity-60 text-xs font-medium mb-2"> You can insert{" "} <Link to={paths.settings.systemPromptVariables()} className="text-primary-button" > system prompt variables </Link>{" "} like:{" "} {availableVariables.slice(0, 3).map((v, i) => ( <Fragment key={v.key}> <span className="bg-theme-settings-input-bg px-1 py-0.5 rounded"> {`{${v.key}}`} </span> {i < availableVariables.length - 1 && ", "} </Fragment> ))} {availableVariables.length > 3 && ( <Link to={paths.settings.systemPromptVariables()} className="text-primary-button" > +{availableVariables.length - 3} more... </Link> )} </p> </div> {systemPromptForm.isEditing ? ( <textarea autoFocus={true} value={systemPromptForm.value} onChange={handleChange} onBlur={() => setSystemPromptForm((prev) => ({ ...prev, isEditing: false, })) } placeholder={ systemPromptForm.isLoading ? "Loading..." : "You are an AI assistant that can answer questions and help with tasks." } rows={5} style={{ resize: "vertical", overflowY: "scroll", minHeight: "150px", }} className="w-full border-none bg-theme-settings-input-bg placeholder:text-theme-settings-input-placeholder text-white text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block p-2.5" /> ) : ( <div onClick={() => setSystemPromptForm((prev) => ({ ...prev, isEditing: true, })) } style={{ resize: "vertical", overflowY: "scroll", minHeight: "150px", }} className="w-full border-none bg-theme-settings-input-bg text-white text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none block p-2.5 cursor-text" > <Highlighter className="whitespace-pre-wrap" highlightClassName="bg-cta-button p-0.5 rounded-md" searchWords={availableVariables.map( (v) => `{${v.key}}` )} autoEscape={true} caseSensitive={true} textToHighlight={systemPromptForm.value || ""} /> </div> )} <button disabled={ !systemPromptForm.isDirty || systemPromptForm.isSubmitting } className={`enabled:hover:bg-secondary enabled:hover:text-white rounded-lg bg-primary-button w-fit py-2 px-4 font-semibold text-xs disabled:opacity-20 disabled:cursor-not-allowed`} type="submit" > Save Changes </button> </form> </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/pages/Admin/Logging/index.jsx
frontend/src/pages/Admin/Logging/index.jsx
import Sidebar from "@/components/SettingsSidebar"; import useQuery from "@/hooks/useQuery"; import System from "@/models/system"; import { useEffect, useState } from "react"; import { isMobile } from "react-device-detect"; import * as Skeleton from "react-loading-skeleton"; import LogRow from "./LogRow"; import showToast from "@/utils/toast"; import CTAButton from "@/components/lib/CTAButton"; import { useTranslation } from "react-i18next"; export default function AdminLogs() { const query = useQuery(); const [loading, setLoading] = useState(true); const [logs, setLogs] = useState([]); const [offset, setOffset] = useState(Number(query.get("offset") || 0)); const [canNext, setCanNext] = useState(false); const { t } = useTranslation(); useEffect(() => { async function fetchLogs() { const { logs: _logs, hasPages = false } = await System.eventLogs(offset); setLogs(_logs); setCanNext(hasPages); setLoading(false); } fetchLogs(); }, [offset]); const handleResetLogs = async () => { if ( !window.confirm( "Are you sure you want to clear all event logs? This action is irreversible." ) ) return; const { success, error } = await System.clearEventLogs(); if (success) { showToast("Event logs cleared successfully.", "success"); setLogs([]); setCanNext(false); setOffset(0); } else { showToast(`Failed to clear logs: ${error}`, "error"); } }; const handlePrevious = () => { setOffset(Math.max(offset - 1, 0)); }; const handleNext = () => { setOffset(offset + 1); }; return ( <div className="w-screen h-screen overflow-hidden bg-theme-bg-container flex"> <Sidebar /> <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] bg-theme-bg-secondary w-full h-full overflow-y-scroll p-4 md:p-0" > <div className="flex flex-col w-full px-1 md:pl-6 md:pr-[50px] md:py-6 py-16"> <div className="w-full flex flex-col gap-y-1 pb-6 border-white/10 border-b-2"> <div className="flex gap-x-4 items-center"> <p className="text-lg leading-6 font-bold text-theme-text-primary"> {t("event.title")} </p> </div> <p className="text-xs leading-[18px] font-base text-theme-text-secondary mt-2"> {t("event.description")} </p> </div> <div className="w-full justify-end flex"> <CTAButton onClick={handleResetLogs} className="mt-3 mr-0 mb-4 md:-mb-14 z-10" > {t("event.clear")} </CTAButton> </div> <div className="overflow-x-auto mt-6"> <LogsContainer loading={loading} logs={logs} offset={offset} canNext={canNext} handleNext={handleNext} handlePrevious={handlePrevious} /> </div> </div> </div> </div> ); } function LogsContainer({ loading, logs, offset, canNext, handleNext, handlePrevious, }) { const { t } = useTranslation(); if (loading) { return ( <Skeleton.default height="80vh" width="100%" highlightColor="var(--theme-bg-primary)" baseColor="var(--theme-bg-secondary)" count={1} className="w-full p-4 rounded-b-2xl rounded-tr-2xl rounded-tl-sm" containerClassName="flex w-full" /> ); } return ( <> <table className="w-full text-xs text-left rounded-lg min-w-[640px] border-spacing-0"> <thead className="text-theme-text-secondary text-xs leading-[18px] font-bold uppercase border-white/10 border-b"> <tr> <th scope="col" className="px-6 py-3 rounded-tl-lg"> {t("event.table.type")} </th> <th scope="col" className="px-6 py-3"> {t("event.table.user")} </th> <th scope="col" className="px-6 py-3"> {t("event.table.occurred")} </th> <th scope="col" className="px-6 py-3 rounded-tr-lg"> {" "} </th> </tr> </thead> <tbody> {!!logs && logs.map((log) => <LogRow key={log.id} log={log} />)} </tbody> </table> <div className="flex w-full justify-between items-center mt-6"> <button onClick={handlePrevious} className="px-4 py-2 rounded-lg border border-slate-200 text-slate-200 light:text-theme-text-secondary light:border-theme-sidebar-border text-sm items-center flex gap-x-2 hover:bg-slate-200 hover:text-slate-800 disabled:invisible" disabled={offset === 0} > {t("common.previous")} </button> <button onClick={handleNext} className="px-4 py-2 rounded-lg border border-slate-200 text-slate-200 light:text-theme-text-secondary light:border-theme-sidebar-border text-sm items-center flex gap-x-2 hover:bg-slate-200 hover:text-slate-800 disabled:invisible" disabled={!canNext} > {t("common.next")} </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/pages/Admin/Logging/LogRow/index.jsx
frontend/src/pages/Admin/Logging/LogRow/index.jsx
import { CaretDown, CaretUp } from "@phosphor-icons/react"; import { useEffect, useState } from "react"; import { safeJsonParse } from "@/utils/request"; export default function LogRow({ log }) { const [expanded, setExpanded] = useState(false); const [metadata, setMetadata] = useState(null); const [hasMetadata, setHasMetadata] = useState(false); useEffect(() => { function parseAndSetMetadata() { const data = safeJsonParse(log.metadata, {}); setHasMetadata(Object.keys(data)?.length > 0); setMetadata(data); } parseAndSetMetadata(); }, [log.metadata]); const handleRowClick = () => { if (log.metadata !== "{}") { setExpanded(!expanded); } }; return ( <> <tr onClick={handleRowClick} className={`bg-transparent text-white text-opacity-80 text-xs font-medium border-b border-white/10 h-10 ${ hasMetadata ? "cursor-pointer hover:bg-white/5" : "" }`} > <EventBadge event={log.event} /> <td className="px-6 border-transparent transform transition-transform duration-200"> {log.user.username} </td> <td className="px-6 border-transparent transform transition-transform duration-200"> {log.occurredAt} </td> {hasMetadata && ( <div className="mt-1"> {expanded ? ( <td className={`px-2 gap-x-1 flex items-center justify-center transform transition-transform duration-200`} > <CaretUp weight="bold" size={20} /> <p className="text-xs text-white/50 w-[20px]">hide</p> </td> ) : ( <td className={`px-2 gap-x-1 flex items-center justify-center transform transition-transform duration-200`} > <CaretDown weight="bold" size={20} /> <p className="text-xs text-white/50 w-[20px]">show</p> </td> )} </div> )} </tr> <EventMetadata metadata={metadata} expanded={expanded} /> </> ); } const EventMetadata = ({ metadata, expanded = false }) => { if (!metadata || !expanded) return null; return ( <tr className="bg-theme-bg-primary"> <td colSpan="2" className="px-6 py-4 font-medium text-theme-text-primary rounded-l-2xl" > Event Metadata </td> <td colSpan="4" className="px-6 py-4 rounded-r-2xl"> <div className="w-full rounded-lg bg-theme-bg-secondary p-2 text-white shadow-sm border-white/10 border bg-opacity-10"> <pre className="overflow-scroll"> {JSON.stringify(metadata, null, 2)} </pre> </div> </td> </tr> ); }; const EventBadge = ({ event }) => { let colorTheme = { bg: "bg-sky-600/20", text: "text-sky-400 light:text-sky-800", }; if (event.includes("update")) colorTheme = { bg: "bg-yellow-600/20", text: "text-yellow-400 light:text-yellow-800", }; if (event.includes("failed_") || event.includes("deleted")) colorTheme = { bg: "bg-red-600/20", text: "text-red-400 light:text-red-800", }; if (event === "login_event") colorTheme = { bg: "bg-green-600/20", text: "text-green-400 light:text-green-800", }; return ( <td className="px-6 py-2 font-medium whitespace-nowrap text-white flex items-center"> <span className={`rounded-full ${colorTheme.bg} px-2 py-0.5 text-xs font-medium ${colorTheme.text} shadow-sm`} > {event} </span> </td> ); };
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/pages/Admin/AgentBuilder/index.jsx
frontend/src/pages/Admin/AgentBuilder/index.jsx
import React, { useState, useEffect, useRef } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { Tooltip } from "react-tooltip"; import BlockList, { BLOCK_TYPES, BLOCK_INFO } from "./BlockList"; import AddBlockMenu from "./AddBlockMenu"; import showToast from "@/utils/toast"; import AgentFlows from "@/models/agentFlows"; import { useTheme } from "@/hooks/useTheme"; import HeaderMenu from "./HeaderMenu"; import paths from "@/utils/paths"; import PublishEntityModal from "@/components/CommunityHub/PublishEntityModal"; const DEFAULT_BLOCKS = [ { id: "flow_info", type: BLOCK_TYPES.FLOW_INFO, config: { name: "", description: "", }, isExpanded: true, }, { id: "start", type: BLOCK_TYPES.START, config: { variables: [{ name: "", value: "" }], }, isExpanded: true, }, { id: "finish", type: BLOCK_TYPES.FINISH, config: {}, isExpanded: false, }, ]; export default function AgentBuilder() { const { flowId } = useParams(); const { theme } = useTheme(); const navigate = useNavigate(); const [agentName, setAgentName] = useState(""); const [_, setAgentDescription] = useState(""); const [currentFlowUuid, setCurrentFlowUuid] = useState(null); const [active, setActive] = useState(true); const [blocks, setBlocks] = useState(DEFAULT_BLOCKS); const [selectedBlock, setSelectedBlock] = useState("start"); const [showBlockMenu, setShowBlockMenu] = useState(false); const [showLoadMenu, setShowLoadMenu] = useState(false); const [availableFlows, setAvailableFlows] = useState([]); const [selectedFlowForDetails, setSelectedFlowForDetails] = useState(null); const nameRef = useRef(null); const descriptionRef = useRef(null); const [showPublishModal, setShowPublishModal] = useState(false); useEffect(() => { loadAvailableFlows(); }, []); useEffect(() => { if (flowId) { loadFlow(flowId); } }, [flowId]); useEffect(() => { const flowInfoBlock = blocks.find( (block) => block.type === BLOCK_TYPES.FLOW_INFO ); setAgentName(flowInfoBlock?.config?.name || ""); }, [blocks]); const loadAvailableFlows = async () => { try { const { success, error, flows } = await AgentFlows.listFlows(); if (!success) throw new Error(error); setAvailableFlows(flows); } catch (error) { console.error(error); showToast("Failed to load available flows", "error", { clear: true }); } }; const loadFlow = async (uuid) => { try { const { success, error, flow } = await AgentFlows.getFlow(uuid); if (!success) throw new Error(error); // Convert steps to blocks with IDs, ensuring finish block is at the end const flowBlocks = [ { id: "flow_info", type: BLOCK_TYPES.FLOW_INFO, config: { name: flow.config.name, description: flow.config.description, }, isExpanded: true, }, ...flow.config.steps.map((step, index) => ({ id: index === 0 ? "start" : `block_${index}`, type: step.type, config: step.config, isExpanded: true, })), ]; // Add finish block if not present if (flowBlocks[flowBlocks.length - 1]?.type !== BLOCK_TYPES.FINISH) { flowBlocks.push({ id: "finish", type: BLOCK_TYPES.FINISH, config: {}, isExpanded: false, }); } setAgentName(flow.config.name); setAgentDescription(flow.config.description); setActive(flow.config.active ?? true); setCurrentFlowUuid(flow.uuid); setBlocks(flowBlocks); setShowLoadMenu(false); } catch (error) { console.error(error); showToast("Failed to load flow", "error", { clear: true }); } }; const addBlock = (type) => { const newBlock = { id: `block_${blocks.length}`, type, config: { ...BLOCK_INFO[type].defaultConfig }, isExpanded: true, }; // Insert the new block before the finish block const newBlocks = [...blocks]; newBlocks.splice(newBlocks.length - 1, 0, newBlock); setBlocks(newBlocks); setShowBlockMenu(false); }; const updateBlockConfig = (blockId, config) => { setBlocks( blocks.map((block) => block.id === blockId ? { ...block, config: { ...block.config, ...config } } : block ) ); }; const removeBlock = (blockId) => { if (blockId === "start") return; setBlocks(blocks.filter((block) => block.id !== blockId)); if (selectedBlock === blockId) { setSelectedBlock("start"); } }; const saveFlow = async () => { const flowInfoBlock = blocks.find( (block) => block.type === BLOCK_TYPES.FLOW_INFO ); const name = flowInfoBlock?.config?.name; const description = flowInfoBlock?.config?.description; if (!name?.trim() || !description?.trim()) { // Make sure the flow info block is expanded first if (!flowInfoBlock.isExpanded) { setBlocks( blocks.map((block) => block.type === BLOCK_TYPES.FLOW_INFO ? { ...block, isExpanded: true } : block ) ); // Small delay to allow expansion animation to complete await new Promise((resolve) => setTimeout(resolve, 100)); } if (!name?.trim()) { nameRef.current?.focus(); } else if (!description?.trim()) { descriptionRef.current?.focus(); } showToast( "Please provide both a name and description for your flow", "error", { clear: true, } ); return; } const flowConfig = { name, description, active, steps: blocks .filter( (block) => block.type !== BLOCK_TYPES.FINISH && block.type !== BLOCK_TYPES.FLOW_INFO ) .map((block) => ({ type: block.type, config: block.config, })), }; try { const { success, error, flow } = await AgentFlows.saveFlow( name, flowConfig, currentFlowUuid ); if (!success) throw new Error(error); setCurrentFlowUuid(flow.uuid); showToast("Agent flow saved successfully!", "success", { clear: true }); await loadAvailableFlows(); } catch (error) { console.error("Save error details:", error); showToast(`Failed to save agent flow. ${error.message}`, "error", { clear: true, }); } }; const toggleBlockExpansion = (blockId) => { setBlocks( blocks.map((block) => block.id === blockId ? { ...block, isExpanded: !block.isExpanded } : block ) ); }; // Get all available variables from the start block const getAvailableVariables = () => { const startBlock = blocks.find((b) => b.type === BLOCK_TYPES.START); return startBlock?.config?.variables?.filter((v) => v.name) || []; }; const renderVariableSelect = ( value, onChange, placeholder = "Select variable" ) => ( <select value={value || ""} onChange={(e) => onChange(e.target.value)} className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" > <option value="" className="bg-theme-bg-primary"> {placeholder} </option> {getAvailableVariables().map((v) => ( <option key={v.name} value={v.name} className="bg-theme-bg-primary"> {v.name} </option> ))} </select> ); const deleteVariable = (variableName) => { // Clean up references in other blocks blocks.forEach((block) => { if (block.type === BLOCK_TYPES.START) return; let configUpdated = false; const newConfig = { ...block.config }; // Check and clean responseVariable/resultVariable if (newConfig.responseVariable === variableName) { newConfig.responseVariable = ""; configUpdated = true; } if (newConfig.resultVariable === variableName) { newConfig.resultVariable = ""; configUpdated = true; } if (configUpdated) { updateBlockConfig(block.id, newConfig); } }); }; const clearFlow = () => { if (!!flowId) navigate(paths.agents.builder()); setAgentName(""); setAgentDescription(""); setCurrentFlowUuid(null); setActive(true); setBlocks(DEFAULT_BLOCKS); }; const moveBlock = (fromIndex, toIndex) => { const newBlocks = [...blocks]; const [movedBlock] = newBlocks.splice(fromIndex, 1); newBlocks.splice(toIndex, 0, movedBlock); setBlocks(newBlocks); }; const handlePublishFlow = () => { setShowPublishModal(true); }; const flowInfoBlock = blocks.find( (block) => block.type === BLOCK_TYPES.FLOW_INFO ); const flowEntity = { name: flowInfoBlock?.config?.name || "", description: flowInfoBlock?.config?.description || "", steps: blocks .filter( (block) => block.type !== BLOCK_TYPES.FINISH && block.type !== BLOCK_TYPES.FLOW_INFO ) .map((block) => ({ type: block.type, config: block.config })), }; return ( <div style={{ backgroundImage: theme === "light" ? "radial-gradient(rgba(0, 0, 0, 0.1) 1px, transparent 0)" : "radial-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 0)", backgroundSize: "15px 15px", backgroundPosition: "-7.5px -7.5px", }} className="w-full h-screen flex bg-theme-bg-primary" > <PublishEntityModal show={showPublishModal} onClose={() => setShowPublishModal(false)} entityType="agent-flow" entity={flowEntity} /> <div className="w-full flex flex-col"> <HeaderMenu agentName={agentName} availableFlows={availableFlows} onNewFlow={clearFlow} onSaveFlow={saveFlow} onPublishFlow={handlePublishFlow} /> <div className="flex-1 p-6 overflow-y-auto"> <div className="max-w-xl mx-auto mt-14"> <BlockList blocks={blocks} updateBlockConfig={updateBlockConfig} removeBlock={removeBlock} toggleBlockExpansion={toggleBlockExpansion} renderVariableSelect={renderVariableSelect} onDeleteVariable={deleteVariable} moveBlock={moveBlock} refs={{ nameRef, descriptionRef }} /> <AddBlockMenu blocks={blocks} showBlockMenu={showBlockMenu} setShowBlockMenu={setShowBlockMenu} addBlock={addBlock} /> </div> </div> </div> <Tooltip id="content-summarization-tooltip" place="top" delayShow={300} className="tooltip !text-xs z-99" > <p className="text-sm"> When enabled, long webpage content will be automatically summarized to reduce token usage. <br /> <br /> Note: This may affect data quality and remove specific details from the original content. </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/pages/Admin/AgentBuilder/BlockList/index.jsx
frontend/src/pages/Admin/AgentBuilder/BlockList/index.jsx
import React from "react"; import { X, CaretUp, CaretDown, Globe, Browser, Brain, Flag, Info, BracketsCurly, } from "@phosphor-icons/react"; import { Tooltip } from "react-tooltip"; import StartNode from "../nodes/StartNode"; import ApiCallNode from "../nodes/ApiCallNode"; import WebsiteNode from "../nodes/WebsiteNode"; import FileNode from "../nodes/FileNode"; import CodeNode from "../nodes/CodeNode"; import LLMInstructionNode from "../nodes/LLMInstructionNode"; import FinishNode from "../nodes/FinishNode"; import WebScrapingNode from "../nodes/WebScrapingNode"; import FlowInfoNode from "../nodes/FlowInfoNode"; const BLOCK_TYPES = { FLOW_INFO: "flowInfo", START: "start", API_CALL: "apiCall", // WEBSITE: "website", // Temporarily disabled // FILE: "file", // Temporarily disabled // CODE: "code", // Temporarily disabled LLM_INSTRUCTION: "llmInstruction", WEB_SCRAPING: "webScraping", FINISH: "finish", }; const BLOCK_INFO = { [BLOCK_TYPES.FLOW_INFO]: { label: "Flow Information", icon: <Info className="w-5 h-5 text-theme-text-primary" />, description: "Basic flow information", defaultConfig: { name: "", description: "", }, getSummary: (config) => config.name || "Untitled Flow", }, [BLOCK_TYPES.START]: { label: "Flow Variables", icon: <BracketsCurly className="w-5 h-5 text-theme-text-primary" />, description: "Configure agent variables and settings", getSummary: (config) => { const varCount = config.variables?.filter((v) => v.name)?.length || 0; return `${varCount} variable${varCount !== 1 ? "s" : ""} defined`; }, }, [BLOCK_TYPES.API_CALL]: { label: "API Call", icon: <Globe className="w-5 h-5 text-theme-text-primary" />, description: "Make an HTTP request", defaultConfig: { url: "", method: "GET", headers: [], bodyType: "json", body: "", formData: [], responseVariable: "", directOutput: false, }, getSummary: (config) => `${config.method || "GET"} ${config.url || "(no URL)"}`, }, // TODO: Implement website, file, and code blocks /* [BLOCK_TYPES.WEBSITE]: { label: "Open Website", icon: <Browser className="w-5 h-5 text-theme-text-primary" />, description: "Navigate to a URL", defaultConfig: { url: "", selector: "", action: "read", value: "", resultVariable: "", }, getSummary: (config) => `${config.action || "read"} from ${config.url || "(no URL)"}`, }, [BLOCK_TYPES.FILE]: { label: "Open File", icon: <File className="w-5 h-5 text-theme-text-primary" />, description: "Read or write to a file", defaultConfig: { path: "", operation: "read", content: "", resultVariable: "", }, getSummary: (config) => `${config.operation || "read"} ${config.path || "(no path)"}`, }, [BLOCK_TYPES.CODE]: { label: "Code Execution", icon: <Code className="w-5 h-5 text-theme-text-primary" />, description: "Execute code snippets", defaultConfig: { language: "javascript", code: "", resultVariable: "", }, getSummary: (config) => `Run ${config.language || "javascript"} code`, }, */ [BLOCK_TYPES.LLM_INSTRUCTION]: { label: "LLM Instruction", icon: <Brain className="w-5 h-5 text-theme-text-primary" />, description: "Process data using LLM instructions", defaultConfig: { instruction: "", resultVariable: "", directOutput: false, }, getSummary: (config) => config.instruction || "No instruction", }, [BLOCK_TYPES.WEB_SCRAPING]: { label: "Web Scraping", icon: <Browser className="w-5 h-5 text-theme-text-primary" />, description: "Scrape content from a webpage", defaultConfig: { url: "", captureAs: "text", querySelector: "", resultVariable: "", directOutput: false, }, getSummary: (config) => config.url || "No URL specified", }, [BLOCK_TYPES.FINISH]: { label: "Flow Complete", icon: <Flag className="w-4 h-4" />, description: "End of agent flow", getSummary: () => "Flow will end here", defaultConfig: {}, renderConfig: () => null, }, }; export default function BlockList({ blocks, updateBlockConfig, removeBlock, toggleBlockExpansion, renderVariableSelect, onDeleteVariable, moveBlock, refs, }) { const renderBlockConfig = (block) => { const isLastConfigurableBlock = blocks[blocks.length - 2]?.id === block.id; const props = { config: block.config, onConfigChange: (config) => updateBlockConfig(block.id, config), renderVariableSelect, onDeleteVariable, }; // Direct output switch to the last configurable block before finish if ( isLastConfigurableBlock && block.type !== BLOCK_TYPES.START && block.type !== BLOCK_TYPES.FLOW_INFO ) { return ( <div className="space-y-4"> {renderBlockConfigContent(block, props)} <div className="flex justify-between items-center pt-4 border-t border-white/10"> <div> <label className="block text-sm font-medium text-theme-text-primary"> Direct Output </label> <p className="text-xs text-theme-text-secondary"> The output of this block will be returned directly to the chat. <br /> This will prevent any further tool calls from being executed. </p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={props.config.directOutput || false} onChange={(e) => props.onConfigChange({ ...props.config, directOutput: e.target.checked, }) } className="peer sr-only" aria-label="Toggle direct output" /> <div className="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> </label> </div> </div> ); } return renderBlockConfigContent(block, props); }; const renderBlockConfigContent = (block, props) => { switch (block.type) { case BLOCK_TYPES.FLOW_INFO: return <FlowInfoNode {...props} ref={refs} />; case BLOCK_TYPES.START: return <StartNode {...props} />; case BLOCK_TYPES.API_CALL: return <ApiCallNode {...props} />; case BLOCK_TYPES.WEBSITE: return <WebsiteNode {...props} />; case BLOCK_TYPES.FILE: return <FileNode {...props} />; case BLOCK_TYPES.CODE: return <CodeNode {...props} />; case BLOCK_TYPES.LLM_INSTRUCTION: return <LLMInstructionNode {...props} />; case BLOCK_TYPES.WEB_SCRAPING: return <WebScrapingNode {...props} />; case BLOCK_TYPES.FINISH: return <FinishNode />; default: return <div>Configuration options coming soon...</div>; } }; return ( <div className="space-y-1"> {blocks.map((block, index) => ( <div key={block.id} className="flex flex-col"> <div className={`bg-theme-action-menu-bg border border-white/10 rounded-lg overflow-hidden transition-all duration-300 ${ block.isExpanded ? "w-full" : "w-[280px] mx-auto" }`} > <div onClick={() => toggleBlockExpansion(block.id)} className="w-full p-4 flex items-center justify-between hover:bg-theme-action-menu-item-hover transition-colors duration-300 group cursor-pointer" > <div className="flex items-center gap-3"> <div className="w-7 h-7 rounded-lg bg-white/10 light:bg-white flex items-center justify-center"> {React.cloneElement(BLOCK_INFO[block.type].icon, { className: "w-4 h-4 text-white", })} </div> <div className="flex-1 text-left min-w-0 max-w-[115px]"> <span className="text-sm font-medium text-white block"> {BLOCK_INFO[block.type].label} </span> {!block.isExpanded && ( <p className="text-xs text-white/60 truncate"> {BLOCK_INFO[block.type].getSummary(block.config)} </p> )} </div> </div> <div className="flex items-center"> {block.id !== "start" && block.type !== BLOCK_TYPES.FINISH && block.type !== BLOCK_TYPES.FLOW_INFO && ( <div className="flex items-center gap-1"> {index > 2 && ( <button onClick={(e) => { e.stopPropagation(); moveBlock(index, index - 1); }} className="w-7 h-7 flex items-center justify-center rounded-lg bg-theme-bg-primary border border-white/5 text-white hover:bg-theme-action-menu-item-hover transition-colors duration-300" data-tooltip-id="block-action" data-tooltip-content="Move block up" > <CaretUp className="w-3.5 h-3.5" /> </button> )} {index < blocks.length - 2 && ( <button onClick={(e) => { e.stopPropagation(); moveBlock(index, index + 1); }} className="w-7 h-7 flex items-center justify-center rounded-lg bg-theme-bg-primary border border-white/5 text-white hover:bg-theme-action-menu-item-hover transition-colors duration-300" data-tooltip-id="block-action" data-tooltip-content="Move block down" > <CaretDown className="w-3.5 h-3.5" /> </button> )} <button onClick={(e) => { e.stopPropagation(); removeBlock(block.id); }} className="w-7 h-7 flex items-center justify-center rounded-lg bg-theme-bg-primary border border-white/5 text-red-400 hover:bg-red-500/10 hover:border-red-500/20 transition-colors duration-300" data-tooltip-id="block-action" data-tooltip-content="Delete block" > <X className="w-3.5 h-3.5" /> </button> </div> )} </div> </div> <div className={`overflow-hidden transition-all duration-300 ease-in-out ${ block.isExpanded ? "max-h-[1000px] opacity-100" : "max-h-0 opacity-0" }`} > <div className="border-t border-white/10 p-4 bg-theme-bg-secondary rounded-b-lg"> {renderBlockConfig(block)} </div> </div> </div> {index < blocks.length - 1 && ( <div className="flex justify-center my-1"> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="text-white/40 light:invert" > <path d="M12 4L12 20M12 20L6 14M12 20L18 14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> </svg> </div> )} </div> ))} <Tooltip id="block-action" place="bottom" delayShow={300} className="tooltip !text-xs" /> </div> ); } export { BLOCK_TYPES, BLOCK_INFO };
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/pages/Admin/AgentBuilder/AddBlockMenu/index.jsx
frontend/src/pages/Admin/AgentBuilder/AddBlockMenu/index.jsx
import React, { useRef, useEffect } from "react"; import { Plus, CaretDown } from "@phosphor-icons/react"; import { BLOCK_TYPES, BLOCK_INFO } from "../BlockList"; /** * Check if the last configurable block has direct output disabled or undefined * If this property is true then you cannot add a new block after it. * @param {Array} blocks - The blocks array * @returns {Boolean} True if the last configurable block has direct output disabled, false otherwise */ function checkIfCanAddBlock(blocks) { const lastConfigurableBlock = blocks[blocks.length - 2]; if (!lastConfigurableBlock) return true; return ( lastConfigurableBlock?.config?.directOutput === false || lastConfigurableBlock?.config?.directOutput === undefined ); } export default function AddBlockMenu({ blocks, showBlockMenu, setShowBlockMenu, addBlock, }) { const menuRef = useRef(null); useEffect(() => { function handleClickOutside(event) { if (menuRef.current && !menuRef.current.contains(event.target)) { setShowBlockMenu(false); } } document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [setShowBlockMenu]); if (checkIfCanAddBlock(blocks) === false) return null; return ( <div className="relative mt-4 w-[280px] mx-auto pb-[50%]" ref={menuRef}> <button onClick={() => setShowBlockMenu(!showBlockMenu)} className="transition-all duration-300 w-full p-2.5 bg-theme-action-menu-bg hover:bg-theme-action-menu-item-hover border border-white/10 rounded-lg text-white flex items-center justify-center gap-2 text-sm font-medium" > <Plus className="w-4 h-4" /> Add Block <CaretDown className={`w-3.5 h-3.5 transition-transform duration-300 ${showBlockMenu ? "rotate-180" : ""}`} /> </button> {showBlockMenu && ( <div className="absolute left-0 right-0 mt-2 bg-theme-action-menu-bg border border-white/10 rounded-lg shadow-lg overflow-hidden z-10 animate-fadeUpIn"> {Object.entries(BLOCK_INFO).map( ([type, info]) => type !== BLOCK_TYPES.START && type !== BLOCK_TYPES.FINISH && type !== BLOCK_TYPES.FLOW_INFO && ( <button key={type} onClick={() => { addBlock(type); setShowBlockMenu(false); }} className="w-full p-2.5 flex items-center gap-3 hover:bg-theme-action-menu-item-hover text-white transition-colors duration-300 group" > <div className="w-7 h-7 rounded-lg bg-white/10 flex items-center justify-center"> <div className="w-fit h-fit text-white">{info.icon}</div> </div> <div className="text-left flex-1"> <div className="text-sm font-medium">{info.label}</div> <div className="text-xs text-white/60"> {info.description} </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/pages/Admin/AgentBuilder/nodes/FileNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/FileNode/index.jsx
import React from "react"; export default function FileNode({ config, onConfigChange, renderVariableSelect, }) { return ( <div className="space-y-4"> <div> <label className="block text-sm font-medium text-white mb-2"> Operation </label> <select value={config.operation} onChange={(e) => onConfigChange({ operation: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-white focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none" > <option value="read" className="bg-theme-bg-primary"> Read File </option> <option value="write" className="bg-theme-bg-primary"> Write File </option> <option value="append" className="bg-theme-bg-primary"> Append to File </option> </select> </div> <div> <label className="block text-sm font-medium text-white mb-2"> File Path </label> <input type="text" placeholder="/path/to/file" value={config.path} onChange={(e) => onConfigChange({ path: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-white placeholder:text-white/20 focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none" autoComplete="off" spellCheck={false} /> </div> {config.operation !== "read" && ( <div> <label className="block text-sm font-medium text-white mb-2"> Content </label> <textarea placeholder="File content..." value={config.content} onChange={(e) => onConfigChange({ content: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-white placeholder:text-white/20 focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none" rows={3} autoComplete="off" spellCheck={false} /> </div> )} <div> <label className="block text-sm font-medium text-white mb-2"> Store Result In </label> {renderVariableSelect( config.resultVariable, (value) => onConfigChange({ resultVariable: value }), "Select or create variable" )} </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/pages/Admin/AgentBuilder/nodes/WebScrapingNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/WebScrapingNode/index.jsx
import { Info } from "@phosphor-icons/react"; import React from "react"; export default function WebScrapingNode({ config, onConfigChange, renderVariableSelect, }) { return ( <div className="space-y-4"> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> URL to Scrape </label> <input type="url" value={config?.url || ""} onChange={(e) => onConfigChange({ ...config, url: e.target.value, }) } className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" placeholder="https://example.com" /> </div> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Capture Page Content As </label> <select value={config.captureAs} onChange={(e) => onConfigChange({ ...config, captureAs: e.target.value }) } className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" > {[ { label: "Text content only", value: "text" }, { label: "Raw HTML", value: "html" }, { label: "CSS Query Selector", value: "querySelector" }, ].map((captureAs) => ( <option key={captureAs.value} value={captureAs.value} className="bg-theme-settings-input-bg" > {captureAs.label} </option> ))} </select> </div> {config.captureAs === "querySelector" && ( <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Query Selector </label> <p className="text-xs text-theme-text-secondary mb-2"> Enter a valid CSS selector to scrape the content of the page. </p> <input value={config.querySelector} onChange={(e) => onConfigChange({ ...config, querySelector: e.target.value }) } placeholder=".article-content, #content, .main-content, etc." className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" /> </div> )} <div className="flex justify-between items-center"> <div className="flex flex-row items-center gap-x-1 mb-2"> <label className="block text-sm font-medium text-theme-text-primary"> Content Summarization </label> <Info size={16} className="text-theme-text-secondary cursor-pointer" data-tooltip-id="content-summarization-tooltip" /> </div> <div className="flex items-center gap-2 mb-2"> <label className="relative inline-flex items-center cursor-pointer"> <input type="checkbox" checked={config.enableSummarization ?? true} onChange={(e) => onConfigChange({ ...config, enableSummarization: e.target.checked, }) } className="sr-only peer" aria-label="Toggle content summarization" /> <div className="w-11 h-6 bg-theme-settings-input-bg peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-button/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-button"></div> </label> </div> </div> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Result Variable </label> {renderVariableSelect( config.resultVariable, (value) => onConfigChange({ ...config, resultVariable: value }), "Select or create variable", true )} </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/pages/Admin/AgentBuilder/nodes/WebsiteNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/WebsiteNode/index.jsx
import React from "react"; export default function WebsiteNode({ config, onConfigChange, renderVariableSelect, }) { return ( <div className="space-y-4"> <div> <label className="block text-sm font-medium text-white mb-2">URL</label> <input type="text" placeholder="https://example.com" value={config.url} onChange={(e) => onConfigChange({ url: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-white placeholder:text-white/20 focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none" autoComplete="off" spellCheck={false} /> </div> <div> <label className="block text-sm font-medium text-white mb-2"> Action </label> <select value={config.action} onChange={(e) => onConfigChange({ action: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-white focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none" > <option value="read" className="bg-theme-bg-primary"> Read Content </option> <option value="click" className="bg-theme-bg-primary"> Click Element </option> <option value="type" className="bg-theme-bg-primary"> Type Text </option> </select> </div> <div> <label className="block text-sm font-medium text-white mb-2"> CSS Selector </label> <input type="text" placeholder="#element-id or .class-name" value={config.selector} onChange={(e) => onConfigChange({ selector: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-white placeholder:text-white/20 focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none" autoComplete="off" spellCheck={false} /> </div> <div> <label className="block text-sm font-medium text-white mb-2"> Store Result In </label> {renderVariableSelect( config.resultVariable, (value) => onConfigChange({ resultVariable: value }), "Select or create variable" )} </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/pages/Admin/AgentBuilder/nodes/FlowInfoNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/FlowInfoNode/index.jsx
import React, { forwardRef } from "react"; const FlowInfoNode = forwardRef(({ config, onConfigChange }, refs) => { return ( <div className="space-y-4"> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Flow Name </label> <div className="flex flex-col text-xs text-theme-text-secondary mt-2 mb-3"> <p className=""> It is important to give your flow a name that an LLM can easily understand. </p> <p>"SendMessageToDiscord", "CheckStockPrice", "CheckWeather"</p> </div> <input id="agent-flow-name-input" ref={refs?.nameRef} type="text" placeholder="Enter flow name" value={config?.name || ""} onChange={(e) => onConfigChange({ ...config, name: e.target.value, }) } className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" autoComplete="off" spellCheck={false} /> </div> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Description </label> <div className="flex flex-col text-xs text-theme-text-secondary mt-2 mb-3"> <p className=""> It is equally important to give your flow a description that an LLM can easily understand. Be sure to include the purpose of the flow, the context it will be used in, and any other relevant information. </p> </div> <textarea ref={refs?.descriptionRef} value={config?.description || ""} onChange={(e) => onConfigChange({ ...config, description: e.target.value, }) } className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" rows={3} placeholder="Enter flow description" /> </div> </div> ); }); FlowInfoNode.displayName = "FlowInfoNode"; export default FlowInfoNode;
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/pages/Admin/AgentBuilder/nodes/StartNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/StartNode/index.jsx
import React from "react"; import { Plus, X } from "@phosphor-icons/react"; export default function StartNode({ config, onConfigChange, onDeleteVariable, }) { const handleDeleteVariable = (index, variableName) => { // First clean up references, then delete the variable onDeleteVariable(variableName); const newVars = config.variables.filter((_, i) => i !== index); onConfigChange({ variables: newVars }); }; return ( <div className="space-y-4"> <h3 className="text-sm font-medium text-theme-text-primary">Variables</h3> {config.variables.map((variable, index) => ( <div key={index} className="flex gap-2"> <input type="text" placeholder="Variable name" value={variable.name} onChange={(e) => { const newVars = [...config.variables]; newVars[index].name = e.target.value; onConfigChange({ variables: newVars }); }} className="flex-1 border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" autoComplete="off" spellCheck={false} /> <input type="text" placeholder="Initial value" value={variable.value} onChange={(e) => { const newVars = [...config.variables]; newVars[index].value = e.target.value; onConfigChange({ variables: newVars }); }} className="flex-1 border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" autoComplete="off" spellCheck={false} /> {config.variables.length > 1 && ( <button onClick={() => handleDeleteVariable(index, variable.name)} className="p-2.5 rounded-lg border-none bg-theme-settings-input-bg text-theme-text-primary hover:text-red-500 hover:border-red-500/20 hover:bg-red-500/10 transition-colors duration-300" title="Delete variable" > <X className="w-4 h-4" /> </button> )} {index === config.variables.length - 1 && ( <button onClick={() => { const newVars = [...config.variables, { name: "", value: "" }]; onConfigChange({ variables: newVars }); }} className="p-2.5 rounded-lg border-none bg-theme-settings-input-bg text-theme-text-primary hover:bg-theme-action-menu-item-hover transition-colors duration-300" title="Add variable" > <Plus className="w-4 h-4" /> </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/pages/Admin/AgentBuilder/nodes/CodeNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/CodeNode/index.jsx
import React from "react"; export default function CodeNode({ config, onConfigChange, renderVariableSelect, }) { return ( <div className="space-y-4"> <div> <label className="block text-sm font-medium text-white mb-2"> Language </label> <select value={config.language} onChange={(e) => onConfigChange({ language: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-white focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none" > <option value="javascript" className="bg-theme-bg-primary"> JavaScript </option> <option value="python" className="bg-theme-bg-primary"> Python </option> <option value="shell" className="bg-theme-bg-primary"> Shell </option> </select> </div> <div> <label className="block text-sm font-medium text-white mb-2"> Code </label> <textarea placeholder="Enter code..." value={config.code} onChange={(e) => onConfigChange({ code: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-white placeholder:text-white/20 focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none font-mono" rows={5} autoComplete="off" spellCheck={false} /> </div> <div> <label className="block text-sm font-medium text-white mb-2"> Store Result In </label> {renderVariableSelect( config.resultVariable, (value) => onConfigChange({ resultVariable: value }), "Select or create variable" )} </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/pages/Admin/AgentBuilder/nodes/FinishNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/FinishNode/index.jsx
import React from "react"; export default function FinishNode() { return ( <div className="text-sm text-white/60"> This is the end of your agent flow. All steps above will be executed in sequence. </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/pages/Admin/AgentBuilder/nodes/ApiCallNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/ApiCallNode/index.jsx
import React, { useRef, useState } from "react"; import { Plus, X, CaretDown } from "@phosphor-icons/react"; export default function ApiCallNode({ config, onConfigChange, renderVariableSelect, }) { const urlInputRef = useRef(null); const [showVarMenu, setShowVarMenu] = useState(false); const varButtonRef = useRef(null); const handleHeaderChange = (index, field, value) => { const newHeaders = [...(config.headers || [])]; newHeaders[index] = { ...newHeaders[index], [field]: value }; onConfigChange({ headers: newHeaders }); }; const addHeader = () => { const newHeaders = [...(config.headers || []), { key: "", value: "" }]; onConfigChange({ headers: newHeaders }); }; const removeHeader = (index) => { const newHeaders = [...(config.headers || [])].filter( (_, i) => i !== index ); onConfigChange({ headers: newHeaders }); }; const insertVariableAtCursor = (variableName) => { if (!urlInputRef.current) return; const input = urlInputRef.current; const start = input.selectionStart; const end = input.selectionEnd; const currentValue = config.url; const newValue = currentValue.substring(0, start) + "${" + variableName + "}" + currentValue.substring(end); onConfigChange({ url: newValue }); setShowVarMenu(false); // Set cursor position after the inserted variable setTimeout(() => { const newPosition = start + variableName.length + 3; // +3 for ${} input.setSelectionRange(newPosition, newPosition); input.focus(); }, 0); }; return ( <div className="space-y-4"> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> URL </label> <div className="flex gap-2"> <input ref={urlInputRef} type="text" placeholder="https://api.example.com/endpoint" value={config.url} onChange={(e) => onConfigChange({ url: e.target.value })} className="flex-1 border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" autoComplete="off" spellCheck={false} /> <div className="relative"> <button ref={varButtonRef} onClick={() => setShowVarMenu(!showVarMenu)} className="h-full px-3 rounded-lg border-none bg-theme-settings-input-bg text-theme-text-primary hover:bg-theme-action-menu-item-hover transition-colors duration-300 flex items-center gap-1" title="Insert variable" > <Plus className="w-4 h-4" /> <CaretDown className="w-3 h-3" /> </button> {showVarMenu && ( <div className="absolute right-0 top-[calc(100%+4px)] w-48 bg-theme-settings-input-bg border-none rounded-lg shadow-lg z-10"> {renderVariableSelect( "", insertVariableAtCursor, "Select variable to insert", true )} </div> )} </div> </div> </div> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Method </label> <select value={config.method} onChange={(e) => onConfigChange({ method: e.target.value })} className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" > {["GET", "POST", "DELETE", "PUT", "PATCH"].map((method) => ( <option key={method} value={method} className="bg-theme-settings-input-bg" > {method} </option> ))} </select> </div> <div> <div className="flex items-center justify-between mb-2"> <label className="text-sm font-medium text-theme-text-primary"> Headers </label> <button onClick={addHeader} className="p-1.5 rounded-lg border-none bg-theme-settings-input-bg text-theme-text-primary hover:bg-theme-action-menu-item-hover transition-colors duration-300" title="Add header" > <Plus className="w-3.5 h-3.5" /> </button> </div> <div className="space-y-2"> {(config.headers || []).map((header, index) => ( <div key={index} className="flex gap-2"> <input type="text" placeholder="Header name" value={header.key} onChange={(e) => handleHeaderChange(index, "key", e.target.value) } className="flex-1 border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" autoComplete="off" spellCheck={false} /> <input type="text" placeholder="Value" value={header.value} onChange={(e) => handleHeaderChange(index, "value", e.target.value) } className="flex-1 border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" autoComplete="off" spellCheck={false} /> <button onClick={() => removeHeader(index)} className="p-2.5 rounded-lg border-none bg-theme-settings-input-bg text-theme-text-primary hover:text-red-500 hover:border-red-500/20 hover:bg-red-500/10 transition-colors duration-300" title="Remove header" > <X className="w-4 h-4" /> </button> </div> ))} </div> </div> {["POST", "PUT", "PATCH"].includes(config.method) && ( <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Request Body </label> <div className="space-y-2"> <select value={config.bodyType || "json"} onChange={(e) => onConfigChange({ bodyType: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-theme-text-primary focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none light:bg-theme-settings-input-bg light:border-black/10" > <option value="json" className="bg-theme-bg-primary light:bg-theme-settings-input-bg" > JSON </option> <option value="text" className="bg-theme-bg-primary light:bg-theme-settings-input-bg" > Raw Text </option> <option value="form" className="bg-theme-bg-primary light:bg-theme-settings-input-bg" > Form Data </option> </select> {config.bodyType === "json" ? ( <textarea placeholder='{"key": "value"}' value={config.body} onChange={(e) => onConfigChange({ body: e.target.value })} className="w-full p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-theme-text-primary placeholder:text-theme-text-secondary/20 focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none light:bg-theme-settings-input-bg light:border-black/10 font-mono" rows={4} autoComplete="off" spellCheck={false} /> ) : config.bodyType === "form" ? ( <div className="space-y-2"> {(config.formData || []).map((item, index) => ( <div key={index} className="flex gap-2"> <input type="text" placeholder="Key" value={item.key} onChange={(e) => { const newFormData = [...(config.formData || [])]; newFormData[index] = { ...item, key: e.target.value }; onConfigChange({ formData: newFormData }); }} className="flex-1 p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-theme-text-primary placeholder:text-theme-text-secondary/20 focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none light:bg-theme-settings-input-bg light:border-black/10" autoComplete="off" spellCheck={false} /> <input type="text" placeholder="Value" value={item.value} onChange={(e) => { const newFormData = [...(config.formData || [])]; newFormData[index] = { ...item, value: e.target.value }; onConfigChange({ formData: newFormData }); }} className="flex-1 p-2.5 text-sm rounded-lg bg-theme-bg-primary border border-white/5 text-theme-text-primary placeholder:text-theme-text-secondary/20 focus:border-primary-button focus:ring-1 focus:ring-primary-button outline-none light:bg-theme-settings-input-bg light:border-black/10" autoComplete="off" spellCheck={false} /> <button onClick={() => { const newFormData = [...(config.formData || [])].filter( (_, i) => i !== index ); onConfigChange({ formData: newFormData }); }} className="p-2.5 rounded-lg bg-theme-bg-primary border border-white/5 text-theme-text-primary hover:text-red-500 hover:border-red-500/20 hover:bg-red-500/10 transition-colors duration-300 light:bg-theme-settings-input-bg light:border-black/10" title="Remove field" > <X className="w-4 h-4" /> </button> </div> ))} <button onClick={() => { const newFormData = [ ...(config.formData || []), { key: "", value: "" }, ]; onConfigChange({ formData: newFormData }); }} className="w-full p-2.5 rounded-lg border-none bg-theme-settings-input-bg text-theme-text-primary hover:bg-theme-action-menu-item-hover transition-colors duration-300 text-sm" > Add Form Field </button> </div> ) : ( <textarea placeholder="Raw request body..." value={config.body} onChange={(e) => onConfigChange({ body: e.target.value })} className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" rows={4} autoComplete="off" spellCheck={false} /> )} </div> </div> )} <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Store Response In </label> {renderVariableSelect( config.responseVariable, (value) => onConfigChange({ responseVariable: value }), "Select or create variable" )} </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/pages/Admin/AgentBuilder/nodes/LLMInstructionNode/index.jsx
frontend/src/pages/Admin/AgentBuilder/nodes/LLMInstructionNode/index.jsx
import React from "react"; export default function LLMInstructionNode({ config, onConfigChange, renderVariableSelect, }) { return ( <div className="space-y-4"> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Instruction </label> <textarea value={config?.instruction || ""} onChange={(e) => onConfigChange({ ...config, instruction: e.target.value, }) } className="w-full border-none bg-theme-settings-input-bg text-theme-text-primary placeholder:text-theme-settings-input-placeholder text-sm rounded-lg focus:outline-primary-button active:outline-primary-button outline-none p-2.5" rows={3} placeholder="Enter instructions for the LLM..." /> </div> <div> <label className="block text-sm font-medium text-theme-text-primary mb-2"> Result Variable </label> {renderVariableSelect( config.resultVariable, (value) => onConfigChange({ ...config, resultVariable: value }), "Select or create variable", true )} </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/pages/Admin/AgentBuilder/HeaderMenu/index.jsx
frontend/src/pages/Admin/AgentBuilder/HeaderMenu/index.jsx
import { CaretDown, CaretUp, Plus, CaretLeft } from "@phosphor-icons/react"; import AnythingInfinityLogo from "@/media/logo/anything-llm-infinity.png"; import { useState, useRef, useEffect } from "react"; import { useNavigate, useParams } from "react-router-dom"; import paths from "@/utils/paths"; import { Link } from "react-router-dom"; export default function HeaderMenu({ agentName, availableFlows = [], onNewFlow, onSaveFlow, onPublishFlow, }) { const { flowId = null } = useParams(); const [showDropdown, setShowDropdown] = useState(false); const navigate = useNavigate(); const dropdownRef = useRef(null); const hasOtherFlows = availableFlows.filter((flow) => flow.uuid !== flowId).length > 0; useEffect(() => { function handleClickOutside(event) { if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { setShowDropdown(false); } } document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); return ( <div className="absolute top-[calc(40px+16px)] left-4 right-4"> <div className="flex justify-between items-start max-w-[1700px] mx-auto"> <div className="flex items-center gap-x-2"> <button onClick={() => navigate(paths.settings.agentSkills())} className="w-8 h-8 flex items-center justify-center rounded-full bg-theme-settings-input-bg border border-white/10 hover:bg-theme-action-menu-bg transition-colors duration-300" > <CaretLeft weight="bold" className="w-5 h-5 text-theme-text-primary" /> </button> <div className="flex items-center bg-theme-settings-input-bg rounded-md border border-white/10 pointer-events-auto" ref={dropdownRef} > <button onClick={() => navigate(paths.settings.agentSkills())} className="!border-t-transparent !border-l-transparent !border-b-transparent flex items-center gap-x-2 px-4 py-2 border-r border-white/10 hover:bg-theme-action-menu-bg transition-colors duration-300" > <img src={AnythingInfinityLogo} alt="logo" className="w-[20px] light:invert" /> <span className="text-theme-text-primary text-sm uppercase tracking-widest"> Builder </span> </button> <div className="relative"> <button disabled={!hasOtherFlows} className="border-none flex items-center justify-between gap-x-1 text-theme-text-primary text-sm px-4 py-2 enabled:hover:bg-theme-action-menu-bg transition-colors duration-300 min-w-[200px] max-w-[300px]" onClick={() => { if (!agentName && !hasOtherFlows) { const agentNameInput = document.getElementById( "agent-flow-name-input" ); if (agentNameInput) agentNameInput.focus(); return; } setShowDropdown(!showDropdown); }} > <span className={`text-sm font-medium truncate ${!!agentName ? "text-theme-text-primary " : "text-theme-text-secondary"}`} > {agentName || "Untitled Flow"} </span> {hasOtherFlows && ( <div className="flex flex-col ml-2 shrink-0"> <CaretUp size={10} /> <CaretDown size={10} /> </div> )} </button> {showDropdown && ( <div className="absolute top-full left-0 mt-1 w-full min-w-[200px] max-w-[350px] bg-theme-settings-input-bg border border-white/10 rounded-md shadow-lg z-50 animate-fadeUpIn"> {availableFlows .filter((flow) => flow.uuid !== flowId) .map((flow) => ( <button key={flow?.uuid || Math.random()} onClick={() => { navigate(paths.agents.editAgent(flow.uuid)); setShowDropdown(false); }} className="border-none w-full text-left px-2 py-1 text-sm text-theme-text-primary hover:bg-theme-action-menu-bg transition-colors duration-300" > <span className="block truncate"> {flow?.name || "Untitled Flow"} </span> </button> ))} </div> )} </div> </div> </div> <div className="flex flex-col gap-y-1 items-end"> <div className="flex items-center gap-x-[15px]"> <button onClick={onNewFlow} className="flex items-center gap-x-2 text-theme-text-primary text-sm font-medium px-3 py-2 rounded-lg border border-white bg-theme-settings-input-bg hover:bg-theme-action-menu-bg transition-colors duration-300" > <Plus className="w-4 h-4" /> New Flow </button> <button onClick={onPublishFlow} className="px-3 py-2 rounded-lg text-sm font-medium flex items-center justify-center gap-2 border border-white/10 bg-theme-bg-primary text-theme-text-primary hover:bg-theme-action-menu-bg transition-all duration-300" > Publish </button> <button onClick={onSaveFlow} className="border-none bg-primary-button hover:opacity-80 text-black light:text-white px-3 py-2 rounded-lg text-sm font-medium transition-all duration-300 flex items-center justify-center gap-2" > Save </button> </div> <Link to="https://docs.anythingllm.com/agent-flows/overview" className="text-theme-text-secondary text-sm hover:underline hover:text-cta-button flex items-center gap-x-1 w-fit float-right" > view documentation &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/pages/Admin/Agents/index.jsx
frontend/src/pages/Admin/Agents/index.jsx
import { useEffect, useRef, useState } from "react"; import Sidebar from "@/components/SettingsSidebar"; import { isMobile } from "react-device-detect"; import Admin from "@/models/admin"; import System from "@/models/system"; import showToast from "@/utils/toast"; import { CaretLeft, CaretRight, Plug, Robot, Hammer, FlowArrow, } from "@phosphor-icons/react"; import ContextualSaveBar from "@/components/ContextualSaveBar"; import { castToType } from "@/utils/types"; import { FullScreenLoader } from "@/components/Preloader"; import { defaultSkills, configurableSkills } from "./skills"; import { DefaultBadge } from "./Badges/default"; import ImportedSkillList from "./Imported/SkillList"; import ImportedSkillConfig from "./Imported/ImportedSkillConfig"; import { Tooltip } from "react-tooltip"; import AgentFlowsList from "./AgentFlows"; import FlowPanel from "./AgentFlows/FlowPanel"; import { MCPServersList, MCPServerHeader } from "./MCPServers"; import ServerPanel from "./MCPServers/ServerPanel"; import { Link } from "react-router-dom"; import paths from "@/utils/paths"; import AgentFlows from "@/models/agentFlows"; export default function AdminAgents() { const formEl = useRef(null); const [hasChanges, setHasChanges] = useState(false); const [settings, setSettings] = useState({}); const [selectedSkill, setSelectedSkill] = useState(""); const [loading, setLoading] = useState(true); const [showSkillModal, setShowSkillModal] = useState(false); const [agentSkills, setAgentSkills] = useState([]); const [importedSkills, setImportedSkills] = useState([]); const [disabledAgentSkills, setDisabledAgentSkills] = useState([]); const [agentFlows, setAgentFlows] = useState([]); const [selectedFlow, setSelectedFlow] = useState(null); const [activeFlowIds, setActiveFlowIds] = useState([]); // MCP Servers are lazy loaded to not block the UI thread const [mcpServers, setMcpServers] = useState([]); const [selectedMcpServer, setSelectedMcpServer] = useState(null); // Alert user if they try to leave the page with unsaved changes useEffect(() => { const handleBeforeUnload = (event) => { if (hasChanges) { event.preventDefault(); event.returnValue = ""; } }; window.addEventListener("beforeunload", handleBeforeUnload); return () => { window.removeEventListener("beforeunload", handleBeforeUnload); }; }, [hasChanges]); useEffect(() => { async function fetchSettings() { const _settings = await System.keys(); const _preferences = await Admin.systemPreferencesByFields([ "disabled_agent_skills", "default_agent_skills", "imported_agent_skills", "active_agent_flows", ]); const { flows = [] } = await AgentFlows.listFlows(); setSettings({ ..._settings, preferences: _preferences.settings } ?? {}); setAgentSkills(_preferences.settings?.default_agent_skills ?? []); setDisabledAgentSkills( _preferences.settings?.disabled_agent_skills ?? [] ); setImportedSkills(_preferences.settings?.imported_agent_skills ?? []); setActiveFlowIds(_preferences.settings?.active_agent_flows ?? []); setAgentFlows(flows); setLoading(false); } fetchSettings(); }, []); const toggleDefaultSkill = (skillName) => { setDisabledAgentSkills((prev) => { const updatedSkills = prev.includes(skillName) ? prev.filter((name) => name !== skillName) : [...prev, skillName]; setHasChanges(true); return updatedSkills; }); }; const toggleAgentSkill = (skillName) => { setAgentSkills((prev) => { const updatedSkills = prev.includes(skillName) ? prev.filter((name) => name !== skillName) : [...prev, skillName]; setHasChanges(true); return updatedSkills; }); }; const toggleFlow = (flowId) => { setActiveFlowIds((prev) => { const updatedFlows = prev.includes(flowId) ? prev.filter((id) => id !== flowId) : [...prev, flowId]; return updatedFlows; }); }; const toggleMCP = (serverName) => { setMcpServers((prev) => { return prev.map((server) => { if (server.name !== serverName) return server; return { ...server, running: !server.running }; }); }); }; const handleSubmit = async (e) => { e.preventDefault(); const data = { workspace: {}, system: {}, env: {}, }; const form = new FormData(formEl.current); for (var [key, value] of form.entries()) { if (key.startsWith("system::")) { const [_, label] = key.split("system::"); data.system[label] = String(value); continue; } if (key.startsWith("env::")) { const [_, label] = key.split("env::"); data.env[label] = String(value); continue; } data.workspace[key] = castToType(key, value); } const { success } = await Admin.updateSystemPreferences(data.system); await System.updateSystem(data.env); if (success) { const _settings = await System.keys(); const _preferences = await Admin.systemPreferencesByFields([ "disabled_agent_skills", "default_agent_skills", "imported_agent_skills", ]); setSettings({ ..._settings, preferences: _preferences.settings } ?? {}); setAgentSkills(_preferences.settings?.default_agent_skills ?? []); setDisabledAgentSkills( _preferences.settings?.disabled_agent_skills ?? [] ); setImportedSkills(_preferences.settings?.imported_agent_skills ?? []); showToast(`Agent preferences saved successfully.`, "success", { clear: true, }); } else { showToast(`Agent preferences failed to save.`, "error", { clear: true }); } setHasChanges(false); }; let SelectedSkillComponent = null; if (selectedFlow) { SelectedSkillComponent = FlowPanel; } else if (selectedMcpServer) { SelectedSkillComponent = ServerPanel; } else if (selectedSkill?.imported) { SelectedSkillComponent = ImportedSkillConfig; } else if (configurableSkills[selectedSkill]) { SelectedSkillComponent = configurableSkills[selectedSkill]?.component; } else { SelectedSkillComponent = defaultSkills[selectedSkill]?.component; } // Update the click handlers to clear the other selection const handleDefaultSkillClick = (skill) => { setSelectedFlow(null); setSelectedMcpServer(null); setSelectedSkill(skill); if (isMobile) setShowSkillModal(true); }; const handleSkillClick = (skill) => { setSelectedFlow(null); setSelectedMcpServer(null); setSelectedSkill(skill); if (isMobile) setShowSkillModal(true); }; const handleFlowClick = (flow) => { setSelectedSkill(null); setSelectedMcpServer(null); setSelectedFlow(flow); if (isMobile) setShowSkillModal(true); }; const handleMCPClick = (server) => { setSelectedSkill(null); setSelectedFlow(null); setSelectedMcpServer(server); if (isMobile) setShowSkillModal(true); }; const handleFlowDelete = (flowId) => { setSelectedFlow(null); setActiveFlowIds((prev) => prev.filter((id) => id !== flowId)); setAgentFlows((prev) => prev.filter((flow) => flow.uuid !== flowId)); }; const handleMCPServerDelete = (serverName) => { setSelectedMcpServer(null); setMcpServers((prev) => prev.filter((server) => server.name !== serverName) ); }; if (loading) { return ( <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] w-full h-full flex justify-center items-center" > <FullScreenLoader /> </div> ); } if (isMobile) { return ( <SkillLayout hasChanges={hasChanges} handleCancel={() => setHasChanges(false)} handleSubmit={handleSubmit} > <form onSubmit={handleSubmit} onChange={() => !selectedFlow && setHasChanges(true)} ref={formEl} className="flex flex-col w-full p-4 mt-10" > <input name="system::default_agent_skills" type="hidden" value={agentSkills.join(",")} /> <input name="system::disabled_agent_skills" type="hidden" value={disabledAgentSkills.join(",")} /> {/* Skill settings nav */} <div hidden={showSkillModal} className="flex flex-col gap-y-[18px] overflow-y-scroll no-scroll" > <div className="text-theme-text-primary flex items-center gap-x-2"> <Robot size={24} /> <p className="text-lg font-medium">Agent Skills</p> </div> {/* Default skills */} <SkillList skills={defaultSkills} selectedSkill={selectedSkill} handleClick={handleDefaultSkillClick} activeSkills={Object.keys(defaultSkills).filter( (skill) => !disabledAgentSkills.includes(skill) )} /> {/* Configurable skills */} <SkillList skills={configurableSkills} selectedSkill={selectedSkill} handleClick={handleDefaultSkillClick} activeSkills={agentSkills} /> <div className="text-theme-text-primary flex items-center gap-x-2"> <Plug size={24} /> <p className="text-lg font-medium">Custom Skills</p> </div> <ImportedSkillList skills={importedSkills} selectedSkill={selectedSkill} handleClick={handleSkillClick} /> <div className="text-theme-text-primary flex items-center gap-x-2 mt-6"> <FlowArrow size={24} /> <p className="text-lg font-medium">Agent Flows</p> </div> <AgentFlowsList flows={agentFlows} selectedFlow={selectedFlow} handleClick={handleFlowClick} /> <input type="hidden" name="system::active_agent_flows" id="active_agent_flows" value={activeFlowIds.join(",")} /> <MCPServerHeader setMcpServers={setMcpServers} setSelectedMcpServer={setSelectedMcpServer} > {({ loadingMcpServers }) => { return ( <MCPServersList isLoading={loadingMcpServers} servers={mcpServers} selectedServer={selectedMcpServer} handleClick={handleMCPClick} /> ); }} </MCPServerHeader> </div> {/* Selected agent skill modal */} {showSkillModal && ( <div className="fixed top-0 left-0 w-full h-full bg-sidebar z-30"> <div className="flex flex-col h-full"> <div className="flex items-center p-4"> <button type="button" onClick={() => { setShowSkillModal(false); setSelectedSkill(""); }} className="text-white/60 hover:text-white transition-colors duration-200" > <div className="flex items-center text-sky-400"> <CaretLeft size={24} /> <div>Back</div> </div> </button> </div> <div className="flex-1 overflow-y-auto p-4"> <div className=" bg-theme-bg-secondary text-white rounded-xl p-4 overflow-y-scroll no-scroll"> {SelectedSkillComponent ? ( <> {selectedMcpServer ? ( <ServerPanel server={selectedMcpServer} toggleServer={toggleMCP} onDelete={handleMCPServerDelete} /> ) : selectedFlow ? ( <FlowPanel flow={selectedFlow} toggleFlow={toggleFlow} enabled={activeFlowIds.includes(selectedFlow.uuid)} onDelete={handleFlowDelete} /> ) : selectedSkill.imported ? ( <ImportedSkillConfig key={selectedSkill.hubId} selectedSkill={selectedSkill} setImportedSkills={setImportedSkills} /> ) : ( <> {defaultSkills?.[selectedSkill] ? ( // The selected skill is a default skill - show the default skill panel <SelectedSkillComponent skill={defaultSkills[selectedSkill]?.skill} settings={settings} toggleSkill={toggleDefaultSkill} enabled={ !disabledAgentSkills.includes( defaultSkills[selectedSkill]?.skill ) } setHasChanges={setHasChanges} {...defaultSkills[selectedSkill]} /> ) : ( // The selected skill is a configurable skill - show the configurable skill panel <SelectedSkillComponent skill={configurableSkills[selectedSkill]?.skill} settings={settings} toggleSkill={toggleAgentSkill} enabled={agentSkills.includes( configurableSkills[selectedSkill]?.skill )} setHasChanges={setHasChanges} {...configurableSkills[selectedSkill]} /> )} </> )} </> ) : ( <div className="flex flex-col items-center justify-center h-full text-theme-text-secondary"> <Robot size={40} /> <p className="font-medium"> Select an Agent Skill, Agent Flow, or MCP Server </p> </div> )} </div> </div> </div> </div> )} </form> </SkillLayout> ); } return ( <SkillLayout hasChanges={hasChanges} handleCancel={() => setHasChanges(false)} handleSubmit={handleSubmit} > <form onSubmit={handleSubmit} onChange={() => !selectedSkill?.imported && !selectedFlow && setHasChanges(true) } ref={formEl} className="flex-1 flex gap-x-6 p-4 mt-10" > <input name="system::default_agent_skills" type="hidden" value={agentSkills.join(",")} /> <input name="system::disabled_agent_skills" type="hidden" value={disabledAgentSkills.join(",")} /> <input type="hidden" name="system::active_agent_flows" id="active_agent_flows" value={activeFlowIds.join(",")} /> {/* Skill settings nav - Make this section scrollable */} <div className="flex flex-col min-w-[360px] h-[calc(100vh-90px)]"> <div className="flex-none mb-4"> <div className="text-theme-text-primary flex items-center gap-x-2"> <Robot size={24} /> <p className="text-lg font-medium">Agent Skills</p> </div> </div> <div className="flex-1 overflow-y-auto pr-2 pb-4"> <div className="space-y-4"> {/* Default skills list */} <SkillList skills={defaultSkills} selectedSkill={selectedSkill} handleClick={handleSkillClick} activeSkills={Object.keys(defaultSkills).filter( (skill) => !disabledAgentSkills.includes(skill) )} /> {/* Configurable skills */} <SkillList skills={configurableSkills} selectedSkill={selectedSkill} handleClick={handleSkillClick} activeSkills={agentSkills} /> <div className="text-theme-text-primary flex items-center gap-x-2 mt-4"> <Plug size={24} /> <p className="text-lg font-medium">Custom Skills</p> </div> <ImportedSkillList skills={importedSkills} selectedSkill={selectedSkill} handleClick={handleSkillClick} /> <div className="text-theme-text-primary flex items-center justify-between gap-x-2 mt-4"> <div className="flex items-center gap-x-2"> <FlowArrow size={24} /> <p className="text-lg font-medium">Agent Flows</p> </div> {agentFlows.length === 0 ? ( <Link to={paths.agents.builder()} className="text-cta-button flex items-center gap-x-1 hover:underline" > <Hammer size={16} /> <p className="text-sm">Create Flow</p> </Link> ) : ( <Link to={paths.agents.builder()} className="text-theme-text-secondary hover:text-cta-button flex items-center gap-x-1" > <Hammer size={16} /> <p className="text-sm">Open Builder</p> </Link> )} </div> <AgentFlowsList flows={agentFlows} selectedFlow={selectedFlow} handleClick={handleFlowClick} /> <MCPServerHeader setMcpServers={setMcpServers} setSelectedMcpServer={setSelectedMcpServer} > {({ loadingMcpServers }) => { return ( <MCPServersList isLoading={loadingMcpServers} servers={mcpServers} selectedServer={selectedMcpServer} handleClick={handleMCPClick} /> ); }} </MCPServerHeader> </div> </div> </div> {/* Selected agent skill setting panel */} <div className="flex-[2] flex flex-col gap-y-[18px] mt-10"> <div className="bg-theme-bg-secondary text-white rounded-xl flex-1 p-4 overflow-y-scroll no-scroll"> {SelectedSkillComponent ? ( <> {selectedMcpServer ? ( <ServerPanel server={selectedMcpServer} toggleServer={toggleMCP} onDelete={handleMCPServerDelete} /> ) : selectedFlow ? ( <FlowPanel flow={selectedFlow} toggleFlow={toggleFlow} enabled={activeFlowIds.includes(selectedFlow.uuid)} onDelete={handleFlowDelete} /> ) : selectedSkill.imported ? ( <ImportedSkillConfig key={selectedSkill.hubId} selectedSkill={selectedSkill} setImportedSkills={setImportedSkills} /> ) : ( <> {defaultSkills?.[selectedSkill] ? ( // The selected skill is a default skill - show the default skill panel <SelectedSkillComponent skill={defaultSkills[selectedSkill]?.skill} settings={settings} toggleSkill={toggleDefaultSkill} enabled={ !disabledAgentSkills.includes( defaultSkills[selectedSkill]?.skill ) } setHasChanges={setHasChanges} {...defaultSkills[selectedSkill]} /> ) : ( // The selected skill is a configurable skill - show the configurable skill panel <SelectedSkillComponent skill={configurableSkills[selectedSkill]?.skill} settings={settings} toggleSkill={toggleAgentSkill} enabled={agentSkills.includes( configurableSkills[selectedSkill]?.skill )} setHasChanges={setHasChanges} {...configurableSkills[selectedSkill]} /> )} </> )} </> ) : ( <div className="flex flex-col items-center justify-center h-full text-theme-text-secondary"> <Robot size={40} /> <p className="font-medium"> Select an Agent Skill, Agent Flow, or MCP Server </p> </div> )} </div> </div> </form> </SkillLayout> ); } function SkillLayout({ children, hasChanges, handleSubmit, handleCancel }) { return ( <div id="workspace-agent-settings-container" className="w-screen h-screen overflow-hidden bg-theme-bg-container flex md:mt-0 mt-6" > <Sidebar /> <div style={{ height: isMobile ? "100%" : "calc(100% - 32px)" }} className="relative md:ml-[2px] md:mr-[16px] md:my-[16px] md:rounded-[16px] w-full h-full flex" > {children} <ContextualSaveBar showing={hasChanges} onSave={handleSubmit} onCancel={handleCancel} /> </div> </div> ); } function SkillList({ isDefault = false, skills = [], selectedSkill = null, handleClick = null, activeSkills = [], }) { if (skills.length === 0) return null; return ( <> <div className={`bg-theme-bg-secondary text-white rounded-xl ${ isMobile ? "w-full" : "min-w-[360px] w-fit" }`} > {Object.entries(skills).map(([skill, settings], index) => ( <div key={skill} className={`py-3 px-4 flex items-center justify-between ${ index === 0 ? "rounded-t-xl" : "" } ${ index === Object.keys(skills).length - 1 ? "rounded-b-xl" : "border-b border-white/10" } cursor-pointer transition-all duration-300 hover:bg-theme-bg-primary ${ selectedSkill === skill ? "bg-white/10 light:bg-theme-bg-sidebar" : "" }`} onClick={() => handleClick?.(skill)} > <div className="text-sm font-light">{settings.title}</div> <div className="flex items-center gap-x-2"> {isDefault ? ( <DefaultBadge title={skill} /> ) : ( <div className="text-sm text-theme-text-secondary font-medium"> {activeSkills.includes(skill) ? "On" : "Off"} </div> )} <CaretRight size={14} weight="bold" className="text-theme-text-secondary" /> </div> </div> ))} </div> {/* Tooltip for default skills - only render when skill list is passed isDefault */} {isDefault && ( <Tooltip id="default-skill" place="bottom" delayShow={300} className="tooltip light:invert-0 !text-xs" /> )} </> ); }
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/pages/Admin/Agents/skills.js
frontend/src/pages/Admin/Agents/skills.js
import AgentWebSearchSelection from "./WebSearchSelection"; import AgentSQLConnectorSelection from "./SQLConnectorSelection"; import GenericSkillPanel from "./GenericSkillPanel"; import DefaultSkillPanel from "./DefaultSkillPanel"; import { Brain, File, Browser, ChartBar, FileMagnifyingGlass, } from "@phosphor-icons/react"; import RAGImage from "@/media/agents/rag-memory.png"; import SummarizeImage from "@/media/agents/view-summarize.png"; import ScrapeWebsitesImage from "@/media/agents/scrape-websites.png"; import GenerateChartsImage from "@/media/agents/generate-charts.png"; import GenerateSaveImages from "@/media/agents/generate-save-files.png"; export const defaultSkills = { "rag-memory": { title: "RAG & long-term memory", description: 'Allow the agent to leverage your local documents to answer a query or ask the agent to "remember" pieces of content for long-term memory retrieval.', component: DefaultSkillPanel, icon: Brain, image: RAGImage, skill: "rag-memory", }, "document-summarizer": { title: "View & summarize documents", description: "Allow the agent to list and summarize the content of workspace files currently embedded.", component: DefaultSkillPanel, icon: File, image: SummarizeImage, skill: "document-summarizer", }, "web-scraping": { title: "Scrape websites", description: "Allow the agent to visit and scrape the content of websites.", component: DefaultSkillPanel, icon: Browser, image: ScrapeWebsitesImage, skill: "web-scraping", }, }; export const configurableSkills = { "save-file-to-browser": { title: "Generate & save files", description: "Enable the default agent to generate and write to files that can be saved to your computer.", component: GenericSkillPanel, skill: "save-file-to-browser", icon: FileMagnifyingGlass, image: GenerateSaveImages, }, "create-chart": { title: "Generate charts", description: "Enable the default agent to generate various types of charts from data provided or given in chat.", component: GenericSkillPanel, skill: "create-chart", icon: ChartBar, image: GenerateChartsImage, }, "web-browsing": { title: "Web Search", component: AgentWebSearchSelection, skill: "web-browsing", }, "sql-agent": { title: "SQL Connector", component: AgentSQLConnectorSelection, skill: "sql-agent", }, };
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/pages/Admin/Agents/Badges/default.jsx
frontend/src/pages/Admin/Agents/Badges/default.jsx
export function DefaultBadge({ title }) { return ( <> <span className="w-fit" data-tooltip-id="default-skill" data-tooltip-content="This skill is enabled by default and cannot be turned off." > <div className="flex items-center gap-x-1 w-fit rounded-full bg-[#F4FFD0]/10 light:bg-blue-100 px-2.5 py-0.5 text-sm font-medium text-sky-400 light:text-theme-text-secondary shadow-sm cursor-pointer"> <div className="text-[#F4FFD0] light:text-blue-600 text-[12px] leading-[15px]"> Default </div> </div> </span> </> ); }
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/pages/Admin/Agents/MCPServers/index.jsx
frontend/src/pages/Admin/Agents/MCPServers/index.jsx
import { useState, useEffect } from "react"; import { titleCase } from "text-case"; import { BookOpenText, ArrowClockwise } from "@phosphor-icons/react"; import MCPLogo from "@/media/agents/mcp-logo.svg"; import MCPServers from "@/models/mcpServers"; import showToast from "@/utils/toast"; export function MCPServerHeader({ setMcpServers, setSelectedMcpServer, children, }) { const [loadingMcpServers, setLoadingMcpServers] = useState(false); useEffect(() => { async function fetchMCPServers() { setLoadingMcpServers(true); const { servers = [] } = await MCPServers.listServers(); setMcpServers(servers); setLoadingMcpServers(false); } fetchMCPServers(); }, []); // Refresh the list of MCP servers const refreshMCPServers = () => { if ( window.confirm( "Are you sure you want to refresh the list of MCP servers? This will restart all MCP servers and reload their tools." ) ) { setLoadingMcpServers(true); MCPServers.forceReload() .then(({ servers = [] }) => { setSelectedMcpServer(null); setMcpServers(servers); }) .catch((err) => { console.error(err); showToast(`Failed to refresh MCP servers.`, "error", { clear: true }); }) .finally(() => { setLoadingMcpServers(false); }); } }; return ( <> <div className="text-theme-text-primary flex items-center justify-between gap-x-2 mt-4"> <div className="flex items-center gap-x-2"> <img src={MCPLogo} className="w-6 h-6 light:invert" alt="MCP Logo" /> <p className="text-lg font-medium">MCP Servers</p> </div> <div className="flex items-center gap-x-3"> <a href="https://docs.anythingllm.com/mcp-compatibility/overview" target="_blank" rel="noopener noreferrer" className="border-none text-theme-text-secondary hover:text-cta-button" > <BookOpenText size={16} /> </a> <button type="button" onClick={refreshMCPServers} disabled={loadingMcpServers} className="border-none text-theme-text-secondary hover:text-cta-button flex items-center gap-x-1" > <ArrowClockwise size={16} className={loadingMcpServers ? "animate-spin" : ""} /> <p className="text-sm"> {loadingMcpServers ? "Loading..." : "Refresh"} </p> </button> </div> </div> {children({ loadingMcpServers })} </> ); } export function MCPServersList({ isLoading = false, servers = [], selectedServer, handleClick, }) { if (isLoading) { return ( <div className="text-theme-text-secondary text-center text-xs flex flex-col gap-y-2"> <p>Loading MCP Servers from configuration file...</p> <a href="https://docs.anythingllm.com/mcp-compatibility/overview" target="_blank" rel="noopener noreferrer" className="text-theme-text-secondary underline hover:text-cta-button" > Learn more about MCP Servers. </a> </div> ); } if (servers.length === 0) { return ( <div className="text-theme-text-secondary text-center text-xs flex flex-col gap-y-2"> <p>No MCP servers found</p> <a href="https://docs.anythingllm.com/mcp-compatibility/overview" target="_blank" rel="noopener noreferrer" className="text-theme-text-secondary underline hover:text-cta-button" > Learn more about MCP Servers. </a> </div> ); } return ( <div className="bg-theme-bg-secondary text-white rounded-xl w-full md:min-w-[360px]"> {servers.map((server, index) => ( <div key={server.name} className={`py-3 px-4 flex items-center justify-between ${ index === 0 ? "rounded-t-xl" : "" } ${ index === servers.length - 1 ? "rounded-b-xl" : "border-b border-white/10" } cursor-pointer transition-all duration-300 hover:bg-theme-bg-primary ${ selectedServer?.name === server.name ? "bg-white/10 light:bg-theme-bg-sidebar" : "" }`} onClick={() => handleClick?.(server)} > <div className="text-sm font-light"> {titleCase(server.name.replace(/[_-]/g, " "))} </div> <div className="flex items-center gap-x-2"> <div className={`text-sm text-theme-text-secondary font-medium ${server.running ? "text-green-500" : "text-red-500"}`} > {server.running ? "On" : "Stopped"} </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/pages/Admin/Agents/MCPServers/ServerPanel.jsx
frontend/src/pages/Admin/Agents/MCPServers/ServerPanel.jsx
import React, { useState, useEffect, useRef } from "react"; import showToast from "@/utils/toast"; import { CaretDown, Gear } from "@phosphor-icons/react"; import MCPLogo from "@/media/agents/mcp-logo.svg"; import { titleCase } from "text-case"; import truncate from "truncate"; import MCPServers from "@/models/mcpServers"; import pluralize from "pluralize"; function ManageServerMenu({ server, toggleServer, onDelete }) { const [open, setOpen] = useState(false); const [running, setRunning] = useState(server.running); const menuRef = useRef(null); async function deleteServer() { if ( !window.confirm( "Are you sure you want to delete this MCP server? It will be removed from your config file and you will need to add it back manually." ) ) return; const { success, error } = await MCPServers.deleteServer(server.name); if (success) { showToast("MCP server deleted successfully.", "success"); onDelete(server.name); } else { showToast(error || "Failed to delete MCP server.", "error"); } } async function handleToggleServer() { if ( !window.confirm( running ? "Are you sure you want to stop this MCP server? It will be started automatically when you next start the server." : "Are you sure you want to start this MCP server? It will be started automatically when you next start the server." ) ) return; const { success, error } = await MCPServers.toggleServer(server.name); if (success) { const newState = !running; setRunning(newState); toggleServer(server.name); showToast( `MCP server ${server.name} ${newState ? "started" : "stopped"} successfully.`, "success", { clear: true } ); } else { showToast(error || "Failed to toggle MCP server.", "error", { clear: true, }); } } useEffect(() => { const handleClickOutside = (event) => { if (menuRef.current && !menuRef.current.contains(event.target)) { setOpen(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); return ( <div className="relative" ref={menuRef}> <button type="button" onClick={() => setOpen(!open)} className="p-1.5 rounded-lg text-white hover:bg-theme-action-menu-item-hover transition-colors duration-300" > <Gear className="h-5 w-5" weight="bold" /> </button> {open && ( <div className="absolute w-[150px] 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 type="button" onClick={handleToggleServer} className="border-none flex items-center rounded-lg gap-x-2 hover:bg-theme-action-menu-item-hover py-1.5 px-2 transition-colors duration-200 w-full text-left" > <span className="text-sm"> {running ? "Stop MCP Server" : "Start MCP Server"} </span> </button> <button type="button" onClick={deleteServer} className="border-none flex items-center rounded-lg gap-x-2 hover:bg-theme-action-menu-item-hover py-1.5 px-2 transition-colors duration-200 w-full text-left" > <span className="text-sm">Delete MCP Server</span> </button> </div> )} </div> ); } export default function ServerPanel({ server, toggleServer, onDelete }) { return ( <> <div className="p-2"> <div className="flex flex-col gap-y-[18px] max-w-[800px]"> <div className="flex w-full justify-between"> <div className="flex items-center gap-x-2"> <img src={MCPLogo} className="w-6 h-6 light:invert" /> <label htmlFor="name" className="text-white text-md font-bold"> {titleCase(server.name.replace(/[_-]/g, " "))} </label> {server.tools.length > 0 && ( <p className="text-theme-text-secondary text-sm"> {server.tools.length} {pluralize("tool", server.tools.length)}{" "} available </p> )} </div> <ManageServerMenu key={server.name} server={server} toggleServer={toggleServer} onDelete={onDelete} /> </div> <RenderServerConfig config={server.config} /> <RenderServerStatus server={server} /> <RenderServerTools tools={server.tools} /> </div> </div> </> ); } function RenderServerConfig({ config = null }) { if (!config) return null; return ( <div className="flex flex-col gap-y-2"> <p className="text-theme-text-primary text-sm">Startup Command</p> <div className="bg-theme-bg-primary rounded-lg p-4"> <p className="text-theme-text-secondary text-sm text-left"> <span className="font-bold">Command:</span> {config.command} </p> <p className="text-theme-text-secondary text-sm text-left"> <span className="font-bold">Arguments:</span>{" "} {config.args ? config.args.join(" ") : "None"} </p> </div> </div> ); } function RenderServerStatus({ server }) { if (server.running || !server.error) return null; return ( <div className="flex flex-col gap-y-2"> <p className="text-theme-text-primary text-sm"> This MCP server is not running - it may be stopped or experiencing an error on startup. </p> <div className="bg-theme-bg-primary rounded-lg p-4"> <p className="text-red-500 text-sm font-mono">{server.error}</p> </div> </div> ); } function RenderServerTools({ tools = [] }) { if (tools.length === 0) return null; return ( <div className="flex flex-col gap-y-2"> <div className="flex flex-col gap-y-2"> {tools.map((tool) => ( <ServerTool key={tool.name} tool={tool} /> ))} </div> </div> ); } function ServerTool({ tool }) { const [open, setOpen] = useState(false); return ( <button type="button" onClick={() => setOpen(!open)} className="flex flex-col gap-y-2 px-4 py-2 rounded-lg border border-theme-text-secondary" > <div className="flex items-center justify-between"> <div className="flex items-center gap-x-2"> <p className="text-theme-text-primary font-mono font-bold text-sm"> {tool.name} </p> {!open && ( <p className="text-theme-text-secondary text-sm"> {truncate(tool.description, 70)} </p> )} </div> <div className="border-none text-theme-text-secondary hover:text-cta-button"> <CaretDown size={16} /> </div> </div> {open && ( <div className="flex flex-col gap-y-2"> <div className="flex flex-col gap-y-2"> <p className="text-theme-text-secondary text-sm text-left"> {tool.description} </p> </div> <div className="flex flex-col gap-y-2"> <p className="text-theme-text-primary text-sm text-left"> Tool call arguments </p> <div className="flex flex-col gap-y-2"> {Object.entries(tool.inputSchema?.properties || {}).map( ([key, value]) => ( <div key={key} className="flex items-center gap-x-2"> <p className="text-theme-text-secondary text-sm text-left font-bold"> {key} {tool.inputSchema?.required?.includes(key) && ( <sup className="text-red-500">*</sup> )} </p> <p className="text-theme-text-secondary text-sm text-left"> {value.type} </p> </div> ) )} </div> </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/pages/Admin/Agents/GenericSkillPanel/index.jsx
frontend/src/pages/Admin/Agents/GenericSkillPanel/index.jsx
import React from "react"; export default function GenericSkillPanel({ title, description, skill, toggleSkill, enabled = false, disabled = false, image, icon, }) { return ( <div className="p-2"> <div className="flex flex-col gap-y-[18px] max-w-[500px]"> <div className="flex items-center gap-x-2"> {icon && React.createElement(icon, { size: 24, color: "var(--theme-text-primary)", weight: "bold", })} <label htmlFor="name" className="text-theme-text-primary text-md font-bold" > {title} </label> <label className={`border-none relative inline-flex items-center ml-auto ${ disabled ? "cursor-not-allowed" : "cursor-pointer" }`} > <input type="checkbox" disabled={disabled} className="peer sr-only" checked={enabled} onChange={() => toggleSkill(skill)} /> <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"></span> </label> </div> <img src={image} alt={title} className="w-full rounded-md" /> <p className="text-theme-text-secondary text-opacity-60 text-xs font-medium py-1.5"> {description} </p> </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/pages/Admin/Agents/SQLConnectorSelection/index.jsx
frontend/src/pages/Admin/Agents/SQLConnectorSelection/index.jsx
import React, { useEffect, useState } from "react"; import DBConnection from "./DBConnection"; import { Plus, Database } from "@phosphor-icons/react"; import NewSQLConnection from "./NewConnectionModal"; import { useModal } from "@/hooks/useModal"; import SQLAgentImage from "@/media/agents/sql-agent.png"; import Admin from "@/models/admin"; export default function AgentSQLConnectorSelection({ skill, settings, // unused. toggleSkill, enabled = false, setHasChanges, }) { const { isOpen, openModal, closeModal } = useModal(); const [connections, setConnections] = useState([]); useEffect(() => { Admin.systemPreferencesByFields(["agent_sql_connections"]) .then((res) => setConnections(res?.settings?.agent_sql_connections ?? [])) .catch(() => setConnections([])); }, []); function handleRemoveConnection(databaseId) { setHasChanges(true); setConnections((prev) => prev.map((conn) => { if (conn.database_id === databaseId) return { ...conn, action: "remove" }; return conn; }) ); } return ( <> <div className="p-2"> <div className="flex flex-col gap-y-[18px] max-w-[500px]"> <div className="flex items-center gap-x-2"> <Database size={24} color="var(--theme-text-primary)" weight="bold" /> <label htmlFor="name" className="text-theme-text-primary text-md font-bold" > SQL Agent </label> <label className="border-none relative inline-flex items-center ml-auto cursor-pointer"> <input type="checkbox" className="peer sr-only" checked={enabled} onChange={() => toggleSkill(skill)} /> <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"></span> </label> </div> <img src={SQLAgentImage} alt="SQL Agent" className="w-full rounded-md" /> <p className="text-theme-text-secondary text-opacity-60 text-xs font-medium py-1.5"> Enable your agent to be able to leverage SQL to answer you questions by connecting to various SQL database providers. </p> {enabled && ( <> <input name="system::agent_sql_connections" type="hidden" value={JSON.stringify(connections)} /> <input type="hidden" value={JSON.stringify( connections.filter((conn) => conn.action !== "remove") )} /> <div className="flex flex-col mt-2 gap-y-2"> <p className="text-theme-text-primary font-semibold text-sm"> Your database connections </p> <div className="flex flex-col gap-y-3"> {connections .filter((connection) => connection.action !== "remove") .map((connection) => ( <DBConnection key={connection.database_id} connection={connection} onRemove={handleRemoveConnection} /> ))} <button type="button" onClick={openModal} className="w-fit relative flex h-[40px] items-center border-none hover:bg-theme-bg-secondary rounded-lg" > <div className="flex w-full gap-x-2 items-center p-4"> <div className="bg-theme-bg-secondary p-2 rounded-lg h-[24px] w-[24px] flex items-center justify-center"> <Plus weight="bold" size={14} className="shrink-0 text-theme-text-primary" /> </div> <p className="text-left text-theme-text-primary text-sm"> New SQL connection </p> </div> </button> </div> </div> </> )} </div> </div> <NewSQLConnection isOpen={isOpen} closeModal={closeModal} setHasChanges={setHasChanges} onSubmit={(newDb) => setConnections((prev) => [...prev, { action: "add", ...newDb }]) } /> </> ); }
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/pages/Admin/Agents/SQLConnectorSelection/DBConnection.jsx
frontend/src/pages/Admin/Agents/SQLConnectorSelection/DBConnection.jsx
import PostgreSQLLogo from "./icons/postgresql.png"; import MySQLLogo from "./icons/mysql.png"; import MSSQLLogo from "./icons/mssql.png"; import { X } from "@phosphor-icons/react"; export const DB_LOGOS = { postgresql: PostgreSQLLogo, mysql: MySQLLogo, "sql-server": MSSQLLogo, }; export default function DBConnection({ connection, onRemove }) { const { database_id, engine } = connection; function removeConfirmation() { if ( !window.confirm( `Delete ${database_id} from the list of available SQL connections? This cannot be undone.` ) ) return false; onRemove(database_id); } return ( <div className="flex gap-x-4 items-center"> <img src={DB_LOGOS?.[engine] ?? null} alt={`${engine} logo`} className="w-10 h-10 rounded-md" /> <div className="flex w-full items-center justify-between"> <div className="flex flex-col"> <div className="text-sm font-semibold text-white">{database_id}</div> <div className="mt-1 text-xs text-description">{engine}</div> </div> <button type="button" onClick={removeConfirmation} className="border-none text-white hover:text-red-500" > <X size={24} /> </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/pages/Admin/Agents/SQLConnectorSelection/NewConnectionModal.jsx
frontend/src/pages/Admin/Agents/SQLConnectorSelection/NewConnectionModal.jsx
import { useState } from "react"; import { createPortal } from "react-dom"; import ModalWrapper from "@/components/ModalWrapper"; import { WarningOctagon, X } from "@phosphor-icons/react"; import { DB_LOGOS } from "./DBConnection"; import System from "@/models/system"; import showToast from "@/utils/toast"; function assembleConnectionString({ engine, username = "", password = "", host = "", port = "", database = "", encrypt = false, }) { if ([username, password, host, database].every((i) => !!i) === false) return `Please fill out all the fields above.`; switch (engine) { case "postgresql": return `postgres://${username}:${password}@${host}:${port}/${database}`; case "mysql": return `mysql://${username}:${password}@${host}:${port}/${database}`; case "sql-server": return `mssql://${username}:${password}@${host}:${port}/${database}?encrypt=${encrypt}`; default: return null; } } const DEFAULT_ENGINE = "postgresql"; const DEFAULT_CONFIG = { username: null, password: null, host: null, port: null, database: null, schema: null, encrypt: false, }; export default function NewSQLConnection({ isOpen, closeModal, onSubmit, setHasChanges, }) { const [engine, setEngine] = useState(DEFAULT_ENGINE); const [config, setConfig] = useState(DEFAULT_CONFIG); const [isValidating, setIsValidating] = useState(false); if (!isOpen) return null; function handleClose() { setEngine(DEFAULT_ENGINE); setConfig(DEFAULT_CONFIG); closeModal(); } function onFormChange(e) { const form = new FormData(e.target.form); setConfig({ username: form.get("username").trim(), password: form.get("password"), host: form.get("host").trim(), port: form.get("port").trim(), database: form.get("database").trim(), encrypt: form.get("encrypt") === "true", }); } async function handleUpdate(e) { e.preventDefault(); e.stopPropagation(); const form = new FormData(e.target); const connectionString = assembleConnectionString({ engine, ...config }); setIsValidating(true); try { const { success, error } = await System.validateSQLConnection( engine, connectionString ); if (!success) { showToast( error || "Failed to establish database connection. Please check your connection details.", "error", { clear: true } ); setIsValidating(false); return; } onSubmit({ engine, database_id: form.get("name"), connectionString, }); setHasChanges(true); handleClose(); } catch (error) { console.error("Error validating connection:", error); showToast( error?.message || "Failed to validate connection. Please check your connection details.", "error", { clear: true } ); } finally { setIsValidating(false); } return false; } // Cannot do nested forms, it will cause all sorts of issues, so we portal this out // to the parent container form so we don't have nested forms. 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"> New SQL Connection </h3> </div> <button onClick={handleClose} 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="sql-connection-form" onChange={onFormChange} onSubmit={handleUpdate} > <div className="px-7 py-6"> <div className="space-y-6 max-h-[60vh] overflow-y-auto pr-2"> <p className="text-sm text-white/60"> Add the connection information for your database below and it will be available for future SQL agent calls. </p> <div className="flex flex-col w-full"> <div className="border border-red-800 bg-zinc-800 light:bg-red-200/50 p-4 rounded-lg flex items-center gap-x-2 text-sm text-red-400 light:text-red-500"> <WarningOctagon size={28} className="shrink-0" /> <p> <b>WARNING:</b> The SQL agent has been <i>instructed</i>{" "} to only perform non-modifying queries. This{" "} <b>does not</b> prevent a hallucination from still deleting data. Only connect with a user who has{" "} <b>READ_ONLY</b> permissions. </p> </div> <label className="block mb-2 text-sm font-medium text-white mt-4"> Select your SQL engine </label> <div className="grid md:grid-cols-4 gap-4 grid-cols-2"> <DBEngine provider="postgresql" active={engine === "postgresql"} onClick={() => setEngine("postgresql")} /> <DBEngine provider="mysql" active={engine === "mysql"} onClick={() => setEngine("mysql")} /> <DBEngine provider="sql-server" active={engine === "sql-server"} onClick={() => setEngine("sql-server")} /> </div> </div> <div className="flex flex-col w-full"> <label className="block mb-2 text-sm font-medium text-white"> Connection name </label> <input type="text" name="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="a unique name to identify this SQL connection" required={true} autoComplete="off" spellCheck={false} /> </div> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2"> <div className="flex flex-col"> <label className="block mb-2 text-sm font-medium text-white"> Database user </label> <input type="text" name="username" 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="root" required={true} autoComplete="off" spellCheck={false} /> </div> <div className="flex flex-col"> <label className="block mb-2 text-sm font-medium text-white"> Database user password </label> <input type="text" name="password" 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="password123" required={true} autoComplete="off" spellCheck={false} /> </div> </div> <div className="grid grid-cols-1 gap-4 sm:grid-cols-3"> <div className="sm:col-span-2"> <label className="block mb-2 text-sm font-medium text-white"> Server endpoint </label> <input type="text" name="host" 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="the hostname or endpoint for your database" required={true} autoComplete="off" spellCheck={false} /> </div> <div> <label className="block mb-2 text-sm font-medium text-white"> Port </label> <input type="text" name="port" 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="3306" required={false} autoComplete="off" spellCheck={false} /> </div> </div> <div className="flex flex-col"> <label className="block mb-2 text-sm font-medium text-white"> Database </label> <input type="text" name="database" 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="the database the agent will interact with" required={true} autoComplete="off" spellCheck={false} /> </div> {engine === "postgresql" && ( <div className="flex flex-col"> <label className="block mb-2 text-sm font-medium text-white"> Schema (optional) </label> <input type="text" name="schema" 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="public (default schema if not specified)" required={false} autoComplete="off" spellCheck={false} /> </div> )} {engine === "sql-server" && ( <div className="flex items-center justify-between"> <label className="relative inline-flex items-center cursor-pointer"> <input type="checkbox" name="encrypt" value="true" className="sr-only peer" checked={config.encrypt} /> <div className="w-11 h-6 bg-theme-settings-input-bg peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-800 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div> <span className="ml-3 text-sm font-medium text-white"> Enable Encryption </span> </label> </div> )} <p className="text-theme-text-secondary text-sm"> {assembleConnectionString({ engine, ...config })} </p> </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={handleClose} className="transition-all duration-300 text-white hover:bg-zinc-700 light:hover:bg-theme-bg-primary px-4 py-2 rounded-lg text-sm" > Cancel </button> <button type="submit" form="sql-connection-form" disabled={isValidating} className="transition-all duration-300 bg-white text-black hover:opacity-60 px-4 py-2 rounded-lg text-sm disabled:opacity-50" > {isValidating ? "Validating..." : "Save connection"} </button> </div> </form> </div> </div> </ModalWrapper>, document.getElementById("workspace-agent-settings-container") ); } function DBEngine({ provider, active, onClick }) { return ( <button type="button" onClick={onClick} className={`flex flex-col p-4 border border-white/40 bg-zinc-800 light:bg-theme-settings-input-bg rounded-lg w-fit hover:bg-zinc-700 ${ active ? "!bg-blue-500/50" : "" }`} > <img src={DB_LOGOS[provider]} className="h-[100px] rounded-md" alt={provider} /> </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/pages/Admin/Agents/Imported/SkillList/index.jsx
frontend/src/pages/Admin/Agents/Imported/SkillList/index.jsx
import { CaretRight } from "@phosphor-icons/react"; import { sentenceCase } from "text-case"; export default function ImportedSkillList({ skills = [], selectedSkill = null, handleClick = null, }) { if (skills.length === 0) return ( <div className="text-theme-text-secondary text-center text-xs flex flex-col gap-y-2"> <p>No imported skills found</p> <p> Learn about agent skills in the{" "} <a href="https://docs.anythingllm.com/agent/custom/developer-guide" target="_blank" className="text-theme-text-secondary underline hover:text-cta-button" > AnythingLLM Agent Docs </a> . </p> </div> ); return ( <div className={`bg-theme-bg-secondary text-white rounded-xl w-full md:min-w-[360px]`} > {skills.map((config, index) => ( <div key={config.hubId} className={`py-3 px-4 flex items-center justify-between ${ index === 0 ? "rounded-t-xl" : "" } ${ index === Object.keys(skills).length - 1 ? "rounded-b-xl" : "border-b border-white/10" } cursor-pointer transition-all duration-300 hover:bg-theme-bg-primary ${ selectedSkill === config.hubId ? "bg-theme-bg-primary" : "" }`} onClick={() => handleClick?.({ ...config, imported: true })} > <div className="text-sm font-light">{sentenceCase(config.name)}</div> <div className="flex items-center gap-x-2"> <div className="text-sm text-theme-text-secondary font-medium"> {config.active ? "On" : "Off"} </div> <CaretRight size={14} weight="bold" className="text-theme-text-secondary" /> </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/pages/Admin/Agents/Imported/ImportedSkillConfig/index.jsx
frontend/src/pages/Admin/Agents/Imported/ImportedSkillConfig/index.jsx
import System from "@/models/system"; import showToast from "@/utils/toast"; import { Gear, Plug } from "@phosphor-icons/react"; import { useEffect, useState, useRef } from "react"; import { sentenceCase } from "text-case"; /** * Converts setup_args to inputs for the form builder * @param {object} setupArgs - The setup arguments object * @returns {object} - The inputs object */ function inputsFromArgs(setupArgs) { if ( !setupArgs || setupArgs.constructor?.call?.().toString() !== "[object Object]" ) { return {}; } return Object.entries(setupArgs).reduce( (acc, [key, props]) => ({ ...acc, [key]: props.hasOwnProperty("value") ? props.value : props?.input?.default || "", }), {} ); } /** * Imported skill config component for imported skills only. * @returns {JSX.Element} */ export default function ImportedSkillConfig({ selectedSkill, // imported skill config object setImportedSkills, // function to set imported skills since config is file-write }) { const [config, setConfig] = useState(selectedSkill); const [hasChanges, setHasChanges] = useState(false); const [inputs, setInputs] = useState( inputsFromArgs(selectedSkill?.setup_args) ); const hasSetupArgs = selectedSkill?.setup_args && Object.keys(selectedSkill.setup_args).length > 0; async function toggleSkill() { const updatedConfig = { ...selectedSkill, active: !config.active }; await System.experimentalFeatures.agentPlugins.updatePluginConfig( config.hubId, { active: !config.active } ); setImportedSkills((prev) => prev.map((s) => (s.hubId === config.hubId ? updatedConfig : s)) ); setConfig(updatedConfig); showToast( `Skill ${updatedConfig.active ? "activated" : "deactivated"}.`, "success", { clear: true } ); } async function handleSubmit(e) { e.preventDefault(); const errors = []; const updatedConfig = { ...config }; for (const [key, value] of Object.entries(inputs)) { const settings = config.setup_args[key]; if (settings.required && !value) { errors.push(`${key} is required to have a value.`); continue; } if (typeof value !== settings.type) { errors.push(`${key} must be of type ${settings.type}.`); continue; } updatedConfig.setup_args[key].value = value; } if (errors.length > 0) { errors.forEach((error) => showToast(error, "error")); return; } await System.experimentalFeatures.agentPlugins.updatePluginConfig( config.hubId, updatedConfig ); setConfig(updatedConfig); setImportedSkills((prev) => prev.map((skill) => skill.hubId === config.hubId ? updatedConfig : skill ) ); showToast("Skill config updated successfully.", "success"); setHasChanges(false); } useEffect(() => { setHasChanges( JSON.stringify(inputs) !== JSON.stringify(inputsFromArgs(selectedSkill.setup_args)) ); }, [inputs]); return ( <> <div className="p-2"> <div className="flex flex-col gap-y-[18px] max-w-[500px]"> <div className="flex items-center gap-x-2"> <Plug size={24} weight="bold" className="text-white" /> <label htmlFor="name" className="text-white text-md font-bold"> {sentenceCase(config.name)} </label> <label className="border-none relative inline-flex items-center ml-auto cursor-pointer"> <input type="checkbox" className="peer sr-only" checked={config.active} onChange={() => toggleSkill()} /> <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"></span> </label> <ManageSkillMenu config={config} setImportedSkills={setImportedSkills} /> </div> <p className="text-white text-opacity-60 text-xs font-medium py-1.5"> {config.description} by{" "} <a href={config.author_url} target="_blank" rel="noopener noreferrer" className="text-white hover:underline" > {config.author} </a> </p> {hasSetupArgs ? ( <div className="flex flex-col gap-y-2"> {Object.entries(config.setup_args).map(([key, props]) => ( <div key={key} className="flex flex-col gap-y-1"> <label htmlFor={key} className="text-white text-sm font-bold"> {key} </label> <input type={props?.input?.type || "text"} required={props?.input?.required} defaultValue={ props.hasOwnProperty("value") ? props.value : props?.input?.default || "" } onChange={(e) => setInputs({ ...inputs, [key]: e.target.value }) } placeholder={props?.input?.placeholder || ""} className="border-solid bg-transparent border border-white light:border-black rounded-md p-2 text-white text-sm" /> <p className="text-white text-opacity-60 text-xs font-medium py-1.5"> {props?.input?.hint} </p> </div> ))} {hasChanges && ( <button onClick={handleSubmit} type="button" className="bg-blue-500 text-white light:text-white rounded-md p-2" > Save </button> )} </div> ) : ( <p className="text-white text-opacity-60 text-sm font-medium py-1.5"> There are no options to modify for this skill. </p> )} </div> </div> </> ); } function ManageSkillMenu({ config, setImportedSkills }) { const [open, setOpen] = useState(false); const menuRef = useRef(null); async function deleteSkill() { if ( !window.confirm( "Are you sure you want to delete this skill? This action cannot be undone." ) ) return; const success = await System.experimentalFeatures.agentPlugins.deletePlugin( config.hubId ); if (success) { setImportedSkills((prev) => prev.filter((s) => s.hubId !== config.hubId)); showToast("Skill deleted successfully.", "success"); setOpen(false); } else { showToast("Failed to delete skill.", "error"); } } useEffect(() => { const handleClickOutside = (event) => { if (menuRef.current && !menuRef.current.contains(event.target)) { setOpen(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); if (!config.hubId) return null; return ( <div className="relative" ref={menuRef}> <button type="button" onClick={() => setOpen(!open)} className="p-1.5 rounded-lg text-white hover:bg-theme-action-menu-item-hover transition-colors duration-300" > <Gear className="h-5 w-5" weight="bold" /> </button> {open && ( <div className="absolute w-[100px] -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 type="button" onClick={deleteSkill} className="border-none flex items-center rounded-lg gap-x-2 hover:bg-theme-action-menu-item-hover py-1.5 px-2 transition-colors duration-200 w-full text-left" > <span className="text-sm">Delete Skill</span> </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/pages/Admin/Agents/DefaultSkillPanel/index.jsx
frontend/src/pages/Admin/Agents/DefaultSkillPanel/index.jsx
import React from "react"; import { DefaultBadge } from "../Badges/default"; export default function DefaultSkillPanel({ title, description, image, icon, enabled = true, toggleSkill, skill, }) { return ( <div className="p-2"> <div className="flex flex-col gap-y-[18px] max-w-[500px]"> <div className="flex w-full justify-between items-center"> <div className="flex items-center gap-x-2"> {icon && React.createElement(icon, { size: 24, color: "var(--theme-text-primary)", weight: "bold", })} <label htmlFor="name" className="text-theme-text-primary text-md font-bold" > {title} </label> <DefaultBadge title={title} /> </div> <label className={`border-none relative inline-flex items-center ml-auto cursor-pointer`} > <input type="checkbox" className="peer sr-only" checked={enabled} onChange={() => toggleSkill(skill)} /> <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"></span> </label> </div> <img src={image} alt={title} className="w-full rounded-md" /> <p className="text-theme-text-secondary text-opacity-60 text-xs font-medium py-1.5"> {description} <br /> <br /> By default, this skill is enabled, but you can disable it if you don't want it to be available to the agent. </p> </div> </div> ); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false