repo
stringlengths
7
64
file_url
stringlengths
81
338
file_path
stringlengths
5
257
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:25:31
2026-01-05 01:50:38
truncated
bool
2 classes
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/jest.setup.ts
jest.setup.ts
// Learn more: https://github.com/testing-library/jest-dom import "@testing-library/jest-dom"; import { jest } from "@jest/globals"; global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve([]), headers: new Headers(), redirected: false, statusText: "OK", type: "basic", url: "", body: null, bodyUsed: false, arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)), blob: () => Promise.resolve(new Blob()), formData: () => Promise.resolve(new FormData()), text: () => Promise.resolve(""), } as Response), );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/jest.config.ts
jest.config.ts
import type { Config } from "jest"; import nextJest from "next/jest.js"; const createJestConfig = nextJest({ // Provide the path to your Next.js app to load next.config.js and .env files in your test environment dir: "./", }); // Add any custom config to be passed to Jest const config: Config = { coverageProvider: "v8", testEnvironment: "jsdom", testMatch: ["**/*.test.js", "**/*.test.ts", "**/*.test.jsx", "**/*.test.tsx"], setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"], moduleNameMapper: { "^@/(.*)$": "<rootDir>/$1", }, extensionsToTreatAsEsm: [".ts", ".tsx"], injectGlobals: true, }; // createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async export default createJestConfig(config);
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/typing.ts
app/typing.ts
export type Updater<T> = (updater: (value: T) => void) => void; export const ROLES = ["system", "user", "assistant"] as const; export type MessageRole = (typeof ROLES)[number]; export interface RequestMessage { role: MessageRole; content: string; } export type DalleSize = "1024x1024" | "1792x1024" | "1024x1792"; export type DalleQuality = "standard" | "hd"; export type DalleStyle = "vivid" | "natural"; export type ModelSize = | "1024x1024" | "1792x1024" | "1024x1792" | "768x1344" | "864x1152" | "1344x768" | "1152x864" | "1440x720" | "720x1440";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/constant.ts
app/constant.ts
export const OWNER = "ChatGPTNextWeb"; export const REPO = "ChatGPT-Next-Web"; export const REPO_URL = `https://github.com/${OWNER}/${REPO}`; export const PLUGINS_REPO_URL = `https://github.com/${OWNER}/NextChat-Awesome-Plugins`; export const ISSUE_URL = `https://github.com/${OWNER}/${REPO}/issues`; export const UPDATE_URL = `${REPO_URL}#keep-updated`; export const RELEASE_URL = `${REPO_URL}/releases`; export const FETCH_COMMIT_URL = `https://api.github.com/repos/${OWNER}/${REPO}/commits?per_page=1`; export const FETCH_TAG_URL = `https://api.github.com/repos/${OWNER}/${REPO}/tags?per_page=1`; export const RUNTIME_CONFIG_DOM = "danger-runtime-config"; export const STABILITY_BASE_URL = "https://api.stability.ai"; export const OPENAI_BASE_URL = "https://api.openai.com"; export const ANTHROPIC_BASE_URL = "https://api.anthropic.com"; export const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/"; export const BAIDU_BASE_URL = "https://aip.baidubce.com"; export const BAIDU_OATUH_URL = `${BAIDU_BASE_URL}/oauth/2.0/token`; export const BYTEDANCE_BASE_URL = "https://ark.cn-beijing.volces.com"; export const ALIBABA_BASE_URL = "https://dashscope.aliyuncs.com/api/"; export const TENCENT_BASE_URL = "https://hunyuan.tencentcloudapi.com"; export const MOONSHOT_BASE_URL = "https://api.moonshot.ai"; export const IFLYTEK_BASE_URL = "https://spark-api-open.xf-yun.com"; export const DEEPSEEK_BASE_URL = "https://api.deepseek.com"; export const XAI_BASE_URL = "https://api.x.ai"; export const CHATGLM_BASE_URL = "https://open.bigmodel.cn"; export const SILICONFLOW_BASE_URL = "https://api.siliconflow.cn"; export const AI302_BASE_URL = "https://api.302.ai"; export const CACHE_URL_PREFIX = "/api/cache"; export const UPLOAD_URL = `${CACHE_URL_PREFIX}/upload`; export enum Path { Home = "/", Chat = "/chat", Settings = "/settings", NewChat = "/new-chat", Masks = "/masks", Plugins = "/plugins", Auth = "/auth", Sd = "/sd", SdNew = "/sd-new", Artifacts = "/artifacts", SearchChat = "/search-chat", McpMarket = "/mcp-market", } export enum ApiPath { Cors = "", Azure = "/api/azure", OpenAI = "/api/openai", Anthropic = "/api/anthropic", Google = "/api/google", Baidu = "/api/baidu", ByteDance = "/api/bytedance", Alibaba = "/api/alibaba", Tencent = "/api/tencent", Moonshot = "/api/moonshot", Iflytek = "/api/iflytek", Stability = "/api/stability", Artifacts = "/api/artifacts", XAI = "/api/xai", ChatGLM = "/api/chatglm", DeepSeek = "/api/deepseek", SiliconFlow = "/api/siliconflow", "302.AI" = "/api/302ai", } export enum SlotID { AppBody = "app-body", CustomModel = "custom-model", } export enum FileName { Masks = "masks.json", Prompts = "prompts.json", } export enum StoreKey { Chat = "chat-next-web-store", Plugin = "chat-next-web-plugin", Access = "access-control", Config = "app-config", Mask = "mask-store", Prompt = "prompt-store", Update = "chat-update", Sync = "sync", SdList = "sd-list", Mcp = "mcp-store", } export const DEFAULT_SIDEBAR_WIDTH = 300; export const MAX_SIDEBAR_WIDTH = 500; export const MIN_SIDEBAR_WIDTH = 230; export const NARROW_SIDEBAR_WIDTH = 100; export const ACCESS_CODE_PREFIX = "nk-"; export const LAST_INPUT_KEY = "last-input"; export const UNFINISHED_INPUT = (id: string) => "unfinished-input-" + id; export const STORAGE_KEY = "chatgpt-next-web"; export const REQUEST_TIMEOUT_MS = 60000; export const REQUEST_TIMEOUT_MS_FOR_THINKING = REQUEST_TIMEOUT_MS * 5; export const EXPORT_MESSAGE_CLASS_NAME = "export-markdown"; export enum ServiceProvider { OpenAI = "OpenAI", Azure = "Azure", Google = "Google", Anthropic = "Anthropic", Baidu = "Baidu", ByteDance = "ByteDance", Alibaba = "Alibaba", Tencent = "Tencent", Moonshot = "Moonshot", Stability = "Stability", Iflytek = "Iflytek", XAI = "XAI", ChatGLM = "ChatGLM", DeepSeek = "DeepSeek", SiliconFlow = "SiliconFlow", "302.AI" = "302.AI", } // Google API safety settings, see https://ai.google.dev/gemini-api/docs/safety-settings // BLOCK_NONE will not block any content, and BLOCK_ONLY_HIGH will block only high-risk content. export enum GoogleSafetySettingsThreshold { BLOCK_NONE = "BLOCK_NONE", BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", } export enum ModelProvider { Stability = "Stability", GPT = "GPT", GeminiPro = "GeminiPro", Claude = "Claude", Ernie = "Ernie", Doubao = "Doubao", Qwen = "Qwen", Hunyuan = "Hunyuan", Moonshot = "Moonshot", Iflytek = "Iflytek", XAI = "XAI", ChatGLM = "ChatGLM", DeepSeek = "DeepSeek", SiliconFlow = "SiliconFlow", "302.AI" = "302.AI", } export const Stability = { GeneratePath: "v2beta/stable-image/generate", ExampleEndpoint: "https://api.stability.ai", }; export const Anthropic = { ChatPath: "v1/messages", ChatPath1: "v1/complete", ExampleEndpoint: "https://api.anthropic.com", Vision: "2023-06-01", }; export const OpenaiPath = { ChatPath: "v1/chat/completions", SpeechPath: "v1/audio/speech", ImagePath: "v1/images/generations", UsagePath: "dashboard/billing/usage", SubsPath: "dashboard/billing/subscription", ListModelPath: "v1/models", }; export const Azure = { ChatPath: (deployName: string, apiVersion: string) => `deployments/${deployName}/chat/completions?api-version=${apiVersion}`, // https://<your_resource_name>.openai.azure.com/openai/deployments/<your_deployment_name>/images/generations?api-version=<api_version> ImagePath: (deployName: string, apiVersion: string) => `deployments/${deployName}/images/generations?api-version=${apiVersion}`, ExampleEndpoint: "https://{resource-url}/openai", }; export const Google = { ExampleEndpoint: "https://generativelanguage.googleapis.com/", ChatPath: (modelName: string) => `v1beta/models/${modelName}:streamGenerateContent`, }; export const Baidu = { ExampleEndpoint: BAIDU_BASE_URL, ChatPath: (modelName: string) => { let endpoint = modelName; if (modelName === "ernie-4.0-8k") { endpoint = "completions_pro"; } if (modelName === "ernie-4.0-8k-preview-0518") { endpoint = "completions_adv_pro"; } if (modelName === "ernie-3.5-8k") { endpoint = "completions"; } if (modelName === "ernie-speed-8k") { endpoint = "ernie_speed"; } return `rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${endpoint}`; }, }; export const ByteDance = { ExampleEndpoint: "https://ark.cn-beijing.volces.com/api/", ChatPath: "api/v3/chat/completions", }; export const Alibaba = { ExampleEndpoint: ALIBABA_BASE_URL, ChatPath: (modelName: string) => { if (modelName.includes("vl") || modelName.includes("omni")) { return "v1/services/aigc/multimodal-generation/generation"; } return `v1/services/aigc/text-generation/generation`; }, }; export const Tencent = { ExampleEndpoint: TENCENT_BASE_URL, }; export const Moonshot = { ExampleEndpoint: MOONSHOT_BASE_URL, ChatPath: "v1/chat/completions", }; export const Iflytek = { ExampleEndpoint: IFLYTEK_BASE_URL, ChatPath: "v1/chat/completions", }; export const DeepSeek = { ExampleEndpoint: DEEPSEEK_BASE_URL, ChatPath: "chat/completions", }; export const XAI = { ExampleEndpoint: XAI_BASE_URL, ChatPath: "v1/chat/completions", }; export const ChatGLM = { ExampleEndpoint: CHATGLM_BASE_URL, ChatPath: "api/paas/v4/chat/completions", ImagePath: "api/paas/v4/images/generations", VideoPath: "api/paas/v4/videos/generations", }; export const SiliconFlow = { ExampleEndpoint: SILICONFLOW_BASE_URL, ChatPath: "v1/chat/completions", ListModelPath: "v1/models?&sub_type=chat", }; export const AI302 = { ExampleEndpoint: AI302_BASE_URL, ChatPath: "v1/chat/completions", EmbeddingsPath: "jina/v1/embeddings", ListModelPath: "v1/models?llm=1", }; export const DEFAULT_INPUT_TEMPLATE = `{{input}}`; // input / time / model / lang // export const DEFAULT_SYSTEM_TEMPLATE = ` // You are ChatGPT, a large language model trained by {{ServiceProvider}}. // Knowledge cutoff: {{cutoff}} // Current model: {{model}} // Current time: {{time}} // Latex inline: $x^2$ // Latex block: $$e=mc^2$$ // `; export const DEFAULT_SYSTEM_TEMPLATE = ` You are ChatGPT, a large language model trained by {{ServiceProvider}}. Knowledge cutoff: {{cutoff}} Current model: {{model}} Current time: {{time}} Latex inline: \\(x^2\\) Latex block: $$e=mc^2$$ `; export const MCP_TOOLS_TEMPLATE = ` [clientId] {{ clientId }} [tools] {{ tools }} `; export const MCP_SYSTEM_TEMPLATE = ` You are an AI assistant with access to system tools. Your role is to help users by combining natural language understanding with tool operations when needed. 1. AVAILABLE TOOLS: {{ MCP_TOOLS }} 2. WHEN TO USE TOOLS: - ALWAYS USE TOOLS when they can help answer user questions - DO NOT just describe what you could do - TAKE ACTION immediately - If you're not sure whether to use a tool, USE IT - Common triggers for tool use: * Questions about files or directories * Requests to check, list, or manipulate system resources * Any query that can be answered with available tools 3. HOW TO USE TOOLS: A. Tool Call Format: - Use markdown code blocks with format: \`\`\`json:mcp:{clientId}\`\`\` - Always include: * method: "tools/call"(Only this method is supported) * params: - name: must match an available primitive name - arguments: required parameters for the primitive B. Response Format: - Tool responses will come as user messages - Format: \`\`\`json:mcp-response:{clientId}\`\`\` - Wait for response before making another tool call C. Important Rules: - Only use tools/call method - Only ONE tool call per message - ALWAYS TAKE ACTION instead of just describing what you could do - Include the correct clientId in code block language tag - Verify arguments match the primitive's requirements 4. INTERACTION FLOW: A. When user makes a request: - IMMEDIATELY use appropriate tool if available - DO NOT ask if user wants you to use the tool - DO NOT just describe what you could do B. After receiving tool response: - Explain results clearly - Take next appropriate action if needed C. If tools fail: - Explain the error - Try alternative approach immediately 5. EXAMPLE INTERACTION: good example: \`\`\`json:mcp:filesystem { "method": "tools/call", "params": { "name": "list_allowed_directories", "arguments": {} } } \`\`\`" \`\`\`json:mcp-response:filesystem { "method": "tools/call", "params": { "name": "write_file", "arguments": { "path": "/Users/river/dev/nextchat/test/joke.txt", "content": "为什么数学书总是感到忧伤?因为它有太多的问题。" } } } \`\`\` follwing is the wrong! mcp json example: \`\`\`json:mcp:filesystem { "method": "write_file", "params": { "path": "NextChat_Information.txt", "content": "1" } } \`\`\` This is wrong because the method is not tools/call. \`\`\`{ "method": "search_repositories", "params": { "query": "2oeee" } } \`\`\` This is wrong because the method is not tools/call.!!!!!!!!!!! the right format is: \`\`\`json:mcp:filesystem { "method": "tools/call", "params": { "name": "search_repositories", "arguments": { "query": "2oeee" } } } \`\`\` please follow the format strictly ONLY use tools/call method!!!!!!!!!!! `; export const SUMMARIZE_MODEL = "gpt-4o-mini"; export const GEMINI_SUMMARIZE_MODEL = "gemini-pro"; export const DEEPSEEK_SUMMARIZE_MODEL = "deepseek-chat"; export const KnowledgeCutOffDate: Record<string, string> = { default: "2021-09", "gpt-4-turbo": "2023-12", "gpt-4-turbo-2024-04-09": "2023-12", "gpt-4-turbo-preview": "2023-12", "gpt-4.1": "2024-06", "gpt-4.1-2025-04-14": "2024-06", "gpt-4.1-mini": "2024-06", "gpt-4.1-mini-2025-04-14": "2024-06", "gpt-4.1-nano": "2024-06", "gpt-4.1-nano-2025-04-14": "2024-06", "gpt-4.5-preview": "2023-10", "gpt-4.5-preview-2025-02-27": "2023-10", "gpt-4o": "2023-10", "gpt-4o-2024-05-13": "2023-10", "gpt-4o-2024-08-06": "2023-10", "gpt-4o-2024-11-20": "2023-10", "chatgpt-4o-latest": "2023-10", "gpt-4o-mini": "2023-10", "gpt-4o-mini-2024-07-18": "2023-10", "gpt-4-vision-preview": "2023-04", "o1-mini-2024-09-12": "2023-10", "o1-mini": "2023-10", "o1-preview-2024-09-12": "2023-10", "o1-preview": "2023-10", "o1-2024-12-17": "2023-10", o1: "2023-10", "o3-mini-2025-01-31": "2023-10", "o3-mini": "2023-10", // After improvements, // it's now easier to add "KnowledgeCutOffDate" instead of stupid hardcoding it, as was done previously. "gemini-pro": "2023-12", "gemini-pro-vision": "2023-12", "deepseek-chat": "2024-07", "deepseek-coder": "2024-07", }; export const DEFAULT_TTS_ENGINE = "OpenAI-TTS"; export const DEFAULT_TTS_ENGINES = ["OpenAI-TTS", "Edge-TTS"]; export const DEFAULT_TTS_MODEL = "tts-1"; export const DEFAULT_TTS_VOICE = "alloy"; export const DEFAULT_TTS_MODELS = ["tts-1", "tts-1-hd"]; export const DEFAULT_TTS_VOICES = [ "alloy", "echo", "fable", "onyx", "nova", "shimmer", ]; export const VISION_MODEL_REGEXES = [ /vision/, /gpt-4o/, /gpt-4\.1/, /claude.*[34]/, /gemini-1\.5/, /gemini-exp/, /gemini-2\.[05]/, /learnlm/, /qwen-vl/, /qwen2-vl/, /gpt-4-turbo(?!.*preview)/, /^dall-e-3$/, /glm-4v/, /vl/i, /o3/, /o4-mini/, /grok-4/i, /gpt-5/ ]; export const EXCLUDE_VISION_MODEL_REGEXES = [/claude-3-5-haiku-20241022/]; const openaiModels = [ // As of July 2024, gpt-4o-mini should be used in place of gpt-3.5-turbo, // as it is cheaper, more capable, multimodal, and just as fast. gpt-3.5-turbo is still available for use in the API. "gpt-3.5-turbo", "gpt-3.5-turbo-1106", "gpt-3.5-turbo-0125", "gpt-4", "gpt-4-0613", "gpt-4-32k", "gpt-4-32k-0613", "gpt-4-turbo", "gpt-4-turbo-preview", "gpt-4.1", "gpt-4.1-2025-04-14", "gpt-4.1-mini", "gpt-4.1-mini-2025-04-14", "gpt-4.1-nano", "gpt-4.1-nano-2025-04-14", "gpt-4.5-preview", "gpt-4.5-preview-2025-02-27", "gpt-5-chat", "gpt-5-mini", "gpt-5-nano", "gpt-5", "gpt-5-chat-2025-01-01-preview", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-2024-11-20", "chatgpt-4o-latest", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "gpt-4-vision-preview", "gpt-4-turbo-2024-04-09", "gpt-4-1106-preview", "dall-e-3", "o1-mini", "o1-preview", "o3-mini", "o3", "o4-mini", ]; const googleModels = [ "gemini-1.5-pro-latest", "gemini-1.5-pro", "gemini-1.5-pro-002", "gemini-1.5-flash-latest", "gemini-1.5-flash-8b-latest", "gemini-1.5-flash", "gemini-1.5-flash-8b", "gemini-1.5-flash-002", "learnlm-1.5-pro-experimental", "gemini-exp-1206", "gemini-2.0-flash", "gemini-2.0-flash-exp", "gemini-2.0-flash-lite-preview-02-05", "gemini-2.0-flash-thinking-exp", "gemini-2.0-flash-thinking-exp-1219", "gemini-2.0-flash-thinking-exp-01-21", "gemini-2.0-pro-exp", "gemini-2.0-pro-exp-02-05", "gemini-2.5-pro-preview-06-05", "gemini-2.5-pro" ]; const anthropicModels = [ "claude-instant-1.2", "claude-2.0", "claude-2.1", "claude-3-sonnet-20240229", "claude-3-opus-20240229", "claude-3-opus-latest", "claude-3-haiku-20240307", "claude-3-5-haiku-20241022", "claude-3-5-haiku-latest", "claude-3-5-sonnet-20240620", "claude-3-5-sonnet-20241022", "claude-3-5-sonnet-latest", "claude-3-7-sonnet-20250219", "claude-3-7-sonnet-latest", "claude-sonnet-4-20250514", "claude-opus-4-20250514", ]; const baiduModels = [ "ernie-4.0-turbo-8k", "ernie-4.0-8k", "ernie-4.0-8k-preview", "ernie-4.0-8k-preview-0518", "ernie-4.0-8k-latest", "ernie-3.5-8k", "ernie-3.5-8k-0205", "ernie-speed-128k", "ernie-speed-8k", "ernie-lite-8k", "ernie-tiny-8k", ]; const bytedanceModels = [ "Doubao-lite-4k", "Doubao-lite-32k", "Doubao-lite-128k", "Doubao-pro-4k", "Doubao-pro-32k", "Doubao-pro-128k", ]; const alibabaModes = [ "qwen-turbo", "qwen-plus", "qwen-max", "qwen-max-0428", "qwen-max-0403", "qwen-max-0107", "qwen-max-longcontext", "qwen-omni-turbo", "qwen-vl-plus", "qwen-vl-max", ]; const tencentModels = [ "hunyuan-pro", "hunyuan-standard", "hunyuan-lite", "hunyuan-role", "hunyuan-functioncall", "hunyuan-code", "hunyuan-vision", ]; const moonshotModels = [ "moonshot-v1-auto", "moonshot-v1-8k", "moonshot-v1-32k", "moonshot-v1-128k", "moonshot-v1-8k-vision-preview", "moonshot-v1-32k-vision-preview", "moonshot-v1-128k-vision-preview", "kimi-thinking-preview", "kimi-k2-0711-preview", "kimi-latest", ]; const iflytekModels = [ "general", "generalv3", "pro-128k", "generalv3.5", "4.0Ultra", ]; const deepseekModels = ["deepseek-chat", "deepseek-coder", "deepseek-reasoner"]; const xAIModes = [ "grok-beta", "grok-2", "grok-2-1212", "grok-2-latest", "grok-vision-beta", "grok-2-vision-1212", "grok-2-vision", "grok-2-vision-latest", "grok-3-mini-fast-beta", "grok-3-mini-fast", "grok-3-mini-fast-latest", "grok-3-mini-beta", "grok-3-mini", "grok-3-mini-latest", "grok-3-fast-beta", "grok-3-fast", "grok-3-fast-latest", "grok-3-beta", "grok-3", "grok-3-latest", "grok-4", "grok-4-0709", "grok-4-fast-non-reasoning", "grok-4-fast-reasoning", "grok-code-fast-1", ]; const chatglmModels = [ "glm-4-plus", "glm-4-0520", "glm-4", "glm-4-air", "glm-4-airx", "glm-4-long", "glm-4-flashx", "glm-4-flash", "glm-4v-plus", "glm-4v", "glm-4v-flash", // free "cogview-3-plus", "cogview-3", "cogview-3-flash", // free // 目前无法适配轮询任务 // "cogvideox", // "cogvideox-flash", // free ]; const siliconflowModels = [ "Qwen/Qwen2.5-7B-Instruct", "Qwen/Qwen2.5-72B-Instruct", "deepseek-ai/DeepSeek-R1", "deepseek-ai/DeepSeek-R1-Distill-Llama-70B", "deepseek-ai/DeepSeek-R1-Distill-Llama-8B", "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B", "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", "deepseek-ai/DeepSeek-V3", "meta-llama/Llama-3.3-70B-Instruct", "THUDM/glm-4-9b-chat", "Pro/deepseek-ai/DeepSeek-R1", "Pro/deepseek-ai/DeepSeek-V3", ]; const ai302Models = [ "deepseek-chat", "gpt-4o", "chatgpt-4o-latest", "llama3.3-70b", "deepseek-reasoner", "gemini-2.0-flash", "claude-3-7-sonnet-20250219", "claude-3-7-sonnet-latest", "grok-3-beta", "grok-3-mini-beta", "gpt-4.1", "gpt-4.1-mini", "o3", "o4-mini", "qwen3-235b-a22b", "qwen3-32b", "gemini-2.5-pro-preview-05-06", "llama-4-maverick", "gemini-2.5-flash", "claude-sonnet-4-20250514", "claude-opus-4-20250514", "gemini-2.5-pro", ]; let seq = 1000; // 内置的模型序号生成器从1000开始 export const DEFAULT_MODELS = [ ...openaiModels.map((name) => ({ name, available: true, sorted: seq++, // Global sequence sort(index) provider: { id: "openai", providerName: "OpenAI", providerType: "openai", sorted: 1, // 这里是固定的,确保顺序与之前内置的版本一致 }, })), ...openaiModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "azure", providerName: "Azure", providerType: "azure", sorted: 2, }, })), ...googleModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "google", providerName: "Google", providerType: "google", sorted: 3, }, })), ...anthropicModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "anthropic", providerName: "Anthropic", providerType: "anthropic", sorted: 4, }, })), ...baiduModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "baidu", providerName: "Baidu", providerType: "baidu", sorted: 5, }, })), ...bytedanceModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "bytedance", providerName: "ByteDance", providerType: "bytedance", sorted: 6, }, })), ...alibabaModes.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "alibaba", providerName: "Alibaba", providerType: "alibaba", sorted: 7, }, })), ...tencentModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "tencent", providerName: "Tencent", providerType: "tencent", sorted: 8, }, })), ...moonshotModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "moonshot", providerName: "Moonshot", providerType: "moonshot", sorted: 9, }, })), ...iflytekModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "iflytek", providerName: "Iflytek", providerType: "iflytek", sorted: 10, }, })), ...xAIModes.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "xai", providerName: "XAI", providerType: "xai", sorted: 11, }, })), ...chatglmModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "chatglm", providerName: "ChatGLM", providerType: "chatglm", sorted: 12, }, })), ...deepseekModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "deepseek", providerName: "DeepSeek", providerType: "deepseek", sorted: 13, }, })), ...siliconflowModels.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "siliconflow", providerName: "SiliconFlow", providerType: "siliconflow", sorted: 14, }, })), ...ai302Models.map((name) => ({ name, available: true, sorted: seq++, provider: { id: "ai302", providerName: "302.AI", providerType: "ai302", sorted: 15, }, })), ] as const; export const CHAT_PAGE_SIZE = 15; export const MAX_RENDER_MSG_COUNT = 45; // some famous webdav endpoints export const internalAllowedWebDavEndpoints = [ "https://dav.jianguoyun.com/dav/", "https://dav.dropdav.com/", "https://dav.box.com/dav", "https://nanao.teracloud.jp/dav/", "https://bora.teracloud.jp/dav/", "https://webdav.4shared.com/", "https://dav.idrivesync.com", "https://webdav.yandex.com", "https://app.koofr.net/dav/Koofr", ]; export const DEFAULT_GA_ID = "G-89WN60ZK2E"; export const SAAS_CHAT_URL = "https://nextchat.club"; export const SAAS_CHAT_UTM_URL = "https://nextchat.club?utm=github";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/layout.tsx
app/layout.tsx
/* eslint-disable @next/next/no-page-custom-font */ import "./styles/globals.scss"; import "./styles/markdown.scss"; import "./styles/highlight.scss"; import { getClientConfig } from "./config/client"; import type { Metadata, Viewport } from "next"; import { SpeedInsights } from "@vercel/speed-insights/next"; import { GoogleTagManager, GoogleAnalytics } from "@next/third-parties/google"; import { getServerSideConfig } from "./config/server"; export const metadata: Metadata = { title: "NextChat", description: "Your personal ChatGPT Chat Bot.", appleWebApp: { title: "NextChat", statusBarStyle: "default", }, }; export const viewport: Viewport = { width: "device-width", initialScale: 1, maximumScale: 1, themeColor: [ { media: "(prefers-color-scheme: light)", color: "#fafafa" }, { media: "(prefers-color-scheme: dark)", color: "#151515" }, ], }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { const serverConfig = getServerSideConfig(); return ( <html lang="en"> <head> <meta name="config" content={JSON.stringify(getClientConfig())} /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <link rel="manifest" href="/site.webmanifest" crossOrigin="use-credentials" ></link> <script src="/serviceWorkerRegister.js" defer></script> </head> <body> {children} {serverConfig?.isVercel && ( <> <SpeedInsights /> </> )} {serverConfig?.gtmId && ( <> <GoogleTagManager gtmId={serverConfig.gtmId} /> </> )} {serverConfig?.gaId && ( <> <GoogleAnalytics gaId={serverConfig.gaId} /> </> )} </body> </html> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils.ts
app/utils.ts
import { useEffect, useState } from "react"; import { showToast } from "./components/ui-lib"; import Locale from "./locales"; import { RequestMessage } from "./client/api"; import { REQUEST_TIMEOUT_MS, REQUEST_TIMEOUT_MS_FOR_THINKING, ServiceProvider, } from "./constant"; // import { fetch as tauriFetch, ResponseType } from "@tauri-apps/api/http"; import { fetch as tauriStreamFetch } from "./utils/stream"; import { VISION_MODEL_REGEXES, EXCLUDE_VISION_MODEL_REGEXES } from "./constant"; import { useAccessStore } from "./store"; import { ModelSize } from "./typing"; export function trimTopic(topic: string) { // Fix an issue where double quotes still show in the Indonesian language // This will remove the specified punctuation from the end of the string // and also trim quotes from both the start and end if they exist. return ( topic // fix for gemini .replace(/^["“”*]+|["“”*]+$/g, "") .replace(/[,。!?”“"、,.!?*]*$/, "") ); } export async function copyToClipboard(text: string) { try { if (window.__TAURI__) { window.__TAURI__.writeText(text); } else { await navigator.clipboard.writeText(text); } showToast(Locale.Copy.Success); } catch (error) { const textArea = document.createElement("textarea"); textArea.value = text; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { document.execCommand("copy"); showToast(Locale.Copy.Success); } catch (error) { showToast(Locale.Copy.Failed); } document.body.removeChild(textArea); } } export async function downloadAs(text: string, filename: string) { if (window.__TAURI__) { const result = await window.__TAURI__.dialog.save({ defaultPath: `${filename}`, filters: [ { name: `${filename.split(".").pop()} files`, extensions: [`${filename.split(".").pop()}`], }, { name: "All Files", extensions: ["*"], }, ], }); if (result !== null) { try { await window.__TAURI__.fs.writeTextFile(result, text); showToast(Locale.Download.Success); } catch (error) { showToast(Locale.Download.Failed); } } else { showToast(Locale.Download.Failed); } } else { const element = document.createElement("a"); element.setAttribute( "href", "data:text/plain;charset=utf-8," + encodeURIComponent(text), ); element.setAttribute("download", filename); element.style.display = "none"; document.body.appendChild(element); element.click(); document.body.removeChild(element); } } export function readFromFile() { return new Promise<string>((res, rej) => { const fileInput = document.createElement("input"); fileInput.type = "file"; fileInput.accept = "application/json"; fileInput.onchange = (event: any) => { const file = event.target.files[0]; const fileReader = new FileReader(); fileReader.onload = (e: any) => { res(e.target.result); }; fileReader.onerror = (e) => rej(e); fileReader.readAsText(file); }; fileInput.click(); }); } export function isIOS() { const userAgent = navigator.userAgent.toLowerCase(); return /iphone|ipad|ipod/.test(userAgent); } export function useWindowSize() { const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight, }); useEffect(() => { const onResize = () => { setSize({ width: window.innerWidth, height: window.innerHeight, }); }; window.addEventListener("resize", onResize); return () => { window.removeEventListener("resize", onResize); }; }, []); return size; } export const MOBILE_MAX_WIDTH = 600; export function useMobileScreen() { const { width } = useWindowSize(); return width <= MOBILE_MAX_WIDTH; } export function isFirefox() { return ( typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent) ); } export function selectOrCopy(el: HTMLElement, content: string) { const currentSelection = window.getSelection(); if (currentSelection?.type === "Range") { return false; } copyToClipboard(content); return true; } function getDomContentWidth(dom: HTMLElement) { const style = window.getComputedStyle(dom); const paddingWidth = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight); const width = dom.clientWidth - paddingWidth; return width; } function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) { let dom = document.getElementById(id); if (!dom) { dom = document.createElement("span"); dom.style.position = "absolute"; dom.style.wordBreak = "break-word"; dom.style.fontSize = "14px"; dom.style.transform = "translateY(-200vh)"; dom.style.pointerEvents = "none"; dom.style.opacity = "0"; dom.id = id; document.body.appendChild(dom); init?.(dom); } return dom!; } export function autoGrowTextArea(dom: HTMLTextAreaElement) { const measureDom = getOrCreateMeasureDom("__measure"); const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => { dom.innerText = "TEXT_FOR_MEASURE"; }); const width = getDomContentWidth(dom); measureDom.style.width = width + "px"; measureDom.innerText = dom.value !== "" ? dom.value : "1"; measureDom.style.fontSize = dom.style.fontSize; measureDom.style.fontFamily = dom.style.fontFamily; const endWithEmptyLine = dom.value.endsWith("\n"); const height = parseFloat(window.getComputedStyle(measureDom).height); const singleLineHeight = parseFloat( window.getComputedStyle(singleLineDom).height, ); const rows = Math.round(height / singleLineHeight) + (endWithEmptyLine ? 1 : 0); return rows; } export function getCSSVar(varName: string) { return getComputedStyle(document.body).getPropertyValue(varName).trim(); } /** * Detects Macintosh */ export function isMacOS(): boolean { if (typeof window !== "undefined") { let userAgent = window.navigator.userAgent.toLocaleLowerCase(); const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent); return !!macintosh; } return false; } export function getMessageTextContent(message: RequestMessage) { if (typeof message.content === "string") { return message.content; } for (const c of message.content) { if (c.type === "text") { return c.text ?? ""; } } return ""; } export function getMessageTextContentWithoutThinking(message: RequestMessage) { let content = ""; if (typeof message.content === "string") { content = message.content; } else { for (const c of message.content) { if (c.type === "text") { content = c.text ?? ""; break; } } } // Filter out thinking lines (starting with "> ") return content .split("\n") .filter((line) => !line.startsWith("> ") && line.trim() !== "") .join("\n") .trim(); } export function getMessageImages(message: RequestMessage): string[] { if (typeof message.content === "string") { return []; } const urls: string[] = []; for (const c of message.content) { if (c.type === "image_url") { urls.push(c.image_url?.url ?? ""); } } return urls; } export function isVisionModel(model: string) { const visionModels = useAccessStore.getState().visionModels; const envVisionModels = visionModels?.split(",").map((m) => m.trim()); if (envVisionModels?.includes(model)) { return true; } return ( !EXCLUDE_VISION_MODEL_REGEXES.some((regex) => regex.test(model)) && VISION_MODEL_REGEXES.some((regex) => regex.test(model)) ); } export function isDalle3(model: string) { return "dall-e-3" === model; } export function getTimeoutMSByModel(model: string) { model = model.toLowerCase(); if ( model.startsWith("dall-e") || model.startsWith("dalle") || model.startsWith("o1") || model.startsWith("o3") || model.includes("deepseek-r") || model.includes("-thinking") ) return REQUEST_TIMEOUT_MS_FOR_THINKING; return REQUEST_TIMEOUT_MS; } export function getModelSizes(model: string): ModelSize[] { if (isDalle3(model)) { return ["1024x1024", "1792x1024", "1024x1792"]; } if (model.toLowerCase().includes("cogview")) { return [ "1024x1024", "768x1344", "864x1152", "1344x768", "1152x864", "1440x720", "720x1440", ]; } return []; } export function supportsCustomSize(model: string): boolean { return getModelSizes(model).length > 0; } export function showPlugins(provider: ServiceProvider, model: string) { if ( provider == ServiceProvider.OpenAI || provider == ServiceProvider.Azure || provider == ServiceProvider.Moonshot || provider == ServiceProvider.ChatGLM ) { return true; } if (provider == ServiceProvider.Anthropic && !model.includes("claude-2")) { return true; } if (provider == ServiceProvider.Google && !model.includes("vision")) { return true; } return false; } export function fetch( url: string, options?: Record<string, unknown>, ): Promise<any> { if (window.__TAURI__) { return tauriStreamFetch(url, options); } return window.fetch(url, options); } export function adapter(config: Record<string, unknown>) { const { baseURL, url, params, data: body, ...rest } = config; const path = baseURL ? `${baseURL}${url}` : url; const fetchUrl = params ? `${path}?${new URLSearchParams(params as any).toString()}` : path; return fetch(fetchUrl as string, { ...rest, body }).then((res) => { const { status, headers, statusText } = res; return res .text() .then((data: string) => ({ status, statusText, headers, data })); }); } export function safeLocalStorage(): { getItem: (key: string) => string | null; setItem: (key: string, value: string) => void; removeItem: (key: string) => void; clear: () => void; } { let storage: Storage | null; try { if (typeof window !== "undefined" && window.localStorage) { storage = window.localStorage; } else { storage = null; } } catch (e) { console.error("localStorage is not available:", e); storage = null; } return { getItem(key: string): string | null { if (storage) { return storage.getItem(key); } else { console.warn( `Attempted to get item "${key}" from localStorage, but localStorage is not available.`, ); return null; } }, setItem(key: string, value: string): void { if (storage) { storage.setItem(key, value); } else { console.warn( `Attempted to set item "${key}" in localStorage, but localStorage is not available.`, ); } }, removeItem(key: string): void { if (storage) { storage.removeItem(key); } else { console.warn( `Attempted to remove item "${key}" from localStorage, but localStorage is not available.`, ); } }, clear(): void { if (storage) { storage.clear(); } else { console.warn( "Attempted to clear localStorage, but localStorage is not available.", ); } }, }; } export function getOperationId(operation: { operationId?: string; method: string; path: string; }) { // pattern '^[a-zA-Z0-9_-]+$' return ( operation?.operationId || `${operation.method.toUpperCase()}${operation.path.replaceAll("/", "_")}` ); } export function clientUpdate() { // this a wild for updating client app return window.__TAURI__?.updater .checkUpdate() .then((updateResult) => { if (updateResult.shouldUpdate) { window.__TAURI__?.updater .installUpdate() .then((result) => { showToast(Locale.Settings.Update.Success); }) .catch((e) => { console.error("[Install Update Error]", e); showToast(Locale.Settings.Update.Failed); }); } }) .catch((e) => { console.error("[Check Update Error]", e); showToast(Locale.Settings.Update.Failed); }); } // https://gist.github.com/iwill/a83038623ba4fef6abb9efca87ae9ccb export function semverCompare(a: string, b: string) { if (a.startsWith(b + "-")) return -1; if (b.startsWith(a + "-")) return 1; return a.localeCompare(b, undefined, { numeric: true, sensitivity: "case", caseFirst: "upper", }); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/global.d.ts
app/global.d.ts
declare module "*.jpg"; declare module "*.png"; declare module "*.woff2"; declare module "*.woff"; declare module "*.ttf"; declare module "*.scss" { const content: Record<string, string>; export default content; } declare module "*.svg"; declare interface Window { __TAURI__?: { writeText(text: string): Promise<void>; invoke(command: string, payload?: Record<string, unknown>): Promise<any>; dialog: { save(options?: Record<string, unknown>): Promise<string | null>; }; fs: { writeBinaryFile(path: string, data: Uint8Array): Promise<void>; writeTextFile(path: string, data: string): Promise<void>; }; notification: { requestPermission(): Promise<Permission>; isPermissionGranted(): Promise<boolean>; sendNotification(options: string | Options): void; }; updater: { checkUpdate(): Promise<UpdateResult>; installUpdate(): Promise<void>; onUpdaterEvent( handler: (status: UpdateStatusResult) => void, ): Promise<UnlistenFn>; }; http: { fetch<T>( url: string, options?: Record<string, unknown>, ): Promise<Response<T>>; }; }; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/command.ts
app/command.ts
import { useEffect } from "react"; import { useSearchParams } from "react-router-dom"; import Locale from "./locales"; type Command = (param: string) => void; interface Commands { fill?: Command; submit?: Command; mask?: Command; code?: Command; settings?: Command; } export function useCommand(commands: Commands = {}) { const [searchParams, setSearchParams] = useSearchParams(); useEffect(() => { let shouldUpdate = false; searchParams.forEach((param, name) => { const commandName = name as keyof Commands; if (typeof commands[commandName] === "function") { commands[commandName]!(param); searchParams.delete(name); shouldUpdate = true; } }); if (shouldUpdate) { setSearchParams(searchParams); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [searchParams, commands]); } interface ChatCommands { new?: Command; newm?: Command; next?: Command; prev?: Command; clear?: Command; fork?: Command; del?: Command; } // Compatible with Chinese colon character ":" export const ChatCommandPrefix = /^[::]/; export function useChatCommand(commands: ChatCommands = {}) { function extract(userInput: string) { const match = userInput.match(ChatCommandPrefix); if (match) { return userInput.slice(1) as keyof ChatCommands; } return userInput as keyof ChatCommands; } function search(userInput: string) { const input = extract(userInput); const desc = Locale.Chat.Commands; return Object.keys(commands) .filter((c) => c.startsWith(input)) .map((c) => ({ title: desc[c as keyof ChatCommands], content: ":" + c, })); } function match(userInput: string) { const command = extract(userInput); const matched = typeof commands[command] === "function"; return { matched, invoke: () => matched && commands[command]!(userInput), }; } return { match, search }; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/page.tsx
app/page.tsx
import { Analytics } from "@vercel/analytics/react"; import { Home } from "./components/home"; import { getServerSideConfig } from "./config/server"; const serverConfig = getServerSideConfig(); export default async function App() { return ( <> <Home /> {serverConfig?.isVercel && ( <> <Analytics /> </> )} </> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/polyfill.ts
app/polyfill.ts
declare global { interface Array<T> { at(index: number): T | undefined; } } if (!Array.prototype.at) { Array.prototype.at = function (index: number) { // Get the length of the array const length = this.length; // Convert negative index to a positive index if (index < 0) { index = length + index; } // Return undefined if the index is out of range if (index < 0 || index >= length) { return undefined; } // Use Array.prototype.slice method to get value at the specified index return Array.prototype.slice.call(this, index, index + 1)[0]; }; } export {};
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/config.ts
app/store/config.ts
import { LLMModel } from "../client/api"; import { DalleQuality, DalleStyle, ModelSize } from "../typing"; import { getClientConfig } from "../config/client"; import { DEFAULT_INPUT_TEMPLATE, DEFAULT_MODELS, DEFAULT_SIDEBAR_WIDTH, DEFAULT_TTS_ENGINE, DEFAULT_TTS_ENGINES, DEFAULT_TTS_MODEL, DEFAULT_TTS_MODELS, DEFAULT_TTS_VOICE, DEFAULT_TTS_VOICES, StoreKey, ServiceProvider, } from "../constant"; import { createPersistStore } from "../utils/store"; import type { Voice } from "rt-client"; export type ModelType = (typeof DEFAULT_MODELS)[number]["name"]; export type TTSModelType = (typeof DEFAULT_TTS_MODELS)[number]; export type TTSVoiceType = (typeof DEFAULT_TTS_VOICES)[number]; export type TTSEngineType = (typeof DEFAULT_TTS_ENGINES)[number]; export enum SubmitKey { Enter = "Enter", CtrlEnter = "Ctrl + Enter", ShiftEnter = "Shift + Enter", AltEnter = "Alt + Enter", MetaEnter = "Meta + Enter", } export enum Theme { Auto = "auto", Dark = "dark", Light = "light", } const config = getClientConfig(); export const DEFAULT_CONFIG = { lastUpdate: Date.now(), // timestamp, to merge state submitKey: SubmitKey.Enter, avatar: "1f603", fontSize: 14, fontFamily: "", theme: Theme.Auto as Theme, tightBorder: !!config?.isApp, sendPreviewBubble: true, enableAutoGenerateTitle: true, sidebarWidth: DEFAULT_SIDEBAR_WIDTH, enableArtifacts: true, // show artifacts config enableCodeFold: true, // code fold config disablePromptHint: false, dontShowMaskSplashScreen: false, // dont show splash screen when create chat hideBuiltinMasks: false, // dont add builtin masks customModels: "", models: DEFAULT_MODELS as any as LLMModel[], modelConfig: { model: "gpt-4o-mini" as ModelType, providerName: "OpenAI" as ServiceProvider, temperature: 0.5, top_p: 1, max_tokens: 4000, presence_penalty: 0, frequency_penalty: 0, sendMemory: true, historyMessageCount: 4, compressMessageLengthThreshold: 1000, compressModel: "", compressProviderName: "", enableInjectSystemPrompts: true, template: config?.template ?? DEFAULT_INPUT_TEMPLATE, size: "1024x1024" as ModelSize, quality: "standard" as DalleQuality, style: "vivid" as DalleStyle, }, ttsConfig: { enable: false, autoplay: false, engine: DEFAULT_TTS_ENGINE, model: DEFAULT_TTS_MODEL, voice: DEFAULT_TTS_VOICE, speed: 1.0, }, realtimeConfig: { enable: false, provider: "OpenAI" as ServiceProvider, model: "gpt-4o-realtime-preview-2024-10-01", apiKey: "", azure: { endpoint: "", deployment: "", }, temperature: 0.9, voice: "alloy" as Voice, }, }; export type ChatConfig = typeof DEFAULT_CONFIG; export type ModelConfig = ChatConfig["modelConfig"]; export type TTSConfig = ChatConfig["ttsConfig"]; export type RealtimeConfig = ChatConfig["realtimeConfig"]; export function limitNumber( x: number, min: number, max: number, defaultValue: number, ) { if (isNaN(x)) { return defaultValue; } return Math.min(max, Math.max(min, x)); } export const TTSConfigValidator = { engine(x: string) { return x as TTSEngineType; }, model(x: string) { return x as TTSModelType; }, voice(x: string) { return x as TTSVoiceType; }, speed(x: number) { return limitNumber(x, 0.25, 4.0, 1.0); }, }; export const ModalConfigValidator = { model(x: string) { return x as ModelType; }, max_tokens(x: number) { return limitNumber(x, 0, 512000, 1024); }, presence_penalty(x: number) { return limitNumber(x, -2, 2, 0); }, frequency_penalty(x: number) { return limitNumber(x, -2, 2, 0); }, temperature(x: number) { return limitNumber(x, 0, 2, 1); }, top_p(x: number) { return limitNumber(x, 0, 1, 1); }, }; export const useAppConfig = createPersistStore( { ...DEFAULT_CONFIG }, (set, get) => ({ reset() { set(() => ({ ...DEFAULT_CONFIG })); }, mergeModels(newModels: LLMModel[]) { if (!newModels || newModels.length === 0) { return; } const oldModels = get().models; const modelMap: Record<string, LLMModel> = {}; for (const model of oldModels) { model.available = false; modelMap[`${model.name}@${model?.provider?.id}`] = model; } for (const model of newModels) { model.available = true; modelMap[`${model.name}@${model?.provider?.id}`] = model; } set(() => ({ models: Object.values(modelMap), })); }, allModels() {}, }), { name: StoreKey.Config, version: 4.1, merge(persistedState, currentState) { const state = persistedState as ChatConfig | undefined; if (!state) return { ...currentState }; const models = currentState.models.slice(); state.models.forEach((pModel) => { const idx = models.findIndex( (v) => v.name === pModel.name && v.provider === pModel.provider, ); if (idx !== -1) models[idx] = pModel; else models.push(pModel); }); return { ...currentState, ...state, models: models }; }, migrate(persistedState, version) { const state = persistedState as ChatConfig; if (version < 3.4) { state.modelConfig.sendMemory = true; state.modelConfig.historyMessageCount = 4; state.modelConfig.compressMessageLengthThreshold = 1000; state.modelConfig.frequency_penalty = 0; state.modelConfig.top_p = 1; state.modelConfig.template = DEFAULT_INPUT_TEMPLATE; state.dontShowMaskSplashScreen = false; state.hideBuiltinMasks = false; } if (version < 3.5) { state.customModels = "claude,claude-100k"; } if (version < 3.6) { state.modelConfig.enableInjectSystemPrompts = true; } if (version < 3.7) { state.enableAutoGenerateTitle = true; } if (version < 3.8) { state.lastUpdate = Date.now(); } if (version < 3.9) { state.modelConfig.template = state.modelConfig.template !== DEFAULT_INPUT_TEMPLATE ? state.modelConfig.template : config?.template ?? DEFAULT_INPUT_TEMPLATE; } if (version < 4.1) { state.modelConfig.compressModel = DEFAULT_CONFIG.modelConfig.compressModel; state.modelConfig.compressProviderName = DEFAULT_CONFIG.modelConfig.compressProviderName; } return state as any; }, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/chat.ts
app/store/chat.ts
import { getMessageTextContent, isDalle3, safeLocalStorage, trimTopic, } from "../utils"; import { indexedDBStorage } from "@/app/utils/indexedDB-storage"; import { nanoid } from "nanoid"; import type { ClientApi, MultimodalContent, RequestMessage, } from "../client/api"; import { getClientApi } from "../client/api"; import { ChatControllerPool } from "../client/controller"; import { showToast } from "../components/ui-lib"; import { DEFAULT_INPUT_TEMPLATE, DEFAULT_MODELS, DEFAULT_SYSTEM_TEMPLATE, GEMINI_SUMMARIZE_MODEL, DEEPSEEK_SUMMARIZE_MODEL, KnowledgeCutOffDate, MCP_SYSTEM_TEMPLATE, MCP_TOOLS_TEMPLATE, ServiceProvider, StoreKey, SUMMARIZE_MODEL, } from "../constant"; import Locale, { getLang } from "../locales"; import { prettyObject } from "../utils/format"; import { createPersistStore } from "../utils/store"; import { estimateTokenLength } from "../utils/token"; import { ModelConfig, ModelType, useAppConfig } from "./config"; import { useAccessStore } from "./access"; import { collectModelsWithDefaultModel } from "../utils/model"; import { createEmptyMask, Mask } from "./mask"; import { executeMcpAction, getAllTools, isMcpEnabled } from "../mcp/actions"; import { extractMcpJson, isMcpJson } from "../mcp/utils"; const localStorage = safeLocalStorage(); export type ChatMessageTool = { id: string; index?: number; type?: string; function?: { name: string; arguments?: string; }; content?: string; isError?: boolean; errorMsg?: string; }; export type ChatMessage = RequestMessage & { date: string; streaming?: boolean; isError?: boolean; id: string; model?: ModelType; tools?: ChatMessageTool[]; audio_url?: string; isMcpResponse?: boolean; }; export function createMessage(override: Partial<ChatMessage>): ChatMessage { return { id: nanoid(), date: new Date().toLocaleString(), role: "user", content: "", ...override, }; } export interface ChatStat { tokenCount: number; wordCount: number; charCount: number; } export interface ChatSession { id: string; topic: string; memoryPrompt: string; messages: ChatMessage[]; stat: ChatStat; lastUpdate: number; lastSummarizeIndex: number; clearContextIndex?: number; mask: Mask; } export const DEFAULT_TOPIC = Locale.Store.DefaultTopic; export const BOT_HELLO: ChatMessage = createMessage({ role: "assistant", content: Locale.Store.BotHello, }); function createEmptySession(): ChatSession { return { id: nanoid(), topic: DEFAULT_TOPIC, memoryPrompt: "", messages: [], stat: { tokenCount: 0, wordCount: 0, charCount: 0, }, lastUpdate: Date.now(), lastSummarizeIndex: 0, mask: createEmptyMask(), }; } function getSummarizeModel( currentModel: string, providerName: string, ): string[] { // if it is using gpt-* models, force to use 4o-mini to summarize if (currentModel.startsWith("gpt") || currentModel.startsWith("chatgpt")) { const configStore = useAppConfig.getState(); const accessStore = useAccessStore.getState(); const allModel = collectModelsWithDefaultModel( configStore.models, [configStore.customModels, accessStore.customModels].join(","), accessStore.defaultModel, ); const summarizeModel = allModel.find( (m) => m.name === SUMMARIZE_MODEL && m.available, ); if (summarizeModel) { return [ summarizeModel.name, summarizeModel.provider?.providerName as string, ]; } } if (currentModel.startsWith("gemini")) { return [GEMINI_SUMMARIZE_MODEL, ServiceProvider.Google]; } else if (currentModel.startsWith("deepseek-")) { return [DEEPSEEK_SUMMARIZE_MODEL, ServiceProvider.DeepSeek]; } return [currentModel, providerName]; } function countMessages(msgs: ChatMessage[]) { return msgs.reduce( (pre, cur) => pre + estimateTokenLength(getMessageTextContent(cur)), 0, ); } function fillTemplateWith(input: string, modelConfig: ModelConfig) { const cutoff = KnowledgeCutOffDate[modelConfig.model] ?? KnowledgeCutOffDate.default; // Find the model in the DEFAULT_MODELS array that matches the modelConfig.model const modelInfo = DEFAULT_MODELS.find((m) => m.name === modelConfig.model); var serviceProvider = "OpenAI"; if (modelInfo) { // TODO: auto detect the providerName from the modelConfig.model // Directly use the providerName from the modelInfo serviceProvider = modelInfo.provider.providerName; } const vars = { ServiceProvider: serviceProvider, cutoff, model: modelConfig.model, time: new Date().toString(), lang: getLang(), input: input, }; let output = modelConfig.template ?? DEFAULT_INPUT_TEMPLATE; // remove duplicate if (input.startsWith(output)) { output = ""; } // must contains {{input}} const inputVar = "{{input}}"; if (!output.includes(inputVar)) { output += "\n" + inputVar; } Object.entries(vars).forEach(([name, value]) => { const regex = new RegExp(`{{${name}}}`, "g"); output = output.replace(regex, value.toString()); // Ensure value is a string }); return output; } async function getMcpSystemPrompt(): Promise<string> { const tools = await getAllTools(); let toolsStr = ""; tools.forEach((i) => { // error client has no tools if (!i.tools) return; toolsStr += MCP_TOOLS_TEMPLATE.replace( "{{ clientId }}", i.clientId, ).replace( "{{ tools }}", i.tools.tools.map((p: object) => JSON.stringify(p, null, 2)).join("\n"), ); }); return MCP_SYSTEM_TEMPLATE.replace("{{ MCP_TOOLS }}", toolsStr); } const DEFAULT_CHAT_STATE = { sessions: [createEmptySession()], currentSessionIndex: 0, lastInput: "", }; export const useChatStore = createPersistStore( DEFAULT_CHAT_STATE, (set, _get) => { function get() { return { ..._get(), ...methods, }; } const methods = { forkSession() { // 获取当前会话 const currentSession = get().currentSession(); if (!currentSession) return; const newSession = createEmptySession(); newSession.topic = currentSession.topic; // 深拷贝消息 newSession.messages = currentSession.messages.map((msg) => ({ ...msg, id: nanoid(), // 生成新的消息 ID })); newSession.mask = { ...currentSession.mask, modelConfig: { ...currentSession.mask.modelConfig, }, }; set((state) => ({ currentSessionIndex: 0, sessions: [newSession, ...state.sessions], })); }, clearSessions() { set(() => ({ sessions: [createEmptySession()], currentSessionIndex: 0, })); }, selectSession(index: number) { set({ currentSessionIndex: index, }); }, moveSession(from: number, to: number) { set((state) => { const { sessions, currentSessionIndex: oldIndex } = state; // move the session const newSessions = [...sessions]; const session = newSessions[from]; newSessions.splice(from, 1); newSessions.splice(to, 0, session); // modify current session id let newIndex = oldIndex === from ? to : oldIndex; if (oldIndex > from && oldIndex <= to) { newIndex -= 1; } else if (oldIndex < from && oldIndex >= to) { newIndex += 1; } return { currentSessionIndex: newIndex, sessions: newSessions, }; }); }, newSession(mask?: Mask) { const session = createEmptySession(); if (mask) { const config = useAppConfig.getState(); const globalModelConfig = config.modelConfig; session.mask = { ...mask, modelConfig: { ...globalModelConfig, ...mask.modelConfig, }, }; session.topic = mask.name; } set((state) => ({ currentSessionIndex: 0, sessions: [session].concat(state.sessions), })); }, nextSession(delta: number) { const n = get().sessions.length; const limit = (x: number) => (x + n) % n; const i = get().currentSessionIndex; get().selectSession(limit(i + delta)); }, deleteSession(index: number) { const deletingLastSession = get().sessions.length === 1; const deletedSession = get().sessions.at(index); if (!deletedSession) return; const sessions = get().sessions.slice(); sessions.splice(index, 1); const currentIndex = get().currentSessionIndex; let nextIndex = Math.min( currentIndex - Number(index < currentIndex), sessions.length - 1, ); if (deletingLastSession) { nextIndex = 0; sessions.push(createEmptySession()); } // for undo delete action const restoreState = { currentSessionIndex: get().currentSessionIndex, sessions: get().sessions.slice(), }; set(() => ({ currentSessionIndex: nextIndex, sessions, })); showToast( Locale.Home.DeleteToast, { text: Locale.Home.Revert, onClick() { set(() => restoreState); }, }, 5000, ); }, currentSession() { let index = get().currentSessionIndex; const sessions = get().sessions; if (index < 0 || index >= sessions.length) { index = Math.min(sessions.length - 1, Math.max(0, index)); set(() => ({ currentSessionIndex: index })); } const session = sessions[index]; return session; }, onNewMessage(message: ChatMessage, targetSession: ChatSession) { get().updateTargetSession(targetSession, (session) => { session.messages = session.messages.concat(); session.lastUpdate = Date.now(); }); get().updateStat(message, targetSession); get().checkMcpJson(message); get().summarizeSession(false, targetSession); }, async onUserInput( content: string, attachImages?: string[], isMcpResponse?: boolean, ) { const session = get().currentSession(); const modelConfig = session.mask.modelConfig; // MCP Response no need to fill template let mContent: string | MultimodalContent[] = isMcpResponse ? content : fillTemplateWith(content, modelConfig); if (!isMcpResponse && attachImages && attachImages.length > 0) { mContent = [ ...(content ? [{ type: "text" as const, text: content }] : []), ...attachImages.map((url) => ({ type: "image_url" as const, image_url: { url }, })), ]; } let userMessage: ChatMessage = createMessage({ role: "user", content: mContent, isMcpResponse, }); const botMessage: ChatMessage = createMessage({ role: "assistant", streaming: true, model: modelConfig.model, }); // get recent messages const recentMessages = await get().getMessagesWithMemory(); const sendMessages = recentMessages.concat(userMessage); const messageIndex = session.messages.length + 1; // save user's and bot's message get().updateTargetSession(session, (session) => { const savedUserMessage = { ...userMessage, content: mContent, }; session.messages = session.messages.concat([ savedUserMessage, botMessage, ]); }); const api: ClientApi = getClientApi(modelConfig.providerName); // make request api.llm.chat({ messages: sendMessages, config: { ...modelConfig, stream: true }, onUpdate(message) { botMessage.streaming = true; if (message) { botMessage.content = message; } get().updateTargetSession(session, (session) => { session.messages = session.messages.concat(); }); }, async onFinish(message) { botMessage.streaming = false; if (message) { botMessage.content = message; botMessage.date = new Date().toLocaleString(); get().onNewMessage(botMessage, session); } ChatControllerPool.remove(session.id, botMessage.id); }, onBeforeTool(tool: ChatMessageTool) { (botMessage.tools = botMessage?.tools || []).push(tool); get().updateTargetSession(session, (session) => { session.messages = session.messages.concat(); }); }, onAfterTool(tool: ChatMessageTool) { botMessage?.tools?.forEach((t, i, tools) => { if (tool.id == t.id) { tools[i] = { ...tool }; } }); get().updateTargetSession(session, (session) => { session.messages = session.messages.concat(); }); }, onError(error) { const isAborted = error.message?.includes?.("aborted"); botMessage.content += "\n\n" + prettyObject({ error: true, message: error.message, }); botMessage.streaming = false; userMessage.isError = !isAborted; botMessage.isError = !isAborted; get().updateTargetSession(session, (session) => { session.messages = session.messages.concat(); }); ChatControllerPool.remove( session.id, botMessage.id ?? messageIndex, ); console.error("[Chat] failed ", error); }, onController(controller) { // collect controller for stop/retry ChatControllerPool.addController( session.id, botMessage.id ?? messageIndex, controller, ); }, }); }, getMemoryPrompt() { const session = get().currentSession(); if (session.memoryPrompt.length) { return { role: "system", content: Locale.Store.Prompt.History(session.memoryPrompt), date: "", } as ChatMessage; } }, async getMessagesWithMemory() { const session = get().currentSession(); const modelConfig = session.mask.modelConfig; const clearContextIndex = session.clearContextIndex ?? 0; const messages = session.messages.slice(); const totalMessageCount = session.messages.length; // in-context prompts const contextPrompts = session.mask.context.slice(); // system prompts, to get close to OpenAI Web ChatGPT const shouldInjectSystemPrompts = modelConfig.enableInjectSystemPrompts && (session.mask.modelConfig.model.startsWith("gpt-") || session.mask.modelConfig.model.startsWith("chatgpt-")); const mcpEnabled = await isMcpEnabled(); const mcpSystemPrompt = mcpEnabled ? await getMcpSystemPrompt() : ""; var systemPrompts: ChatMessage[] = []; if (shouldInjectSystemPrompts) { systemPrompts = [ createMessage({ role: "system", content: fillTemplateWith("", { ...modelConfig, template: DEFAULT_SYSTEM_TEMPLATE, }) + mcpSystemPrompt, }), ]; } else if (mcpEnabled) { systemPrompts = [ createMessage({ role: "system", content: mcpSystemPrompt, }), ]; } if (shouldInjectSystemPrompts || mcpEnabled) { console.log( "[Global System Prompt] ", systemPrompts.at(0)?.content ?? "empty", ); } const memoryPrompt = get().getMemoryPrompt(); // long term memory const shouldSendLongTermMemory = modelConfig.sendMemory && session.memoryPrompt && session.memoryPrompt.length > 0 && session.lastSummarizeIndex > clearContextIndex; const longTermMemoryPrompts = shouldSendLongTermMemory && memoryPrompt ? [memoryPrompt] : []; const longTermMemoryStartIndex = session.lastSummarizeIndex; // short term memory const shortTermMemoryStartIndex = Math.max( 0, totalMessageCount - modelConfig.historyMessageCount, ); // lets concat send messages, including 4 parts: // 0. system prompt: to get close to OpenAI Web ChatGPT // 1. long term memory: summarized memory messages // 2. pre-defined in-context prompts // 3. short term memory: latest n messages // 4. newest input message const memoryStartIndex = shouldSendLongTermMemory ? Math.min(longTermMemoryStartIndex, shortTermMemoryStartIndex) : shortTermMemoryStartIndex; // and if user has cleared history messages, we should exclude the memory too. const contextStartIndex = Math.max(clearContextIndex, memoryStartIndex); const maxTokenThreshold = modelConfig.max_tokens; // get recent messages as much as possible const reversedRecentMessages = []; for ( let i = totalMessageCount - 1, tokenCount = 0; i >= contextStartIndex && tokenCount < maxTokenThreshold; i -= 1 ) { const msg = messages[i]; if (!msg || msg.isError) continue; tokenCount += estimateTokenLength(getMessageTextContent(msg)); reversedRecentMessages.push(msg); } // concat all messages const recentMessages = [ ...systemPrompts, ...longTermMemoryPrompts, ...contextPrompts, ...reversedRecentMessages.reverse(), ]; return recentMessages; }, updateMessage( sessionIndex: number, messageIndex: number, updater: (message?: ChatMessage) => void, ) { const sessions = get().sessions; const session = sessions.at(sessionIndex); const messages = session?.messages; updater(messages?.at(messageIndex)); set(() => ({ sessions })); }, resetSession(session: ChatSession) { get().updateTargetSession(session, (session) => { session.messages = []; session.memoryPrompt = ""; }); }, summarizeSession( refreshTitle: boolean = false, targetSession: ChatSession, ) { const config = useAppConfig.getState(); const session = targetSession; const modelConfig = session.mask.modelConfig; // skip summarize when using dalle3? if (isDalle3(modelConfig.model)) { return; } // if not config compressModel, then using getSummarizeModel const [model, providerName] = modelConfig.compressModel ? [modelConfig.compressModel, modelConfig.compressProviderName] : getSummarizeModel( session.mask.modelConfig.model, session.mask.modelConfig.providerName, ); const api: ClientApi = getClientApi(providerName as ServiceProvider); // remove error messages if any const messages = session.messages; // should summarize topic after chating more than 50 words const SUMMARIZE_MIN_LEN = 50; if ( (config.enableAutoGenerateTitle && session.topic === DEFAULT_TOPIC && countMessages(messages) >= SUMMARIZE_MIN_LEN) || refreshTitle ) { const startIndex = Math.max( 0, messages.length - modelConfig.historyMessageCount, ); const topicMessages = messages .slice( startIndex < messages.length ? startIndex : messages.length - 1, messages.length, ) .concat( createMessage({ role: "user", content: Locale.Store.Prompt.Topic, }), ); api.llm.chat({ messages: topicMessages, config: { model, stream: false, providerName, }, onFinish(message, responseRes) { if (responseRes?.status === 200) { get().updateTargetSession( session, (session) => (session.topic = message.length > 0 ? trimTopic(message) : DEFAULT_TOPIC), ); } }, }); } const summarizeIndex = Math.max( session.lastSummarizeIndex, session.clearContextIndex ?? 0, ); let toBeSummarizedMsgs = messages .filter((msg) => !msg.isError) .slice(summarizeIndex); const historyMsgLength = countMessages(toBeSummarizedMsgs); if (historyMsgLength > (modelConfig?.max_tokens || 4000)) { const n = toBeSummarizedMsgs.length; toBeSummarizedMsgs = toBeSummarizedMsgs.slice( Math.max(0, n - modelConfig.historyMessageCount), ); } const memoryPrompt = get().getMemoryPrompt(); if (memoryPrompt) { // add memory prompt toBeSummarizedMsgs.unshift(memoryPrompt); } const lastSummarizeIndex = session.messages.length; console.log( "[Chat History] ", toBeSummarizedMsgs, historyMsgLength, modelConfig.compressMessageLengthThreshold, ); if ( historyMsgLength > modelConfig.compressMessageLengthThreshold && modelConfig.sendMemory ) { /** Destruct max_tokens while summarizing * this param is just shit **/ const { max_tokens, ...modelcfg } = modelConfig; api.llm.chat({ messages: toBeSummarizedMsgs.concat( createMessage({ role: "system", content: Locale.Store.Prompt.Summarize, date: "", }), ), config: { ...modelcfg, stream: true, model, providerName, }, onUpdate(message) { session.memoryPrompt = message; }, onFinish(message, responseRes) { if (responseRes?.status === 200) { console.log("[Memory] ", message); get().updateTargetSession(session, (session) => { session.lastSummarizeIndex = lastSummarizeIndex; session.memoryPrompt = message; // Update the memory prompt for stored it in local storage }); } }, onError(err) { console.error("[Summarize] ", err); }, }); } }, updateStat(message: ChatMessage, session: ChatSession) { get().updateTargetSession(session, (session) => { session.stat.charCount += message.content.length; // TODO: should update chat count and word count }); }, updateTargetSession( targetSession: ChatSession, updater: (session: ChatSession) => void, ) { const sessions = get().sessions; const index = sessions.findIndex((s) => s.id === targetSession.id); if (index < 0) return; updater(sessions[index]); set(() => ({ sessions })); }, async clearAllData() { await indexedDBStorage.clear(); localStorage.clear(); location.reload(); }, setLastInput(lastInput: string) { set({ lastInput, }); }, /** check if the message contains MCP JSON and execute the MCP action */ checkMcpJson(message: ChatMessage) { const mcpEnabled = isMcpEnabled(); if (!mcpEnabled) return; const content = getMessageTextContent(message); if (isMcpJson(content)) { try { const mcpRequest = extractMcpJson(content); if (mcpRequest) { console.debug("[MCP Request]", mcpRequest); executeMcpAction(mcpRequest.clientId, mcpRequest.mcp) .then((result) => { console.log("[MCP Response]", result); const mcpResponse = typeof result === "object" ? JSON.stringify(result) : String(result); get().onUserInput( `\`\`\`json:mcp-response:${mcpRequest.clientId}\n${mcpResponse}\n\`\`\``, [], true, ); }) .catch((error) => showToast("MCP execution failed", error)); } } catch (error) { console.error("[Check MCP JSON]", error); } } }, }; return methods; }, { name: StoreKey.Chat, version: 3.3, migrate(persistedState, version) { const state = persistedState as any; const newState = JSON.parse( JSON.stringify(state), ) as typeof DEFAULT_CHAT_STATE; if (version < 2) { newState.sessions = []; const oldSessions = state.sessions; for (const oldSession of oldSessions) { const newSession = createEmptySession(); newSession.topic = oldSession.topic; newSession.messages = [...oldSession.messages]; newSession.mask.modelConfig.sendMemory = true; newSession.mask.modelConfig.historyMessageCount = 4; newSession.mask.modelConfig.compressMessageLengthThreshold = 1000; newState.sessions.push(newSession); } } if (version < 3) { // migrate id to nanoid newState.sessions.forEach((s) => { s.id = nanoid(); s.messages.forEach((m) => (m.id = nanoid())); }); } // Enable `enableInjectSystemPrompts` attribute for old sessions. // Resolve issue of old sessions not automatically enabling. if (version < 3.1) { newState.sessions.forEach((s) => { if ( // Exclude those already set by user !s.mask.modelConfig.hasOwnProperty("enableInjectSystemPrompts") ) { // Because users may have changed this configuration, // the user's current configuration is used instead of the default const config = useAppConfig.getState(); s.mask.modelConfig.enableInjectSystemPrompts = config.modelConfig.enableInjectSystemPrompts; } }); } // add default summarize model for every session if (version < 3.2) { newState.sessions.forEach((s) => { const config = useAppConfig.getState(); s.mask.modelConfig.compressModel = config.modelConfig.compressModel; s.mask.modelConfig.compressProviderName = config.modelConfig.compressProviderName; }); } // revert default summarize model for every session if (version < 3.3) { newState.sessions.forEach((s) => { const config = useAppConfig.getState(); s.mask.modelConfig.compressModel = ""; s.mask.modelConfig.compressProviderName = ""; }); } return newState as any; }, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/mask.ts
app/store/mask.ts
import { BUILTIN_MASKS } from "../masks"; import { getLang, Lang } from "../locales"; import { DEFAULT_TOPIC, ChatMessage } from "./chat"; import { ModelConfig, useAppConfig } from "./config"; import { StoreKey } from "../constant"; import { nanoid } from "nanoid"; import { createPersistStore } from "../utils/store"; export type Mask = { id: string; createdAt: number; avatar: string; name: string; hideContext?: boolean; context: ChatMessage[]; syncGlobalConfig?: boolean; modelConfig: ModelConfig; lang: Lang; builtin: boolean; plugin?: string[]; enableArtifacts?: boolean; enableCodeFold?: boolean; }; export const DEFAULT_MASK_STATE = { masks: {} as Record<string, Mask>, language: undefined as Lang | undefined, }; export type MaskState = typeof DEFAULT_MASK_STATE & { language?: Lang | undefined; }; export const DEFAULT_MASK_AVATAR = "gpt-bot"; export const createEmptyMask = () => ({ id: nanoid(), avatar: DEFAULT_MASK_AVATAR, name: DEFAULT_TOPIC, context: [], syncGlobalConfig: true, // use global config as default modelConfig: { ...useAppConfig.getState().modelConfig }, lang: getLang(), builtin: false, createdAt: Date.now(), plugin: [], }) as Mask; export const useMaskStore = createPersistStore( { ...DEFAULT_MASK_STATE }, (set, get) => ({ create(mask?: Partial<Mask>) { const masks = get().masks; const id = nanoid(); masks[id] = { ...createEmptyMask(), ...mask, id, builtin: false, }; set(() => ({ masks })); get().markUpdate(); return masks[id]; }, updateMask(id: string, updater: (mask: Mask) => void) { const masks = get().masks; const mask = masks[id]; if (!mask) return; const updateMask = { ...mask }; updater(updateMask); masks[id] = updateMask; set(() => ({ masks })); get().markUpdate(); }, delete(id: string) { const masks = get().masks; delete masks[id]; set(() => ({ masks })); get().markUpdate(); }, get(id?: string) { return get().masks[id ?? 1145141919810]; }, getAll() { const userMasks = Object.values(get().masks).sort( (a, b) => b.createdAt - a.createdAt, ); const config = useAppConfig.getState(); if (config.hideBuiltinMasks) return userMasks; const buildinMasks = BUILTIN_MASKS.map( (m) => ({ ...m, modelConfig: { ...config.modelConfig, ...m.modelConfig, }, }) as Mask, ); return userMasks.concat(buildinMasks); }, search(text: string) { return Object.values(get().masks); }, setLanguage(language: Lang | undefined) { set({ language, }); }, }), { name: StoreKey.Mask, version: 3.1, migrate(state, version) { const newState = JSON.parse(JSON.stringify(state)) as MaskState; // migrate mask id to nanoid if (version < 3) { Object.values(newState.masks).forEach((m) => (m.id = nanoid())); } if (version < 3.1) { const updatedMasks: Record<string, Mask> = {}; Object.values(newState.masks).forEach((m) => { updatedMasks[m.id] = m; }); newState.masks = updatedMasks; } return newState as any; }, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/sync.ts
app/store/sync.ts
import { getClientConfig } from "../config/client"; import { ApiPath, STORAGE_KEY, StoreKey } from "../constant"; import { createPersistStore } from "../utils/store"; import { AppState, getLocalAppState, GetStoreState, mergeAppState, setLocalAppState, } from "../utils/sync"; import { downloadAs, readFromFile } from "../utils"; import { showToast } from "../components/ui-lib"; import Locale from "../locales"; import { createSyncClient, ProviderType } from "../utils/cloud"; export interface WebDavConfig { server: string; username: string; password: string; } const isApp = !!getClientConfig()?.isApp; export type SyncStore = GetStoreState<typeof useSyncStore>; const DEFAULT_SYNC_STATE = { provider: ProviderType.WebDAV, useProxy: true, proxyUrl: ApiPath.Cors as string, webdav: { endpoint: "", username: "", password: "", }, upstash: { endpoint: "", username: STORAGE_KEY, apiKey: "", }, lastSyncTime: 0, lastProvider: "", }; export const useSyncStore = createPersistStore( DEFAULT_SYNC_STATE, (set, get) => ({ cloudSync() { const config = get()[get().provider]; return Object.values(config).every((c) => c.toString().length > 0); }, markSyncTime() { set({ lastSyncTime: Date.now(), lastProvider: get().provider }); }, export() { const state = getLocalAppState(); const datePart = isApp ? `${new Date().toLocaleDateString().replace(/\//g, "_")} ${new Date() .toLocaleTimeString() .replace(/:/g, "_")}` : new Date().toLocaleString(); const fileName = `Backup-${datePart}.json`; downloadAs(JSON.stringify(state), fileName); }, async import() { const rawContent = await readFromFile(); try { const remoteState = JSON.parse(rawContent) as AppState; const localState = getLocalAppState(); mergeAppState(localState, remoteState); setLocalAppState(localState); location.reload(); } catch (e) { console.error("[Import]", e); showToast(Locale.Settings.Sync.ImportFailed); } }, getClient() { const provider = get().provider; const client = createSyncClient(provider, get()); return client; }, async sync() { const localState = getLocalAppState(); const provider = get().provider; const config = get()[provider]; const client = this.getClient(); try { const remoteState = await client.get(config.username); if (!remoteState || remoteState === "") { await client.set(config.username, JSON.stringify(localState)); console.log( "[Sync] Remote state is empty, using local state instead.", ); return; } else { const parsedRemoteState = JSON.parse( await client.get(config.username), ) as AppState; mergeAppState(localState, parsedRemoteState); setLocalAppState(localState); } } catch (e) { console.log("[Sync] failed to get remote state", e); throw e; } await client.set(config.username, JSON.stringify(localState)); this.markSyncTime(); }, async check() { const client = this.getClient(); return await client.check(); }, }), { name: StoreKey.Sync, version: 1.2, migrate(persistedState, version) { const newState = persistedState as typeof DEFAULT_SYNC_STATE; if (version < 1.1) { newState.upstash.username = STORAGE_KEY; } if (version < 1.2) { if ( (persistedState as typeof DEFAULT_SYNC_STATE).proxyUrl === "/api/cors/" ) { newState.proxyUrl = ""; } } return newState as any; }, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/sd.ts
app/store/sd.ts
import { Stability, StoreKey, ACCESS_CODE_PREFIX, ApiPath, } from "@/app/constant"; import { getBearerToken } from "@/app/client/api"; import { createPersistStore } from "@/app/utils/store"; import { nanoid } from "nanoid"; import { uploadImage, base64Image2Blob } from "@/app/utils/chat"; import { models, getModelParamBasicData } from "@/app/components/sd/sd-panel"; import { useAccessStore } from "./access"; const defaultModel = { name: models[0].name, value: models[0].value, }; const defaultParams = getModelParamBasicData(models[0].params({}), {}); const DEFAULT_SD_STATE = { currentId: 0, draw: [], currentModel: defaultModel, currentParams: defaultParams, }; export const useSdStore = createPersistStore< { currentId: number; draw: any[]; currentModel: typeof defaultModel; currentParams: any; }, { getNextId: () => number; sendTask: (data: any, okCall?: Function) => void; updateDraw: (draw: any) => void; setCurrentModel: (model: any) => void; setCurrentParams: (data: any) => void; } >( DEFAULT_SD_STATE, (set, _get) => { function get() { return { ..._get(), ...methods, }; } const methods = { getNextId() { const id = ++_get().currentId; set({ currentId: id }); return id; }, sendTask(data: any, okCall?: Function) { data = { ...data, id: nanoid(), status: "running" }; set({ draw: [data, ..._get().draw] }); this.getNextId(); this.stabilityRequestCall(data); okCall?.(); }, stabilityRequestCall(data: any) { const accessStore = useAccessStore.getState(); let prefix: string = ApiPath.Stability as string; let bearerToken = ""; if (accessStore.useCustomConfig) { prefix = accessStore.stabilityUrl || (ApiPath.Stability as string); bearerToken = getBearerToken(accessStore.stabilityApiKey); } if (!bearerToken && accessStore.enabledAccessControl()) { bearerToken = getBearerToken( ACCESS_CODE_PREFIX + accessStore.accessCode, ); } const headers = { Accept: "application/json", Authorization: bearerToken, }; const path = `${prefix}/${Stability.GeneratePath}/${data.model}`; const formData = new FormData(); for (let paramsKey in data.params) { formData.append(paramsKey, data.params[paramsKey]); } fetch(path, { method: "POST", headers, body: formData, }) .then((response) => response.json()) .then((resData) => { if (resData.errors && resData.errors.length > 0) { this.updateDraw({ ...data, status: "error", error: resData.errors[0], }); this.getNextId(); return; } const self = this; if (resData.finish_reason === "SUCCESS") { uploadImage(base64Image2Blob(resData.image, "image/png")) .then((img_data) => { console.debug("uploadImage success", img_data, self); self.updateDraw({ ...data, status: "success", img_data, }); }) .catch((e) => { console.error("uploadImage error", e); self.updateDraw({ ...data, status: "error", error: JSON.stringify(e), }); }); } else { self.updateDraw({ ...data, status: "error", error: JSON.stringify(resData), }); } this.getNextId(); }) .catch((error) => { this.updateDraw({ ...data, status: "error", error: error.message }); console.error("Error:", error); this.getNextId(); }); }, updateDraw(_draw: any) { const draw = _get().draw || []; draw.some((item, index) => { if (item.id === _draw.id) { draw[index] = _draw; set(() => ({ draw })); return true; } }); }, setCurrentModel(model: any) { set({ currentModel: model }); }, setCurrentParams(data: any) { set({ currentParams: data, }); }, }; return methods; }, { name: StoreKey.SdList, version: 1.0, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/update.ts
app/store/update.ts
import { FETCH_COMMIT_URL, FETCH_TAG_URL, ModelProvider, StoreKey, } from "../constant"; import { getClientConfig } from "../config/client"; import { createPersistStore } from "../utils/store"; import { clientUpdate } from "../utils"; import ChatGptIcon from "../icons/chatgpt.png"; import Locale from "../locales"; import { ClientApi } from "../client/api"; const ONE_MINUTE = 60 * 1000; const isApp = !!getClientConfig()?.isApp; function formatVersionDate(t: string) { const d = new Date(+t); const year = d.getUTCFullYear(); const month = d.getUTCMonth() + 1; const day = d.getUTCDate(); return [ year.toString(), month.toString().padStart(2, "0"), day.toString().padStart(2, "0"), ].join(""); } type VersionType = "date" | "tag"; async function getVersion(type: VersionType) { if (type === "date") { const data = (await (await fetch(FETCH_COMMIT_URL)).json()) as { commit: { author: { name: string; date: string }; }; sha: string; }[]; const remoteCommitTime = data[0].commit.author.date; const remoteId = new Date(remoteCommitTime).getTime().toString(); return remoteId; } else if (type === "tag") { const data = (await (await fetch(FETCH_TAG_URL)).json()) as { commit: { sha: string; url: string }; name: string; }[]; return data.at(0)?.name; } } export const useUpdateStore = createPersistStore( { versionType: "tag" as VersionType, lastUpdate: 0, version: "unknown", remoteVersion: "", used: 0, subscription: 0, lastUpdateUsage: 0, }, (set, get) => ({ formatVersion(version: string) { if (get().versionType === "date") { version = formatVersionDate(version); } return version; }, async getLatestVersion(force = false) { const versionType = get().versionType; let version = versionType === "date" ? getClientConfig()?.commitDate : getClientConfig()?.version; set(() => ({ version })); const shouldCheck = Date.now() - get().lastUpdate > 2 * 60 * ONE_MINUTE; if (!force && !shouldCheck) return; set(() => ({ lastUpdate: Date.now(), })); try { const remoteId = await getVersion(versionType); set(() => ({ remoteVersion: remoteId, })); if (window.__TAURI__?.notification && isApp) { // Check if notification permission is granted await window.__TAURI__?.notification .isPermissionGranted() .then((granted) => { if (!granted) { return; } else { // Request permission to show notifications window.__TAURI__?.notification .requestPermission() .then((permission) => { if (permission === "granted") { if (version === remoteId) { // Show a notification using Tauri window.__TAURI__?.notification.sendNotification({ title: "NextChat", body: `${Locale.Settings.Update.IsLatest}`, icon: `${ChatGptIcon.src}`, sound: "Default", }); } else { const updateMessage = Locale.Settings.Update.FoundUpdate(`${remoteId}`); // Show a notification for the new version using Tauri window.__TAURI__?.notification.sendNotification({ title: "NextChat", body: updateMessage, icon: `${ChatGptIcon.src}`, sound: "Default", }); clientUpdate(); } } }); } }); } console.log("[Got Upstream] ", remoteId); } catch (error) { console.error("[Fetch Upstream Commit Id]", error); } }, async updateUsage(force = false) { // only support openai for now const overOneMinute = Date.now() - get().lastUpdateUsage >= ONE_MINUTE; if (!overOneMinute && !force) return; set(() => ({ lastUpdateUsage: Date.now(), })); try { const api = new ClientApi(ModelProvider.GPT); const usage = await api.llm.usage(); if (usage) { set(() => ({ used: usage.used, subscription: usage.total, })); } } catch (e) { console.error((e as Error).message); } }, }), { name: StoreKey.Update, version: 1, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/plugin.ts
app/store/plugin.ts
import OpenAPIClientAxios from "openapi-client-axios"; import { StoreKey } from "../constant"; import { nanoid } from "nanoid"; import { createPersistStore } from "../utils/store"; import { getClientConfig } from "../config/client"; import yaml from "js-yaml"; import { adapter, getOperationId } from "../utils"; import { useAccessStore } from "./access"; const isApp = getClientConfig()?.isApp !== false; export type Plugin = { id: string; createdAt: number; title: string; version: string; content: string; builtin: boolean; authType?: string; authLocation?: string; authHeader?: string; authToken?: string; }; export type FunctionToolItem = { type: string; function: { name: string; description?: string; parameters: Object; }; }; type FunctionToolServiceItem = { api: OpenAPIClientAxios; length: number; tools: FunctionToolItem[]; funcs: Record<string, Function>; }; export const FunctionToolService = { tools: {} as Record<string, FunctionToolServiceItem>, add(plugin: Plugin, replace = false) { if (!replace && this.tools[plugin.id]) return this.tools[plugin.id]; const headerName = ( plugin?.authType == "custom" ? plugin?.authHeader : "Authorization" ) as string; const tokenValue = plugin?.authType == "basic" ? `Basic ${plugin?.authToken}` : plugin?.authType == "bearer" ? `Bearer ${plugin?.authToken}` : plugin?.authToken; const authLocation = plugin?.authLocation || "header"; const definition = yaml.load(plugin.content) as any; const serverURL = definition?.servers?.[0]?.url; const baseURL = !isApp ? "/api/proxy" : serverURL; const headers: Record<string, string | undefined> = { "X-Base-URL": !isApp ? serverURL : undefined, }; if (authLocation == "header") { headers[headerName] = tokenValue; } // try using openaiApiKey for Dalle3 Plugin. if (!tokenValue && plugin.id === "dalle3") { const openaiApiKey = useAccessStore.getState().openaiApiKey; if (openaiApiKey) { headers[headerName] = `Bearer ${openaiApiKey}`; } } const api = new OpenAPIClientAxios({ definition: yaml.load(plugin.content) as any, axiosConfigDefaults: { adapter: (window.__TAURI__ ? adapter : ["xhr"]) as any, baseURL, headers, }, }); try { api.initSync(); } catch (e) {} const operations = api.getOperations(); return (this.tools[plugin.id] = { api, length: operations.length, tools: operations.map((o) => { // @ts-ignore const parameters = o?.requestBody?.content["application/json"] ?.schema || { type: "object", properties: {}, }; if (!parameters["required"]) { parameters["required"] = []; } if (o.parameters instanceof Array) { o.parameters.forEach((p) => { // @ts-ignore if (p?.in == "query" || p?.in == "path") { // const name = `${p.in}__${p.name}` // @ts-ignore const name = p?.name; parameters["properties"][name] = { // @ts-ignore type: p.schema.type, // @ts-ignore description: p.description, }; // @ts-ignore if (p.required) { parameters["required"].push(name); } } }); } return { type: "function", function: { name: getOperationId(o), description: o.description || o.summary, parameters: parameters, }, } as FunctionToolItem; }), funcs: operations.reduce((s, o) => { // @ts-ignore s[getOperationId(o)] = function (args) { const parameters: Record<string, any> = {}; if (o.parameters instanceof Array) { o.parameters.forEach((p) => { // @ts-ignore parameters[p?.name] = args[p?.name]; // @ts-ignore delete args[p?.name]; }); } if (authLocation == "query") { parameters[headerName] = tokenValue; } else if (authLocation == "body") { args[headerName] = tokenValue; } // @ts-ignore if o.operationId is null, then using o.path and o.method return api.client.paths[o.path][o.method]( parameters, args, api.axiosConfigDefaults, ); }; return s; }, {}), }); }, get(id: string) { return this.tools[id]; }, }; export const createEmptyPlugin = () => ({ id: nanoid(), title: "", version: "1.0.0", content: "", builtin: false, createdAt: Date.now(), }) as Plugin; export const DEFAULT_PLUGIN_STATE = { plugins: {} as Record<string, Plugin>, }; export const usePluginStore = createPersistStore( { ...DEFAULT_PLUGIN_STATE }, (set, get) => ({ create(plugin?: Partial<Plugin>) { const plugins = get().plugins; const id = plugin?.id || nanoid(); plugins[id] = { ...createEmptyPlugin(), ...plugin, id, builtin: false, }; set(() => ({ plugins })); get().markUpdate(); return plugins[id]; }, updatePlugin(id: string, updater: (plugin: Plugin) => void) { const plugins = get().plugins; const plugin = plugins[id]; if (!plugin) return; const updatePlugin = { ...plugin }; updater(updatePlugin); plugins[id] = updatePlugin; FunctionToolService.add(updatePlugin, true); set(() => ({ plugins })); get().markUpdate(); }, delete(id: string) { const plugins = get().plugins; delete plugins[id]; set(() => ({ plugins })); get().markUpdate(); }, getAsTools(ids: string[]) { const plugins = get().plugins; const selected = (ids || []) .map((id) => plugins[id]) .filter((i) => i) .map((p) => FunctionToolService.add(p)); return [ // @ts-ignore selected.reduce((s, i) => s.concat(i.tools), []), selected.reduce((s, i) => Object.assign(s, i.funcs), {}), ]; }, get(id?: string) { return get().plugins[id ?? 1145141919810]; }, getAll() { return Object.values(get().plugins).sort( (a, b) => b.createdAt - a.createdAt, ); }, }), { name: StoreKey.Plugin, version: 1, onRehydrateStorage(state) { // Skip store rehydration on server side if (typeof window === "undefined") { return; } fetch("./plugins.json") .then((res) => res.json()) .then((res) => { Promise.all( res.map((item: any) => // skip get schema state.get(item.id) ? item : fetch(item.schema) .then((res) => res.text()) .then((content) => ({ ...item, content, })) .catch((e) => item), ), ).then((builtinPlugins: any) => { builtinPlugins .filter((item: any) => item?.content) .forEach((item: any) => { const plugin = state.create(item); state.updatePlugin(plugin.id, (plugin) => { const tool = FunctionToolService.add(plugin, true); plugin.title = tool.api.definition.info.title; plugin.version = tool.api.definition.info.version; plugin.builtin = true; }); }); }); }); }, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/index.ts
app/store/index.ts
export * from "./chat"; export * from "./update"; export * from "./access"; export * from "./config"; export * from "./plugin";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/prompt.ts
app/store/prompt.ts
import Fuse from "fuse.js"; import { nanoid } from "nanoid"; import { StoreKey } from "../constant"; import { getLang } from "../locales"; import { createPersistStore } from "../utils/store"; export interface Prompt { id: string; isUser?: boolean; title: string; content: string; createdAt: number; } export const SearchService = { ready: false, builtinEngine: new Fuse<Prompt>([], { keys: ["title"] }), userEngine: new Fuse<Prompt>([], { keys: ["title"] }), count: { builtin: 0, }, allPrompts: [] as Prompt[], builtinPrompts: [] as Prompt[], init(builtinPrompts: Prompt[], userPrompts: Prompt[]) { if (this.ready) { return; } this.allPrompts = userPrompts.concat(builtinPrompts); this.builtinPrompts = builtinPrompts.slice(); this.builtinEngine.setCollection(builtinPrompts); this.userEngine.setCollection(userPrompts); this.ready = true; }, remove(id: string) { this.userEngine.remove((doc) => doc.id === id); }, add(prompt: Prompt) { this.userEngine.add(prompt); }, search(text: string) { const userResults = this.userEngine.search(text); const builtinResults = this.builtinEngine.search(text); return userResults.concat(builtinResults).map((v) => v.item); }, }; export const usePromptStore = createPersistStore( { counter: 0, prompts: {} as Record<string, Prompt>, }, (set, get) => ({ add(prompt: Prompt) { const prompts = get().prompts; prompt.id = nanoid(); prompt.isUser = true; prompt.createdAt = Date.now(); prompts[prompt.id] = prompt; set(() => ({ prompts: prompts, })); return prompt.id!; }, get(id: string) { const targetPrompt = get().prompts[id]; if (!targetPrompt) { return SearchService.builtinPrompts.find((v) => v.id === id); } return targetPrompt; }, remove(id: string) { const prompts = get().prompts; delete prompts[id]; Object.entries(prompts).some(([key, prompt]) => { if (prompt.id === id) { delete prompts[key]; return true; } return false; }); SearchService.remove(id); set(() => ({ prompts, counter: get().counter + 1, })); }, getUserPrompts() { const userPrompts = Object.values(get().prompts ?? {}); userPrompts.sort((a, b) => b.id && a.id ? b.createdAt - a.createdAt : 0, ); return userPrompts; }, updatePrompt(id: string, updater: (prompt: Prompt) => void) { const prompt = get().prompts[id] ?? { title: "", content: "", id, }; SearchService.remove(id); updater(prompt); const prompts = get().prompts; prompts[id] = prompt; set(() => ({ prompts })); SearchService.add(prompt); }, search(text: string) { if (text.length === 0) { // return all rompts return this.getUserPrompts().concat(SearchService.builtinPrompts); } return SearchService.search(text) as Prompt[]; }, }), { name: StoreKey.Prompt, version: 3, migrate(state, version) { const newState = JSON.parse(JSON.stringify(state)) as { prompts: Record<string, Prompt>; }; if (version < 3) { Object.values(newState.prompts).forEach((p) => (p.id = nanoid())); } return newState as any; }, onRehydrateStorage(state) { // Skip store rehydration on server side if (typeof window === "undefined") { return; } const PROMPT_URL = "./prompts.json"; type PromptList = Array<[string, string]>; fetch(PROMPT_URL) .then((res) => res.json()) .then((res) => { let fetchPrompts = [res.en, res.tw, res.cn]; if (getLang() === "cn") { fetchPrompts = fetchPrompts.reverse(); } const builtinPrompts = fetchPrompts.map((promptList: PromptList) => { return promptList.map( ([title, content]) => ({ id: nanoid(), title, content, createdAt: Date.now(), }) as Prompt, ); }); const userPrompts = usePromptStore.getState().getUserPrompts() ?? []; const allPromptsForSearch = builtinPrompts .reduce((pre, cur) => pre.concat(cur), []) .filter((v) => !!v.title && !!v.content); SearchService.count.builtin = res.en.length + res.cn.length + res.tw.length; SearchService.init(allPromptsForSearch, userPrompts); }); }, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/store/access.ts
app/store/access.ts
import { GoogleSafetySettingsThreshold, ServiceProvider, StoreKey, ApiPath, OPENAI_BASE_URL, ANTHROPIC_BASE_URL, GEMINI_BASE_URL, BAIDU_BASE_URL, BYTEDANCE_BASE_URL, ALIBABA_BASE_URL, TENCENT_BASE_URL, MOONSHOT_BASE_URL, STABILITY_BASE_URL, IFLYTEK_BASE_URL, DEEPSEEK_BASE_URL, XAI_BASE_URL, CHATGLM_BASE_URL, SILICONFLOW_BASE_URL, AI302_BASE_URL, } from "../constant"; import { getHeaders } from "../client/api"; import { getClientConfig } from "../config/client"; import { createPersistStore } from "../utils/store"; import { ensure } from "../utils/clone"; import { DEFAULT_CONFIG } from "./config"; import { getModelProvider } from "../utils/model"; let fetchState = 0; // 0 not fetch, 1 fetching, 2 done const isApp = getClientConfig()?.buildMode === "export"; const DEFAULT_OPENAI_URL = isApp ? OPENAI_BASE_URL : ApiPath.OpenAI; const DEFAULT_GOOGLE_URL = isApp ? GEMINI_BASE_URL : ApiPath.Google; const DEFAULT_ANTHROPIC_URL = isApp ? ANTHROPIC_BASE_URL : ApiPath.Anthropic; const DEFAULT_BAIDU_URL = isApp ? BAIDU_BASE_URL : ApiPath.Baidu; const DEFAULT_BYTEDANCE_URL = isApp ? BYTEDANCE_BASE_URL : ApiPath.ByteDance; const DEFAULT_ALIBABA_URL = isApp ? ALIBABA_BASE_URL : ApiPath.Alibaba; const DEFAULT_TENCENT_URL = isApp ? TENCENT_BASE_URL : ApiPath.Tencent; const DEFAULT_MOONSHOT_URL = isApp ? MOONSHOT_BASE_URL : ApiPath.Moonshot; const DEFAULT_STABILITY_URL = isApp ? STABILITY_BASE_URL : ApiPath.Stability; const DEFAULT_IFLYTEK_URL = isApp ? IFLYTEK_BASE_URL : ApiPath.Iflytek; const DEFAULT_DEEPSEEK_URL = isApp ? DEEPSEEK_BASE_URL : ApiPath.DeepSeek; const DEFAULT_XAI_URL = isApp ? XAI_BASE_URL : ApiPath.XAI; const DEFAULT_CHATGLM_URL = isApp ? CHATGLM_BASE_URL : ApiPath.ChatGLM; const DEFAULT_SILICONFLOW_URL = isApp ? SILICONFLOW_BASE_URL : ApiPath.SiliconFlow; const DEFAULT_AI302_URL = isApp ? AI302_BASE_URL : ApiPath["302.AI"]; const DEFAULT_ACCESS_STATE = { accessCode: "", useCustomConfig: false, provider: ServiceProvider.OpenAI, // openai openaiUrl: DEFAULT_OPENAI_URL, openaiApiKey: "", // azure azureUrl: "", azureApiKey: "", azureApiVersion: "2023-08-01-preview", // google ai studio googleUrl: DEFAULT_GOOGLE_URL, googleApiKey: "", googleApiVersion: "v1", googleSafetySettings: GoogleSafetySettingsThreshold.BLOCK_ONLY_HIGH, // anthropic anthropicUrl: DEFAULT_ANTHROPIC_URL, anthropicApiKey: "", anthropicApiVersion: "2023-06-01", // baidu baiduUrl: DEFAULT_BAIDU_URL, baiduApiKey: "", baiduSecretKey: "", // bytedance bytedanceUrl: DEFAULT_BYTEDANCE_URL, bytedanceApiKey: "", // alibaba alibabaUrl: DEFAULT_ALIBABA_URL, alibabaApiKey: "", // moonshot moonshotUrl: DEFAULT_MOONSHOT_URL, moonshotApiKey: "", //stability stabilityUrl: DEFAULT_STABILITY_URL, stabilityApiKey: "", // tencent tencentUrl: DEFAULT_TENCENT_URL, tencentSecretKey: "", tencentSecretId: "", // iflytek iflytekUrl: DEFAULT_IFLYTEK_URL, iflytekApiKey: "", iflytekApiSecret: "", // deepseek deepseekUrl: DEFAULT_DEEPSEEK_URL, deepseekApiKey: "", // xai xaiUrl: DEFAULT_XAI_URL, xaiApiKey: "", // chatglm chatglmUrl: DEFAULT_CHATGLM_URL, chatglmApiKey: "", // siliconflow siliconflowUrl: DEFAULT_SILICONFLOW_URL, siliconflowApiKey: "", // 302.AI ai302Url: DEFAULT_AI302_URL, ai302ApiKey: "", // server config needCode: true, hideUserApiKey: false, hideBalanceQuery: false, disableGPT4: false, disableFastLink: false, customModels: "", defaultModel: "", visionModels: "", // tts config edgeTTSVoiceName: "zh-CN-YunxiNeural", }; export const useAccessStore = createPersistStore( { ...DEFAULT_ACCESS_STATE }, (set, get) => ({ enabledAccessControl() { this.fetch(); return get().needCode; }, getVisionModels() { this.fetch(); return get().visionModels; }, edgeVoiceName() { this.fetch(); return get().edgeTTSVoiceName; }, isValidOpenAI() { return ensure(get(), ["openaiApiKey"]); }, isValidAzure() { return ensure(get(), ["azureUrl", "azureApiKey", "azureApiVersion"]); }, isValidGoogle() { return ensure(get(), ["googleApiKey"]); }, isValidAnthropic() { return ensure(get(), ["anthropicApiKey"]); }, isValidBaidu() { return ensure(get(), ["baiduApiKey", "baiduSecretKey"]); }, isValidByteDance() { return ensure(get(), ["bytedanceApiKey"]); }, isValidAlibaba() { return ensure(get(), ["alibabaApiKey"]); }, isValidTencent() { return ensure(get(), ["tencentSecretKey", "tencentSecretId"]); }, isValidMoonshot() { return ensure(get(), ["moonshotApiKey"]); }, isValidIflytek() { return ensure(get(), ["iflytekApiKey"]); }, isValidDeepSeek() { return ensure(get(), ["deepseekApiKey"]); }, isValidXAI() { return ensure(get(), ["xaiApiKey"]); }, isValidChatGLM() { return ensure(get(), ["chatglmApiKey"]); }, isValidSiliconFlow() { return ensure(get(), ["siliconflowApiKey"]); }, isAuthorized() { this.fetch(); // has token or has code or disabled access control return ( this.isValidOpenAI() || this.isValidAzure() || this.isValidGoogle() || this.isValidAnthropic() || this.isValidBaidu() || this.isValidByteDance() || this.isValidAlibaba() || this.isValidTencent() || this.isValidMoonshot() || this.isValidIflytek() || this.isValidDeepSeek() || this.isValidXAI() || this.isValidChatGLM() || this.isValidSiliconFlow() || !this.enabledAccessControl() || (this.enabledAccessControl() && ensure(get(), ["accessCode"])) ); }, fetch() { if (fetchState > 0 || getClientConfig()?.buildMode === "export") return; fetchState = 1; fetch("/api/config", { method: "post", body: null, headers: { ...getHeaders(), }, }) .then((res) => res.json()) .then((res) => { const defaultModel = res.defaultModel ?? ""; if (defaultModel !== "") { const [model, providerName] = getModelProvider(defaultModel); DEFAULT_CONFIG.modelConfig.model = model; DEFAULT_CONFIG.modelConfig.providerName = providerName as any; } return res; }) .then((res: DangerConfig) => { console.log("[Config] got config from server", res); set(() => ({ ...res })); }) .catch(() => { console.error("[Config] failed to fetch config"); }) .finally(() => { fetchState = 2; }); }, }), { name: StoreKey.Access, version: 2, migrate(persistedState, version) { if (version < 2) { const state = persistedState as { token: string; openaiApiKey: string; azureApiVersion: string; googleApiKey: string; }; state.openaiApiKey = state.token; state.azureApiVersion = "2023-08-01-preview"; } return persistedState as any; }, }, );
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/exporter.tsx
app/components/exporter.tsx
/* eslint-disable @next/next/no-img-element */ import { ChatMessage, useAppConfig, useChatStore } from "../store"; import Locale from "../locales"; import styles from "./exporter.module.scss"; import { List, ListItem, Modal, Select, showImageModal, showModal, showToast, } from "./ui-lib"; import { IconButton } from "./button"; import { copyToClipboard, downloadAs, getMessageImages, useMobileScreen, } from "../utils"; import CopyIcon from "../icons/copy.svg"; import LoadingIcon from "../icons/three-dots.svg"; import ChatGptIcon from "../icons/chatgpt.png"; import ShareIcon from "../icons/share.svg"; import DownloadIcon from "../icons/download.svg"; import { useEffect, useMemo, useRef, useState } from "react"; import { MessageSelector, useMessageSelector } from "./message-selector"; import { Avatar } from "./emoji"; import dynamic from "next/dynamic"; import NextImage from "next/image"; import { toBlob, toPng } from "html-to-image"; import { prettyObject } from "../utils/format"; import { EXPORT_MESSAGE_CLASS_NAME } from "../constant"; import { getClientConfig } from "../config/client"; import { type ClientApi, getClientApi } from "../client/api"; import { getMessageTextContent } from "../utils"; import { MaskAvatar } from "./mask"; import clsx from "clsx"; const Markdown = dynamic(async () => (await import("./markdown")).Markdown, { loading: () => <LoadingIcon />, }); export function ExportMessageModal(props: { onClose: () => void }) { return ( <div className="modal-mask"> <Modal title={Locale.Export.Title} onClose={props.onClose} footer={ <div style={{ width: "100%", textAlign: "center", fontSize: 14, opacity: 0.5, }} > {Locale.Exporter.Description.Title} </div> } > <div style={{ minHeight: "40vh" }}> <MessageExporter /> </div> </Modal> </div> ); } function useSteps( steps: Array<{ name: string; value: string; }>, ) { const stepCount = steps.length; const [currentStepIndex, setCurrentStepIndex] = useState(0); const nextStep = () => setCurrentStepIndex((currentStepIndex + 1) % stepCount); const prevStep = () => setCurrentStepIndex((currentStepIndex - 1 + stepCount) % stepCount); return { currentStepIndex, setCurrentStepIndex, nextStep, prevStep, currentStep: steps[currentStepIndex], }; } function Steps< T extends { name: string; value: string; }[], >(props: { steps: T; onStepChange?: (index: number) => void; index: number }) { const steps = props.steps; const stepCount = steps.length; return ( <div className={styles["steps"]}> <div className={styles["steps-progress"]}> <div className={styles["steps-progress-inner"]} style={{ width: `${((props.index + 1) / stepCount) * 100}%`, }} ></div> </div> <div className={styles["steps-inner"]}> {steps.map((step, i) => { return ( <div key={i} className={clsx("clickable", styles["step"], { [styles["step-finished"]]: i <= props.index, [styles["step-current"]]: i === props.index, })} onClick={() => { props.onStepChange?.(i); }} role="button" > <span className={styles["step-index"]}>{i + 1}</span> <span className={styles["step-name"]}>{step.name}</span> </div> ); })} </div> </div> ); } export function MessageExporter() { const steps = [ { name: Locale.Export.Steps.Select, value: "select", }, { name: Locale.Export.Steps.Preview, value: "preview", }, ]; const { currentStep, setCurrentStepIndex, currentStepIndex } = useSteps(steps); const formats = ["text", "image", "json"] as const; type ExportFormat = (typeof formats)[number]; const [exportConfig, setExportConfig] = useState({ format: "image" as ExportFormat, includeContext: true, }); function updateExportConfig(updater: (config: typeof exportConfig) => void) { const config = { ...exportConfig }; updater(config); setExportConfig(config); } const chatStore = useChatStore(); const session = chatStore.currentSession(); const { selection, updateSelection } = useMessageSelector(); const selectedMessages = useMemo(() => { const ret: ChatMessage[] = []; if (exportConfig.includeContext) { ret.push(...session.mask.context); } ret.push(...session.messages.filter((m) => selection.has(m.id))); return ret; }, [ exportConfig.includeContext, session.messages, session.mask.context, selection, ]); function preview() { if (exportConfig.format === "text") { return ( <MarkdownPreviewer messages={selectedMessages} topic={session.topic} /> ); } else if (exportConfig.format === "json") { return ( <JsonPreviewer messages={selectedMessages} topic={session.topic} /> ); } else { return ( <ImagePreviewer messages={selectedMessages} topic={session.topic} /> ); } } return ( <> <Steps steps={steps} index={currentStepIndex} onStepChange={setCurrentStepIndex} /> <div className={styles["message-exporter-body"]} style={currentStep.value !== "select" ? { display: "none" } : {}} > <List> <ListItem title={Locale.Export.Format.Title} subTitle={Locale.Export.Format.SubTitle} > <Select value={exportConfig.format} onChange={(e) => updateExportConfig( (config) => (config.format = e.currentTarget.value as ExportFormat), ) } > {formats.map((f) => ( <option key={f} value={f}> {f} </option> ))} </Select> </ListItem> <ListItem title={Locale.Export.IncludeContext.Title} subTitle={Locale.Export.IncludeContext.SubTitle} > <input type="checkbox" checked={exportConfig.includeContext} onChange={(e) => { updateExportConfig( (config) => (config.includeContext = e.currentTarget.checked), ); }} ></input> </ListItem> </List> <MessageSelector selection={selection} updateSelection={updateSelection} defaultSelectAll /> </div> {currentStep.value === "preview" && ( <div className={styles["message-exporter-body"]}>{preview()}</div> )} </> ); } export function RenderExport(props: { messages: ChatMessage[]; onRender: (messages: ChatMessage[]) => void; }) { const domRef = useRef<HTMLDivElement>(null); useEffect(() => { if (!domRef.current) return; const dom = domRef.current; const messages = Array.from( dom.getElementsByClassName(EXPORT_MESSAGE_CLASS_NAME), ); if (messages.length !== props.messages.length) { return; } const renderMsgs = messages.map((v, i) => { const [role, _] = v.id.split(":"); return { id: i.toString(), role: role as any, content: role === "user" ? v.textContent ?? "" : v.innerHTML, date: "", }; }); props.onRender(renderMsgs); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <div ref={domRef}> {props.messages.map((m, i) => ( <div key={i} id={`${m.role}:${i}`} className={EXPORT_MESSAGE_CLASS_NAME} > <Markdown content={getMessageTextContent(m)} defaultShow /> </div> ))} </div> ); } export function PreviewActions(props: { download: () => void; copy: () => void; showCopy?: boolean; messages?: ChatMessage[]; }) { const [loading, setLoading] = useState(false); const [shouldExport, setShouldExport] = useState(false); const config = useAppConfig(); const onRenderMsgs = (msgs: ChatMessage[]) => { setShouldExport(false); const api: ClientApi = getClientApi(config.modelConfig.providerName); api .share(msgs) .then((res) => { if (!res) return; showModal({ title: Locale.Export.Share, children: [ <input type="text" value={res} key="input" style={{ width: "100%", maxWidth: "unset", }} readOnly onClick={(e) => e.currentTarget.select()} ></input>, ], actions: [ <IconButton icon={<CopyIcon />} text={Locale.Chat.Actions.Copy} key="copy" onClick={() => copyToClipboard(res)} />, ], }); setTimeout(() => { window.open(res, "_blank"); }, 800); }) .catch((e) => { console.error("[Share]", e); showToast(prettyObject(e)); }) .finally(() => setLoading(false)); }; const share = async () => { if (props.messages?.length) { setLoading(true); setShouldExport(true); } }; return ( <> <div className={styles["preview-actions"]}> {props.showCopy && ( <IconButton text={Locale.Export.Copy} bordered shadow icon={<CopyIcon />} onClick={props.copy} ></IconButton> )} <IconButton text={Locale.Export.Download} bordered shadow icon={<DownloadIcon />} onClick={props.download} ></IconButton> <IconButton text={Locale.Export.Share} bordered shadow icon={loading ? <LoadingIcon /> : <ShareIcon />} onClick={share} ></IconButton> </div> <div style={{ position: "fixed", right: "200vw", pointerEvents: "none", }} > {shouldExport && ( <RenderExport messages={props.messages ?? []} onRender={onRenderMsgs} /> )} </div> </> ); } export function ImagePreviewer(props: { messages: ChatMessage[]; topic: string; }) { const chatStore = useChatStore(); const session = chatStore.currentSession(); const mask = session.mask; const config = useAppConfig(); const previewRef = useRef<HTMLDivElement>(null); const copy = () => { showToast(Locale.Export.Image.Toast); const dom = previewRef.current; if (!dom) return; toBlob(dom).then((blob) => { if (!blob) return; try { navigator.clipboard .write([ new ClipboardItem({ "image/png": blob, }), ]) .then(() => { showToast(Locale.Copy.Success); refreshPreview(); }); } catch (e) { console.error("[Copy Image] ", e); showToast(Locale.Copy.Failed); } }); }; const isMobile = useMobileScreen(); const download = async () => { showToast(Locale.Export.Image.Toast); const dom = previewRef.current; if (!dom) return; const isApp = getClientConfig()?.isApp; try { const blob = await toPng(dom); if (!blob) return; if (isMobile || (isApp && window.__TAURI__)) { if (isApp && window.__TAURI__) { const result = await window.__TAURI__.dialog.save({ defaultPath: `${props.topic}.png`, filters: [ { name: "PNG Files", extensions: ["png"], }, { name: "All Files", extensions: ["*"], }, ], }); if (result !== null) { const response = await fetch(blob); const buffer = await response.arrayBuffer(); const uint8Array = new Uint8Array(buffer); await window.__TAURI__.fs.writeBinaryFile(result, uint8Array); showToast(Locale.Download.Success); } else { showToast(Locale.Download.Failed); } } else { showImageModal(blob); } } else { const link = document.createElement("a"); link.download = `${props.topic}.png`; link.href = blob; link.click(); refreshPreview(); } } catch (error) { showToast(Locale.Download.Failed); } }; const refreshPreview = () => { const dom = previewRef.current; if (dom) { dom.innerHTML = dom.innerHTML; // Refresh the content of the preview by resetting its HTML for fix a bug glitching } }; return ( <div className={styles["image-previewer"]}> <PreviewActions copy={copy} download={download} showCopy={!isMobile} messages={props.messages} /> <div className={clsx(styles["preview-body"], styles["default-theme"])} ref={previewRef} > <div className={styles["chat-info"]}> <div className={clsx(styles["logo"], "no-dark")}> <NextImage src={ChatGptIcon.src} alt="logo" width={50} height={50} /> </div> <div> <div className={styles["main-title"]}>NextChat</div> <div className={styles["sub-title"]}> github.com/ChatGPTNextWeb/ChatGPT-Next-Web </div> <div className={styles["icons"]}> <MaskAvatar avatar={config.avatar} /> <span className={styles["icon-space"]}>&</span> <MaskAvatar avatar={mask.avatar} model={session.mask.modelConfig.model} /> </div> </div> <div> <div className={styles["chat-info-item"]}> {Locale.Exporter.Model}: {mask.modelConfig.model} </div> <div className={styles["chat-info-item"]}> {Locale.Exporter.Messages}: {props.messages.length} </div> <div className={styles["chat-info-item"]}> {Locale.Exporter.Topic}: {session.topic} </div> <div className={styles["chat-info-item"]}> {Locale.Exporter.Time}:{" "} {new Date( props.messages.at(-1)?.date ?? Date.now(), ).toLocaleString()} </div> </div> </div> {props.messages.map((m, i) => { return ( <div className={clsx(styles["message"], styles["message-" + m.role])} key={i} > <div className={styles["avatar"]}> {m.role === "user" ? ( <Avatar avatar={config.avatar}></Avatar> ) : ( <MaskAvatar avatar={session.mask.avatar} model={m.model || session.mask.modelConfig.model} /> )} </div> <div className={styles["body"]}> <Markdown content={getMessageTextContent(m)} fontSize={config.fontSize} fontFamily={config.fontFamily} defaultShow /> {getMessageImages(m).length == 1 && ( <img key={i} src={getMessageImages(m)[0]} alt="message" className={styles["message-image"]} /> )} {getMessageImages(m).length > 1 && ( <div className={styles["message-images"]} style={ { "--image-count": getMessageImages(m).length, } as React.CSSProperties } > {getMessageImages(m).map((src, i) => ( <img key={i} src={src} alt="message" className={styles["message-image-multi"]} /> ))} </div> )} </div> </div> ); })} </div> </div> ); } export function MarkdownPreviewer(props: { messages: ChatMessage[]; topic: string; }) { const mdText = `# ${props.topic}\n\n` + props.messages .map((m) => { return m.role === "user" ? `## ${Locale.Export.MessageFromYou}:\n${getMessageTextContent(m)}` : `## ${Locale.Export.MessageFromChatGPT}:\n${getMessageTextContent( m, ).trim()}`; }) .join("\n\n"); const copy = () => { copyToClipboard(mdText); }; const download = () => { downloadAs(mdText, `${props.topic}.md`); }; return ( <> <PreviewActions copy={copy} download={download} showCopy={true} messages={props.messages} /> <div className="markdown-body"> <pre className={styles["export-content"]}>{mdText}</pre> </div> </> ); } export function JsonPreviewer(props: { messages: ChatMessage[]; topic: string; }) { const msgs = { messages: [ { role: "system", content: `${Locale.FineTuned.Sysmessage} ${props.topic}`, }, ...props.messages.map((m) => ({ role: m.role, content: m.content, })), ], }; const mdText = "```json\n" + JSON.stringify(msgs, null, 2) + "\n```"; const minifiedJson = JSON.stringify(msgs); const copy = () => { copyToClipboard(minifiedJson); }; const download = () => { downloadAs(JSON.stringify(msgs), `${props.topic}.json`); }; return ( <> <PreviewActions copy={copy} download={download} showCopy={false} messages={props.messages} /> <div className="markdown-body" onClick={copy}> <Markdown content={mdText} /> </div> </> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/auth.tsx
app/components/auth.tsx
import styles from "./auth.module.scss"; import { IconButton } from "./button"; import { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { Path, SAAS_CHAT_URL } from "../constant"; import { useAccessStore } from "../store"; import Locale from "../locales"; import Delete from "../icons/close.svg"; import Arrow from "../icons/arrow.svg"; import Logo from "../icons/logo.svg"; import { useMobileScreen } from "@/app/utils"; import BotIcon from "../icons/bot.svg"; import { getClientConfig } from "../config/client"; import { PasswordInput } from "./ui-lib"; import LeftIcon from "@/app/icons/left.svg"; import { safeLocalStorage } from "@/app/utils"; import { trackSettingsPageGuideToCPaymentClick, trackAuthorizationPageButtonToCPaymentClick, } from "../utils/auth-settings-events"; import clsx from "clsx"; const storage = safeLocalStorage(); export function AuthPage() { const navigate = useNavigate(); const accessStore = useAccessStore(); const goHome = () => navigate(Path.Home); const goChat = () => navigate(Path.Chat); const goSaas = () => { trackAuthorizationPageButtonToCPaymentClick(); window.location.href = SAAS_CHAT_URL; }; const resetAccessCode = () => { accessStore.update((access) => { access.openaiApiKey = ""; access.accessCode = ""; }); }; // Reset access code to empty string useEffect(() => { if (getClientConfig()?.isApp) { navigate(Path.Settings); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <div className={styles["auth-page"]}> <TopBanner></TopBanner> <div className={styles["auth-header"]}> <IconButton icon={<LeftIcon />} text={Locale.Auth.Return} onClick={() => navigate(Path.Home)} ></IconButton> </div> <div className={clsx("no-dark", styles["auth-logo"])}> <BotIcon /> </div> <div className={styles["auth-title"]}>{Locale.Auth.Title}</div> <div className={styles["auth-tips"]}>{Locale.Auth.Tips}</div> <PasswordInput style={{ marginTop: "3vh", marginBottom: "3vh" }} aria={Locale.Settings.ShowPassword} aria-label={Locale.Auth.Input} value={accessStore.accessCode} type="text" placeholder={Locale.Auth.Input} onChange={(e) => { accessStore.update( (access) => (access.accessCode = e.currentTarget.value), ); }} /> {!accessStore.hideUserApiKey ? ( <> <div className={styles["auth-tips"]}>{Locale.Auth.SubTips}</div> <PasswordInput style={{ marginTop: "3vh", marginBottom: "3vh" }} aria={Locale.Settings.ShowPassword} aria-label={Locale.Settings.Access.OpenAI.ApiKey.Placeholder} value={accessStore.openaiApiKey} type="text" placeholder={Locale.Settings.Access.OpenAI.ApiKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.openaiApiKey = e.currentTarget.value), ); }} /> <PasswordInput style={{ marginTop: "3vh", marginBottom: "3vh" }} aria={Locale.Settings.ShowPassword} aria-label={Locale.Settings.Access.Google.ApiKey.Placeholder} value={accessStore.googleApiKey} type="text" placeholder={Locale.Settings.Access.Google.ApiKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.googleApiKey = e.currentTarget.value), ); }} /> </> ) : null} <div className={styles["auth-actions"]}> <IconButton text={Locale.Auth.Confirm} type="primary" onClick={goChat} /> <IconButton text={Locale.Auth.SaasTips} onClick={() => { goSaas(); }} /> </div> </div> ); } function TopBanner() { const [isHovered, setIsHovered] = useState(false); const [isVisible, setIsVisible] = useState(true); const isMobile = useMobileScreen(); useEffect(() => { // 检查 localStorage 中是否有标记 const bannerDismissed = storage.getItem("bannerDismissed"); // 如果标记不存在,存储默认值并显示横幅 if (!bannerDismissed) { storage.setItem("bannerDismissed", "false"); setIsVisible(true); // 显示横幅 } else if (bannerDismissed === "true") { // 如果标记为 "true",则隐藏横幅 setIsVisible(false); } }, []); const handleMouseEnter = () => { setIsHovered(true); }; const handleMouseLeave = () => { setIsHovered(false); }; const handleClose = () => { setIsVisible(false); storage.setItem("bannerDismissed", "true"); }; if (!isVisible) { return null; } return ( <div className={styles["top-banner"]} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} > <div className={clsx(styles["top-banner-inner"], "no-dark")}> <Logo className={styles["top-banner-logo"]}></Logo> <span> {Locale.Auth.TopTips} <a href={SAAS_CHAT_URL} rel="stylesheet" onClick={() => { trackSettingsPageGuideToCPaymentClick(); }} > {Locale.Settings.Access.SaasStart.ChatNow} <Arrow style={{ marginLeft: "4px" }} /> </a> </span> </div> {(isHovered || isMobile) && ( <Delete className={styles["top-banner-close"]} onClick={handleClose} /> )} </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/plugin.tsx
app/components/plugin.tsx
import { useDebouncedCallback } from "use-debounce"; import OpenAPIClientAxios from "openapi-client-axios"; import yaml from "js-yaml"; import { PLUGINS_REPO_URL } from "../constant"; import { IconButton } from "./button"; import { ErrorBoundary } from "./error"; import styles from "./mask.module.scss"; import pluginStyles from "./plugin.module.scss"; import EditIcon from "../icons/edit.svg"; import AddIcon from "../icons/add.svg"; import CloseIcon from "../icons/close.svg"; import DeleteIcon from "../icons/delete.svg"; import ConfirmIcon from "../icons/confirm.svg"; import ReloadIcon from "../icons/reload.svg"; import GithubIcon from "../icons/github.svg"; import { Plugin, usePluginStore, FunctionToolService } from "../store/plugin"; import { PasswordInput, List, ListItem, Modal, showConfirm, showToast, } from "./ui-lib"; import Locale from "../locales"; import { useNavigate } from "react-router-dom"; import { useState } from "react"; import clsx from "clsx"; export function PluginPage() { const navigate = useNavigate(); const pluginStore = usePluginStore(); const allPlugins = pluginStore.getAll(); const [searchPlugins, setSearchPlugins] = useState<Plugin[]>([]); const [searchText, setSearchText] = useState(""); const plugins = searchText.length > 0 ? searchPlugins : allPlugins; // refactored already, now it accurate const onSearch = (text: string) => { setSearchText(text); if (text.length > 0) { const result = allPlugins.filter( (m) => m?.title.toLowerCase().includes(text.toLowerCase()), ); setSearchPlugins(result); } else { setSearchPlugins(allPlugins); } }; const [editingPluginId, setEditingPluginId] = useState<string | undefined>(); const editingPlugin = pluginStore.get(editingPluginId); const editingPluginTool = FunctionToolService.get(editingPlugin?.id); const closePluginModal = () => setEditingPluginId(undefined); const onChangePlugin = useDebouncedCallback((editingPlugin, e) => { const content = e.target.innerText; try { const api = new OpenAPIClientAxios({ definition: yaml.load(content) as any, }); api .init() .then(() => { if (content != editingPlugin.content) { pluginStore.updatePlugin(editingPlugin.id, (plugin) => { plugin.content = content; const tool = FunctionToolService.add(plugin, true); plugin.title = tool.api.definition.info.title; plugin.version = tool.api.definition.info.version; }); } }) .catch((e) => { console.error(e); showToast(Locale.Plugin.EditModal.Error); }); } catch (e) { console.error(e); showToast(Locale.Plugin.EditModal.Error); } }, 100).bind(null, editingPlugin); const [loadUrl, setLoadUrl] = useState<string>(""); const loadFromUrl = (loadUrl: string) => fetch(loadUrl) .catch((e) => { const p = new URL(loadUrl); return fetch(`/api/proxy/${p.pathname}?${p.search}`, { headers: { "X-Base-URL": p.origin, }, }); }) .then((res) => res.text()) .then((content) => { try { return JSON.stringify(JSON.parse(content), null, " "); } catch (e) { return content; } }) .then((content) => { pluginStore.updatePlugin(editingPlugin.id, (plugin) => { plugin.content = content; const tool = FunctionToolService.add(plugin, true); plugin.title = tool.api.definition.info.title; plugin.version = tool.api.definition.info.version; }); }) .catch((e) => { showToast(Locale.Plugin.EditModal.Error); }); return ( <ErrorBoundary> <div className={styles["mask-page"]}> <div className="window-header"> <div className="window-header-title"> <div className="window-header-main-title"> {Locale.Plugin.Page.Title} </div> <div className="window-header-submai-title"> {Locale.Plugin.Page.SubTitle(plugins.length)} </div> </div> <div className="window-actions"> <div className="window-action-button"> <a href={PLUGINS_REPO_URL} target="_blank" rel="noopener noreferrer" > <IconButton icon={<GithubIcon />} bordered /> </a> </div> <div className="window-action-button"> <IconButton icon={<CloseIcon />} bordered onClick={() => navigate(-1)} /> </div> </div> </div> <div className={styles["mask-page-body"]}> <div className={styles["mask-filter"]}> <input type="text" className={styles["search-bar"]} placeholder={Locale.Plugin.Page.Search} autoFocus onInput={(e) => onSearch(e.currentTarget.value)} /> <IconButton className={styles["mask-create"]} icon={<AddIcon />} text={Locale.Plugin.Page.Create} bordered onClick={() => { const createdPlugin = pluginStore.create(); setEditingPluginId(createdPlugin.id); }} /> </div> <div> {plugins.length == 0 && ( <div style={{ display: "flex", margin: "60px auto", alignItems: "center", justifyContent: "center", }} > {Locale.Plugin.Page.Find} <a href={PLUGINS_REPO_URL} target="_blank" rel="noopener noreferrer" style={{ marginLeft: 16 }} > <IconButton icon={<GithubIcon />} bordered /> </a> </div> )} {plugins.map((m) => ( <div className={styles["mask-item"]} key={m.id}> <div className={styles["mask-header"]}> <div className={styles["mask-icon"]}></div> <div className={styles["mask-title"]}> <div className={styles["mask-name"]}> {m.title}@<small>{m.version}</small> </div> <div className={clsx(styles["mask-info"], "one-line")}> {Locale.Plugin.Item.Info( FunctionToolService.add(m).length, )} </div> </div> </div> <div className={styles["mask-actions"]}> <IconButton icon={<EditIcon />} text={Locale.Plugin.Item.Edit} onClick={() => setEditingPluginId(m.id)} /> {!m.builtin && ( <IconButton icon={<DeleteIcon />} text={Locale.Plugin.Item.Delete} onClick={async () => { if ( await showConfirm(Locale.Plugin.Item.DeleteConfirm) ) { pluginStore.delete(m.id); } }} /> )} </div> </div> ))} </div> </div> </div> {editingPlugin && ( <div className="modal-mask"> <Modal title={Locale.Plugin.EditModal.Title(editingPlugin?.builtin)} onClose={closePluginModal} actions={[ <IconButton icon={<ConfirmIcon />} text={Locale.UI.Confirm} key="export" bordered onClick={() => setEditingPluginId("")} />, ]} > <List> <ListItem title={Locale.Plugin.EditModal.Auth}> <select value={editingPlugin?.authType} onChange={(e) => { pluginStore.updatePlugin(editingPlugin.id, (plugin) => { plugin.authType = e.target.value; }); }} > <option value="">{Locale.Plugin.Auth.None}</option> <option value="bearer">{Locale.Plugin.Auth.Bearer}</option> <option value="basic">{Locale.Plugin.Auth.Basic}</option> <option value="custom">{Locale.Plugin.Auth.Custom}</option> </select> </ListItem> {["bearer", "basic", "custom"].includes( editingPlugin.authType as string, ) && ( <ListItem title={Locale.Plugin.Auth.Location}> <select value={editingPlugin?.authLocation} onChange={(e) => { pluginStore.updatePlugin(editingPlugin.id, (plugin) => { plugin.authLocation = e.target.value; }); }} > <option value="header"> {Locale.Plugin.Auth.LocationHeader} </option> <option value="query"> {Locale.Plugin.Auth.LocationQuery} </option> <option value="body"> {Locale.Plugin.Auth.LocationBody} </option> </select> </ListItem> )} {editingPlugin.authType == "custom" && ( <ListItem title={Locale.Plugin.Auth.CustomHeader}> <input type="text" value={editingPlugin?.authHeader} onChange={(e) => { pluginStore.updatePlugin(editingPlugin.id, (plugin) => { plugin.authHeader = e.target.value; }); }} ></input> </ListItem> )} {["bearer", "basic", "custom"].includes( editingPlugin.authType as string, ) && ( <ListItem title={Locale.Plugin.Auth.Token}> <PasswordInput type="text" value={editingPlugin?.authToken} onChange={(e) => { pluginStore.updatePlugin(editingPlugin.id, (plugin) => { plugin.authToken = e.currentTarget.value; }); }} ></PasswordInput> </ListItem> )} </List> <List> <ListItem title={Locale.Plugin.EditModal.Content}> <div className={pluginStyles["plugin-schema"]}> <input type="text" style={{ minWidth: 200 }} onInput={(e) => setLoadUrl(e.currentTarget.value)} ></input> <IconButton icon={<ReloadIcon />} text={Locale.Plugin.EditModal.Load} bordered onClick={() => loadFromUrl(loadUrl)} /> </div> </ListItem> <ListItem subTitle={ <div className={clsx( "markdown-body", pluginStyles["plugin-content"], )} dir="auto" > <pre> <code contentEditable={true} dangerouslySetInnerHTML={{ __html: editingPlugin.content, }} onBlur={onChangePlugin} ></code> </pre> </div> } ></ListItem> {editingPluginTool?.tools.map((tool, index) => ( <ListItem key={index} title={tool?.function?.name} subTitle={tool?.function?.description} /> ))} </List> </Modal> </div> )} </ErrorBoundary> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/ui-lib.tsx
app/components/ui-lib.tsx
/* eslint-disable @next/next/no-img-element */ import styles from "./ui-lib.module.scss"; import LoadingIcon from "../icons/three-dots.svg"; import CloseIcon from "../icons/close.svg"; import EyeIcon from "../icons/eye.svg"; import EyeOffIcon from "../icons/eye-off.svg"; import DownIcon from "../icons/down.svg"; import ConfirmIcon from "../icons/confirm.svg"; import CancelIcon from "../icons/cancel.svg"; import MaxIcon from "../icons/max.svg"; import MinIcon from "../icons/min.svg"; import Locale from "../locales"; import { createRoot } from "react-dom/client"; import React, { CSSProperties, HTMLProps, MouseEvent, useEffect, useState, useCallback, useRef, } from "react"; import { IconButton } from "./button"; import { Avatar } from "./emoji"; import clsx from "clsx"; export function Popover(props: { children: JSX.Element; content: JSX.Element; open?: boolean; onClose?: () => void; }) { return ( <div className={styles.popover}> {props.children} {props.open && ( <div className={styles["popover-mask"]} onClick={props.onClose}></div> )} {props.open && ( <div className={styles["popover-content"]}>{props.content}</div> )} </div> ); } export function Card(props: { children: JSX.Element[]; className?: string }) { return ( <div className={clsx(styles.card, props.className)}>{props.children}</div> ); } export function ListItem(props: { title?: string; subTitle?: string | JSX.Element; children?: JSX.Element | JSX.Element[]; icon?: JSX.Element; className?: string; onClick?: (e: MouseEvent) => void; vertical?: boolean; }) { return ( <div className={clsx( styles["list-item"], { [styles["vertical"]]: props.vertical, }, props.className, )} onClick={props.onClick} > <div className={styles["list-header"]}> {props.icon && <div className={styles["list-icon"]}>{props.icon}</div>} <div className={styles["list-item-title"]}> <div>{props.title}</div> {props.subTitle && ( <div className={styles["list-item-sub-title"]}> {props.subTitle} </div> )} </div> </div> {props.children} </div> ); } export function List(props: { children: React.ReactNode; id?: string }) { return ( <div className={styles.list} id={props.id}> {props.children} </div> ); } export function Loading() { return ( <div style={{ height: "100vh", width: "100vw", display: "flex", alignItems: "center", justifyContent: "center", }} > <LoadingIcon /> </div> ); } interface ModalProps { title: string; children?: any; actions?: React.ReactNode[]; defaultMax?: boolean; footer?: React.ReactNode; onClose?: () => void; } export function Modal(props: ModalProps) { useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { if (e.key === "Escape") { props.onClose?.(); } }; window.addEventListener("keydown", onKeyDown); return () => { window.removeEventListener("keydown", onKeyDown); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const [isMax, setMax] = useState(!!props.defaultMax); return ( <div className={clsx(styles["modal-container"], { [styles["modal-container-max"]]: isMax, })} > <div className={styles["modal-header"]}> <div className={styles["modal-title"]}>{props.title}</div> <div className={styles["modal-header-actions"]}> <div className={styles["modal-header-action"]} onClick={() => setMax(!isMax)} > {isMax ? <MinIcon /> : <MaxIcon />} </div> <div className={styles["modal-header-action"]} onClick={props.onClose} > <CloseIcon /> </div> </div> </div> <div className={styles["modal-content"]}>{props.children}</div> <div className={styles["modal-footer"]}> {props.footer} <div className={styles["modal-actions"]}> {props.actions?.map((action, i) => ( <div key={i} className={styles["modal-action"]}> {action} </div> ))} </div> </div> </div> ); } export function showModal(props: ModalProps) { const div = document.createElement("div"); div.className = "modal-mask"; document.body.appendChild(div); const root = createRoot(div); const closeModal = () => { props.onClose?.(); root.unmount(); div.remove(); }; div.onclick = (e) => { if (e.target === div) { closeModal(); } }; root.render(<Modal {...props} onClose={closeModal}></Modal>); } export type ToastProps = { content: string; action?: { text: string; onClick: () => void; }; onClose?: () => void; }; export function Toast(props: ToastProps) { return ( <div className={styles["toast-container"]}> <div className={styles["toast-content"]}> <span>{props.content}</span> {props.action && ( <button onClick={() => { props.action?.onClick?.(); props.onClose?.(); }} className={styles["toast-action"]} > {props.action.text} </button> )} </div> </div> ); } export function showToast( content: string, action?: ToastProps["action"], delay = 3000, ) { const div = document.createElement("div"); div.className = styles.show; document.body.appendChild(div); const root = createRoot(div); const close = () => { div.classList.add(styles.hide); setTimeout(() => { root.unmount(); div.remove(); }, 300); }; setTimeout(() => { close(); }, delay); root.render(<Toast content={content} action={action} onClose={close} />); } export type InputProps = React.HTMLProps<HTMLTextAreaElement> & { autoHeight?: boolean; rows?: number; }; export function Input(props: InputProps) { return ( <textarea {...props} className={clsx(styles["input"], props.className)} ></textarea> ); } export function PasswordInput( props: HTMLProps<HTMLInputElement> & { aria?: string }, ) { const [visible, setVisible] = useState(false); function changeVisibility() { setVisible(!visible); } return ( <div className={"password-input-container"}> <IconButton aria={props.aria} icon={visible ? <EyeIcon /> : <EyeOffIcon />} onClick={changeVisibility} className={"password-eye"} /> <input {...props} type={visible ? "text" : "password"} className={"password-input"} /> </div> ); } export function Select( props: React.DetailedHTMLProps< React.SelectHTMLAttributes<HTMLSelectElement> & { align?: "left" | "center"; }, HTMLSelectElement >, ) { const { className, children, align, ...otherProps } = props; return ( <div className={clsx( styles["select-with-icon"], { [styles["left-align-option"]]: align === "left", }, className, )} > <select className={styles["select-with-icon-select"]} {...otherProps}> {children} </select> <DownIcon className={styles["select-with-icon-icon"]} /> </div> ); } export function showConfirm(content: any) { const div = document.createElement("div"); div.className = "modal-mask"; document.body.appendChild(div); const root = createRoot(div); const closeModal = () => { root.unmount(); div.remove(); }; return new Promise<boolean>((resolve) => { root.render( <Modal title={Locale.UI.Confirm} actions={[ <IconButton key="cancel" text={Locale.UI.Cancel} onClick={() => { resolve(false); closeModal(); }} icon={<CancelIcon />} tabIndex={0} bordered shadow ></IconButton>, <IconButton key="confirm" text={Locale.UI.Confirm} type="primary" onClick={() => { resolve(true); closeModal(); }} icon={<ConfirmIcon />} tabIndex={0} autoFocus bordered shadow ></IconButton>, ]} onClose={closeModal} > {content} </Modal>, ); }); } function PromptInput(props: { value: string; onChange: (value: string) => void; rows?: number; }) { const [input, setInput] = useState(props.value); const onInput = (value: string) => { props.onChange(value); setInput(value); }; return ( <textarea className={styles["modal-input"]} autoFocus value={input} onInput={(e) => onInput(e.currentTarget.value)} rows={props.rows ?? 3} ></textarea> ); } export function showPrompt(content: any, value = "", rows = 3) { const div = document.createElement("div"); div.className = "modal-mask"; document.body.appendChild(div); const root = createRoot(div); const closeModal = () => { root.unmount(); div.remove(); }; return new Promise<string>((resolve) => { let userInput = value; root.render( <Modal title={content} actions={[ <IconButton key="cancel" text={Locale.UI.Cancel} onClick={() => { closeModal(); }} icon={<CancelIcon />} bordered shadow tabIndex={0} ></IconButton>, <IconButton key="confirm" text={Locale.UI.Confirm} type="primary" onClick={() => { resolve(userInput); closeModal(); }} icon={<ConfirmIcon />} bordered shadow tabIndex={0} ></IconButton>, ]} onClose={closeModal} > <PromptInput onChange={(val) => (userInput = val)} value={value} rows={rows} ></PromptInput> </Modal>, ); }); } export function showImageModal( img: string, defaultMax?: boolean, style?: CSSProperties, boxStyle?: CSSProperties, ) { showModal({ title: Locale.Export.Image.Modal, defaultMax: defaultMax, children: ( <div style={{ display: "flex", justifyContent: "center", ...boxStyle }}> <img src={img} alt="preview" style={ style ?? { maxWidth: "100%", } } ></img> </div> ), }); } export function Selector<T>(props: { items: Array<{ title: string; subTitle?: string; value: T; disable?: boolean; }>; defaultSelectedValue?: T[] | T; onSelection?: (selection: T[]) => void; onClose?: () => void; multiple?: boolean; }) { const [selectedValues, setSelectedValues] = useState<T[]>( Array.isArray(props.defaultSelectedValue) ? props.defaultSelectedValue : props.defaultSelectedValue !== undefined ? [props.defaultSelectedValue] : [], ); const handleSelection = (e: MouseEvent, value: T) => { if (props.multiple) { e.stopPropagation(); const newSelectedValues = selectedValues.includes(value) ? selectedValues.filter((v) => v !== value) : [...selectedValues, value]; setSelectedValues(newSelectedValues); props.onSelection?.(newSelectedValues); } else { setSelectedValues([value]); props.onSelection?.([value]); props.onClose?.(); } }; return ( <div className={styles["selector"]} onClick={() => props.onClose?.()}> <div className={styles["selector-content"]}> <List> {props.items.map((item, i) => { const selected = selectedValues.includes(item.value); return ( <ListItem className={clsx(styles["selector-item"], { [styles["selector-item-disabled"]]: item.disable, })} key={i} title={item.title} subTitle={item.subTitle} icon={<Avatar model={item.value as string} />} onClick={(e) => { if (item.disable) { e.stopPropagation(); } else { handleSelection(e, item.value); } }} > {selected ? ( <div style={{ height: 10, width: 10, backgroundColor: "var(--primary)", borderRadius: 10, }} ></div> ) : ( <></> )} </ListItem> ); })} </List> </div> </div> ); } export function FullScreen(props: any) { const { children, right = 10, top = 10, ...rest } = props; const ref = useRef<HTMLDivElement>(); const [fullScreen, setFullScreen] = useState(false); const toggleFullscreen = useCallback(() => { if (!document.fullscreenElement) { ref.current?.requestFullscreen(); } else { document.exitFullscreen(); } }, []); useEffect(() => { const handleScreenChange = (e: any) => { if (e.target === ref.current) { setFullScreen(!!document.fullscreenElement); } }; document.addEventListener("fullscreenchange", handleScreenChange); return () => { document.removeEventListener("fullscreenchange", handleScreenChange); }; }, []); return ( <div ref={ref} style={{ position: "relative" }} {...rest}> <div style={{ position: "absolute", right, top }}> <IconButton icon={fullScreen ? <MinIcon /> : <MaxIcon />} onClick={toggleFullscreen} bordered /> </div> {children} </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/mcp-market.tsx
app/components/mcp-market.tsx
import { IconButton } from "./button"; import { ErrorBoundary } from "./error"; import styles from "./mcp-market.module.scss"; import EditIcon from "../icons/edit.svg"; import AddIcon from "../icons/add.svg"; import CloseIcon from "../icons/close.svg"; import DeleteIcon from "../icons/delete.svg"; import RestartIcon from "../icons/reload.svg"; import EyeIcon from "../icons/eye.svg"; import GithubIcon from "../icons/github.svg"; import { List, ListItem, Modal, showToast } from "./ui-lib"; import { useNavigate } from "react-router-dom"; import { useEffect, useState } from "react"; import { addMcpServer, getClientsStatus, getClientTools, getMcpConfigFromFile, isMcpEnabled, pauseMcpServer, restartAllClients, resumeMcpServer, } from "../mcp/actions"; import { ListToolsResponse, McpConfigData, PresetServer, ServerConfig, ServerStatusResponse, } from "../mcp/types"; import clsx from "clsx"; import PlayIcon from "../icons/play.svg"; import StopIcon from "../icons/pause.svg"; import { Path } from "../constant"; interface ConfigProperty { type: string; description?: string; required?: boolean; minItems?: number; } export function McpMarketPage() { const navigate = useNavigate(); const [mcpEnabled, setMcpEnabled] = useState(false); const [searchText, setSearchText] = useState(""); const [userConfig, setUserConfig] = useState<Record<string, any>>({}); const [editingServerId, setEditingServerId] = useState<string | undefined>(); const [tools, setTools] = useState<ListToolsResponse["tools"] | null>(null); const [viewingServerId, setViewingServerId] = useState<string | undefined>(); const [isLoading, setIsLoading] = useState(false); const [config, setConfig] = useState<McpConfigData>(); const [clientStatuses, setClientStatuses] = useState< Record<string, ServerStatusResponse> >({}); const [loadingPresets, setLoadingPresets] = useState(true); const [presetServers, setPresetServers] = useState<PresetServer[]>([]); const [loadingStates, setLoadingStates] = useState<Record<string, string>>( {}, ); // 检查 MCP 是否启用 useEffect(() => { const checkMcpStatus = async () => { const enabled = await isMcpEnabled(); setMcpEnabled(enabled); if (!enabled) { navigate(Path.Home); } }; checkMcpStatus(); }, [navigate]); // 添加状态轮询 useEffect(() => { if (!mcpEnabled || !config) return; const updateStatuses = async () => { const statuses = await getClientsStatus(); setClientStatuses(statuses); }; // 立即执行一次 updateStatuses(); // 每 1000ms 轮询一次 const timer = setInterval(updateStatuses, 1000); return () => clearInterval(timer); }, [mcpEnabled, config]); // 加载预设服务器 useEffect(() => { const loadPresetServers = async () => { if (!mcpEnabled) return; try { setLoadingPresets(true); const response = await fetch("https://nextchat.club/mcp/list"); if (!response.ok) { throw new Error("Failed to load preset servers"); } const data = await response.json(); setPresetServers(data?.data ?? []); } catch (error) { console.error("Failed to load preset servers:", error); showToast("Failed to load preset servers"); } finally { setLoadingPresets(false); } }; loadPresetServers(); }, [mcpEnabled]); // 加载初始状态 useEffect(() => { const loadInitialState = async () => { if (!mcpEnabled) return; try { setIsLoading(true); const config = await getMcpConfigFromFile(); setConfig(config); // 获取所有客户端的状态 const statuses = await getClientsStatus(); setClientStatuses(statuses); } catch (error) { console.error("Failed to load initial state:", error); showToast("Failed to load initial state"); } finally { setIsLoading(false); } }; loadInitialState(); }, [mcpEnabled]); // 加载当前编辑服务器的配置 useEffect(() => { if (!editingServerId || !config) return; const currentConfig = config.mcpServers[editingServerId]; if (currentConfig) { // 从当前配置中提取用户配置 const preset = presetServers.find((s) => s.id === editingServerId); if (preset?.configSchema) { const userConfig: Record<string, any> = {}; Object.entries(preset.argsMapping || {}).forEach(([key, mapping]) => { if (mapping.type === "spread") { // For spread types, extract the array from args. const startPos = mapping.position ?? 0; userConfig[key] = currentConfig.args.slice(startPos); } else if (mapping.type === "single") { // For single types, get a single value userConfig[key] = currentConfig.args[mapping.position ?? 0]; } else if ( mapping.type === "env" && mapping.key && currentConfig.env ) { // For env types, get values from environment variables userConfig[key] = currentConfig.env[mapping.key]; } }); setUserConfig(userConfig); } } else { setUserConfig({}); } }, [editingServerId, config, presetServers]); if (!mcpEnabled) { return null; } // 检查服务器是否已添加 const isServerAdded = (id: string) => { return id in (config?.mcpServers ?? {}); }; // 保存服务器配置 const saveServerConfig = async () => { const preset = presetServers.find((s) => s.id === editingServerId); if (!preset || !preset.configSchema || !editingServerId) return; const savingServerId = editingServerId; setEditingServerId(undefined); try { updateLoadingState(savingServerId, "Updating configuration..."); // 构建服务器配置 const args = [...preset.baseArgs]; const env: Record<string, string> = {}; Object.entries(preset.argsMapping || {}).forEach(([key, mapping]) => { const value = userConfig[key]; if (mapping.type === "spread" && Array.isArray(value)) { const pos = mapping.position ?? 0; args.splice(pos, 0, ...value); } else if ( mapping.type === "single" && mapping.position !== undefined ) { args[mapping.position] = value; } else if ( mapping.type === "env" && mapping.key && typeof value === "string" ) { env[mapping.key] = value; } }); const serverConfig: ServerConfig = { command: preset.command, args, ...(Object.keys(env).length > 0 ? { env } : {}), }; const newConfig = await addMcpServer(savingServerId, serverConfig); setConfig(newConfig); showToast("Server configuration updated successfully"); } catch (error) { showToast( error instanceof Error ? error.message : "Failed to save configuration", ); } finally { updateLoadingState(savingServerId, null); } }; // 获取服务器支持的 Tools const loadTools = async (id: string) => { try { const result = await getClientTools(id); if (result) { setTools(result); } else { throw new Error("Failed to load tools"); } } catch (error) { showToast("Failed to load tools"); console.error(error); setTools(null); } }; // 更新加载状态的辅助函数 const updateLoadingState = (id: string, message: string | null) => { setLoadingStates((prev) => { if (message === null) { const { [id]: _, ...rest } = prev; return rest; } return { ...prev, [id]: message }; }); }; // 修改添加服务器函数 const addServer = async (preset: PresetServer) => { if (!preset.configurable) { try { const serverId = preset.id; updateLoadingState(serverId, "Creating MCP client..."); const serverConfig: ServerConfig = { command: preset.command, args: [...preset.baseArgs], }; const newConfig = await addMcpServer(preset.id, serverConfig); setConfig(newConfig); // 更新状态 const statuses = await getClientsStatus(); setClientStatuses(statuses); } finally { updateLoadingState(preset.id, null); } } else { // 如果需要配置,打开配置对话框 setEditingServerId(preset.id); setUserConfig({}); } }; // 修改暂停服务器函数 const pauseServer = async (id: string) => { try { updateLoadingState(id, "Stopping server..."); const newConfig = await pauseMcpServer(id); setConfig(newConfig); showToast("Server stopped successfully"); } catch (error) { showToast("Failed to stop server"); console.error(error); } finally { updateLoadingState(id, null); } }; // Restart server const restartServer = async (id: string) => { try { updateLoadingState(id, "Starting server..."); await resumeMcpServer(id); } catch (error) { showToast( error instanceof Error ? error.message : "Failed to start server, please check logs", ); console.error(error); } finally { updateLoadingState(id, null); } }; // Restart all clients const handleRestartAll = async () => { try { updateLoadingState("all", "Restarting all servers..."); const newConfig = await restartAllClients(); setConfig(newConfig); showToast("Restarting all clients"); } catch (error) { showToast("Failed to restart clients"); console.error(error); } finally { updateLoadingState("all", null); } }; // Render configuration form const renderConfigForm = () => { const preset = presetServers.find((s) => s.id === editingServerId); if (!preset?.configSchema) return null; return Object.entries(preset.configSchema.properties).map( ([key, prop]: [string, ConfigProperty]) => { if (prop.type === "array") { const currentValue = userConfig[key as keyof typeof userConfig] || []; const itemLabel = (prop as any).itemLabel || key; const addButtonText = (prop as any).addButtonText || `Add ${itemLabel}`; return ( <ListItem key={key} title={key} subTitle={prop.description} vertical > <div className={styles["path-list"]}> {(currentValue as string[]).map( (value: string, index: number) => ( <div key={index} className={styles["path-item"]}> <input type="text" value={value} placeholder={`${itemLabel} ${index + 1}`} onChange={(e) => { const newValue = [...currentValue] as string[]; newValue[index] = e.target.value; setUserConfig({ ...userConfig, [key]: newValue }); }} /> <IconButton icon={<DeleteIcon />} className={styles["delete-button"]} onClick={() => { const newValue = [...currentValue] as string[]; newValue.splice(index, 1); setUserConfig({ ...userConfig, [key]: newValue }); }} /> </div> ), )} <IconButton icon={<AddIcon />} text={addButtonText} className={styles["add-button"]} bordered onClick={() => { const newValue = [...currentValue, ""] as string[]; setUserConfig({ ...userConfig, [key]: newValue }); }} /> </div> </ListItem> ); } else if (prop.type === "string") { const currentValue = userConfig[key as keyof typeof userConfig] || ""; return ( <ListItem key={key} title={key} subTitle={prop.description}> <input aria-label={key} type="text" value={currentValue} placeholder={`Enter ${key}`} onChange={(e) => { setUserConfig({ ...userConfig, [key]: e.target.value }); }} /> </ListItem> ); } return null; }, ); }; const checkServerStatus = (clientId: string) => { return clientStatuses[clientId] || { status: "undefined", errorMsg: null }; }; const getServerStatusDisplay = (clientId: string) => { const status = checkServerStatus(clientId); const statusMap = { undefined: null, // 未配置/未找到不显示 // 添加初始化状态 initializing: ( <span className={clsx(styles["server-status"], styles["initializing"])}> Initializing </span> ), paused: ( <span className={clsx(styles["server-status"], styles["stopped"])}> Stopped </span> ), active: <span className={styles["server-status"]}>Running</span>, error: ( <span className={clsx(styles["server-status"], styles["error"])}> Error <span className={styles["error-message"]}>: {status.errorMsg}</span> </span> ), }; return statusMap[status.status]; }; // Get the type of operation status const getOperationStatusType = (message: string) => { if (message.toLowerCase().includes("stopping")) return "stopping"; if (message.toLowerCase().includes("starting")) return "starting"; if (message.toLowerCase().includes("error")) return "error"; return "default"; }; // 渲染服务器列表 const renderServerList = () => { if (loadingPresets) { return ( <div className={styles["loading-container"]}> <div className={styles["loading-text"]}> Loading preset server list... </div> </div> ); } if (!Array.isArray(presetServers) || presetServers.length === 0) { return ( <div className={styles["empty-container"]}> <div className={styles["empty-text"]}>No servers available</div> </div> ); } return presetServers .filter((server) => { if (searchText.length === 0) return true; const searchLower = searchText.toLowerCase(); return ( server.name.toLowerCase().includes(searchLower) || server.description.toLowerCase().includes(searchLower) || server.tags.some((tag) => tag.toLowerCase().includes(searchLower)) ); }) .sort((a, b) => { const aStatus = checkServerStatus(a.id).status; const bStatus = checkServerStatus(b.id).status; const aLoading = loadingStates[a.id]; const bLoading = loadingStates[b.id]; // 定义状态优先级 const statusPriority: Record<string, number> = { error: 0, // Highest priority for error status active: 1, // Second for active initializing: 2, // Initializing starting: 3, // Starting stopping: 4, // Stopping paused: 5, // Paused undefined: 6, // Lowest priority for undefined }; // Get actual status (including loading status) const getEffectiveStatus = (status: string, loading?: string) => { if (loading) { const operationType = getOperationStatusType(loading); return operationType === "default" ? status : operationType; } if (status === "initializing" && !loading) { return "active"; } return status; }; const aEffectiveStatus = getEffectiveStatus(aStatus, aLoading); const bEffectiveStatus = getEffectiveStatus(bStatus, bLoading); // 首先按状态排序 if (aEffectiveStatus !== bEffectiveStatus) { return ( (statusPriority[aEffectiveStatus] ?? 6) - (statusPriority[bEffectiveStatus] ?? 6) ); } // Sort by name when statuses are the same return a.name.localeCompare(b.name); }) .map((server) => ( <div className={clsx(styles["mcp-market-item"], { [styles["loading"]]: loadingStates[server.id], })} key={server.id} > <div className={styles["mcp-market-header"]}> <div className={styles["mcp-market-title"]}> <div className={styles["mcp-market-name"]}> {server.name} {loadingStates[server.id] && ( <span className={styles["operation-status"]} data-status={getOperationStatusType( loadingStates[server.id], )} > {loadingStates[server.id]} </span> )} {!loadingStates[server.id] && getServerStatusDisplay(server.id)} {server.repo && ( <a href={server.repo} target="_blank" rel="noopener noreferrer" className={styles["repo-link"]} title="Open repository" > <GithubIcon /> </a> )} </div> <div className={styles["tags-container"]}> {server.tags.map((tag, index) => ( <span key={index} className={styles["tag"]}> {tag} </span> ))} </div> <div className={clsx(styles["mcp-market-info"], "one-line")} title={server.description} > {server.description} </div> </div> <div className={styles["mcp-market-actions"]}> {isServerAdded(server.id) ? ( <> {server.configurable && ( <IconButton icon={<EditIcon />} text="Configure" onClick={() => setEditingServerId(server.id)} disabled={isLoading} /> )} {checkServerStatus(server.id).status === "paused" ? ( <> <IconButton icon={<PlayIcon />} text="Start" onClick={() => restartServer(server.id)} disabled={isLoading} /> {/* <IconButton icon={<DeleteIcon />} text="Remove" onClick={() => removeServer(server.id)} disabled={isLoading} /> */} </> ) : ( <> <IconButton icon={<EyeIcon />} text="Tools" onClick={async () => { setViewingServerId(server.id); await loadTools(server.id); }} disabled={ isLoading || checkServerStatus(server.id).status === "error" } /> <IconButton icon={<StopIcon />} text="Stop" onClick={() => pauseServer(server.id)} disabled={isLoading} /> </> )} </> ) : ( <IconButton icon={<AddIcon />} text="Add" onClick={() => addServer(server)} disabled={isLoading} /> )} </div> </div> </div> )); }; return ( <ErrorBoundary> <div className={styles["mcp-market-page"]}> <div className="window-header"> <div className="window-header-title"> <div className="window-header-main-title"> MCP Market {loadingStates["all"] && ( <span className={styles["loading-indicator"]}> {loadingStates["all"]} </span> )} </div> <div className="window-header-sub-title"> {Object.keys(config?.mcpServers ?? {}).length} servers configured </div> </div> <div className="window-actions"> <div className="window-action-button"> <IconButton icon={<RestartIcon />} bordered onClick={handleRestartAll} text="Restart All" disabled={isLoading} /> </div> <div className="window-action-button"> <IconButton icon={<CloseIcon />} bordered onClick={() => navigate(-1)} disabled={isLoading} /> </div> </div> </div> <div className={styles["mcp-market-page-body"]}> <div className={styles["mcp-market-filter"]}> <input type="text" className={styles["search-bar"]} placeholder={"Search MCP Server"} autoFocus onInput={(e) => setSearchText(e.currentTarget.value)} /> </div> <div className={styles["server-list"]}>{renderServerList()}</div> </div> {/*编辑服务器配置*/} {editingServerId && ( <div className="modal-mask"> <Modal title={`Configure Server - ${editingServerId}`} onClose={() => !isLoading && setEditingServerId(undefined)} actions={[ <IconButton key="cancel" text="Cancel" onClick={() => setEditingServerId(undefined)} bordered disabled={isLoading} />, <IconButton key="confirm" text="Save" type="primary" onClick={saveServerConfig} bordered disabled={isLoading} />, ]} > <List>{renderConfigForm()}</List> </Modal> </div> )} {viewingServerId && ( <div className="modal-mask"> <Modal title={`Server Details - ${viewingServerId}`} onClose={() => setViewingServerId(undefined)} actions={[ <IconButton key="close" text="Close" onClick={() => setViewingServerId(undefined)} bordered />, ]} > <div className={styles["tools-list"]}> {isLoading ? ( <div>Loading...</div> ) : tools?.tools ? ( tools.tools.map( (tool: ListToolsResponse["tools"], index: number) => ( <div key={index} className={styles["tool-item"]}> <div className={styles["tool-name"]}>{tool.name}</div> <div className={styles["tool-description"]}> {tool.description} </div> </div> ), ) ) : ( <div>No tools available</div> )} </div> </Modal> </div> )} </div> </ErrorBoundary> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/artifacts.tsx
app/components/artifacts.tsx
import { useEffect, useState, useRef, useMemo, forwardRef, useImperativeHandle, } from "react"; import { useParams } from "react-router"; import { IconButton } from "./button"; import { nanoid } from "nanoid"; import ExportIcon from "../icons/share.svg"; import CopyIcon from "../icons/copy.svg"; import DownloadIcon from "../icons/download.svg"; import GithubIcon from "../icons/github.svg"; import LoadingButtonIcon from "../icons/loading.svg"; import ReloadButtonIcon from "../icons/reload.svg"; import Locale from "../locales"; import { Modal, showToast } from "./ui-lib"; import { copyToClipboard, downloadAs } from "../utils"; import { Path, ApiPath, REPO_URL } from "@/app/constant"; import { Loading } from "./home"; import styles from "./artifacts.module.scss"; type HTMLPreviewProps = { code: string; autoHeight?: boolean; height?: number | string; onLoad?: (title?: string) => void; }; export type HTMLPreviewHandler = { reload: () => void; }; export const HTMLPreview = forwardRef<HTMLPreviewHandler, HTMLPreviewProps>( function HTMLPreview(props, ref) { const iframeRef = useRef<HTMLIFrameElement>(null); const [frameId, setFrameId] = useState<string>(nanoid()); const [iframeHeight, setIframeHeight] = useState(600); const [title, setTitle] = useState(""); /* * https://stackoverflow.com/questions/19739001/what-is-the-difference-between-srcdoc-and-src-datatext-html-in-an * 1. using srcdoc * 2. using src with dataurl: * easy to share * length limit (Data URIs cannot be larger than 32,768 characters.) */ useEffect(() => { const handleMessage = (e: any) => { const { id, height, title } = e.data; setTitle(title); if (id == frameId) { setIframeHeight(height); } }; window.addEventListener("message", handleMessage); return () => { window.removeEventListener("message", handleMessage); }; }, [frameId]); useImperativeHandle(ref, () => ({ reload: () => { setFrameId(nanoid()); }, })); const height = useMemo(() => { if (!props.autoHeight) return props.height || 600; if (typeof props.height === "string") { return props.height; } const parentHeight = props.height || 600; return iframeHeight + 40 > parentHeight ? parentHeight : iframeHeight + 40; }, [props.autoHeight, props.height, iframeHeight]); const srcDoc = useMemo(() => { const script = `<script>window.addEventListener("DOMContentLoaded", () => new ResizeObserver((entries) => parent.postMessage({id: '${frameId}', height: entries[0].target.clientHeight}, '*')).observe(document.body))</script>`; if (props.code.includes("<!DOCTYPE html>")) { props.code.replace("<!DOCTYPE html>", "<!DOCTYPE html>" + script); } return script + props.code; }, [props.code, frameId]); const handleOnLoad = () => { if (props?.onLoad) { props.onLoad(title); } }; return ( <iframe className={styles["artifacts-iframe"]} key={frameId} ref={iframeRef} sandbox="allow-forms allow-modals allow-scripts" style={{ height }} srcDoc={srcDoc} onLoad={handleOnLoad} /> ); }, ); export function ArtifactsShareButton({ getCode, id, style, fileName, }: { getCode: () => string; id?: string; style?: any; fileName?: string; }) { const [loading, setLoading] = useState(false); const [name, setName] = useState(id); const [show, setShow] = useState(false); const shareUrl = useMemo( () => [location.origin, "#", Path.Artifacts, "/", name].join(""), [name], ); const upload = (code: string) => id ? Promise.resolve({ id }) : fetch(ApiPath.Artifacts, { method: "POST", body: code, }) .then((res) => res.json()) .then(({ id }) => { if (id) { return { id }; } throw Error(); }) .catch((e) => { showToast(Locale.Export.Artifacts.Error); }); return ( <> <div className="window-action-button" style={style}> <IconButton icon={loading ? <LoadingButtonIcon /> : <ExportIcon />} bordered title={Locale.Export.Artifacts.Title} onClick={() => { if (loading) return; setLoading(true); upload(getCode()) .then((res) => { if (res?.id) { setShow(true); setName(res?.id); } }) .finally(() => setLoading(false)); }} /> </div> {show && ( <div className="modal-mask"> <Modal title={Locale.Export.Artifacts.Title} onClose={() => setShow(false)} actions={[ <IconButton key="download" icon={<DownloadIcon />} bordered text={Locale.Export.Download} onClick={() => { downloadAs(getCode(), `${fileName || name}.html`).then(() => setShow(false), ); }} />, <IconButton key="copy" icon={<CopyIcon />} bordered text={Locale.Chat.Actions.Copy} onClick={() => { copyToClipboard(shareUrl).then(() => setShow(false)); }} />, ]} > <div> <a target="_blank" href={shareUrl}> {shareUrl} </a> </div> </Modal> </div> )} </> ); } export function Artifacts() { const { id } = useParams(); const [code, setCode] = useState(""); const [loading, setLoading] = useState(true); const [fileName, setFileName] = useState(""); const previewRef = useRef<HTMLPreviewHandler>(null); useEffect(() => { if (id) { fetch(`${ApiPath.Artifacts}?id=${id}`) .then((res) => { if (res.status > 300) { throw Error("can not get content"); } return res; }) .then((res) => res.text()) .then(setCode) .catch((e) => { showToast(Locale.Export.Artifacts.Error); }); } }, [id]); return ( <div className={styles["artifacts"]}> <div className={styles["artifacts-header"]}> <a href={REPO_URL} target="_blank" rel="noopener noreferrer"> <IconButton bordered icon={<GithubIcon />} shadow /> </a> <IconButton bordered style={{ marginLeft: 20 }} icon={<ReloadButtonIcon />} shadow onClick={() => previewRef.current?.reload()} /> <div className={styles["artifacts-title"]}>NextChat Artifacts</div> <ArtifactsShareButton id={id} getCode={() => code} fileName={fileName} /> </div> <div className={styles["artifacts-content"]}> {loading && <Loading />} {code && ( <HTMLPreview code={code} ref={previewRef} autoHeight={false} height={"100%"} onLoad={(title) => { setFileName(title as string); setLoading(false); }} /> )} </div> </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/tts-config.tsx
app/components/tts-config.tsx
import { TTSConfig, TTSConfigValidator } from "../store"; import Locale from "../locales"; import { ListItem, Select } from "./ui-lib"; import { DEFAULT_TTS_ENGINE, DEFAULT_TTS_ENGINES, DEFAULT_TTS_MODELS, DEFAULT_TTS_VOICES, } from "../constant"; import { InputRange } from "./input-range"; export function TTSConfigList(props: { ttsConfig: TTSConfig; updateConfig: (updater: (config: TTSConfig) => void) => void; }) { return ( <> <ListItem title={Locale.Settings.TTS.Enable.Title} subTitle={Locale.Settings.TTS.Enable.SubTitle} > <input type="checkbox" checked={props.ttsConfig.enable} onChange={(e) => props.updateConfig( (config) => (config.enable = e.currentTarget.checked), ) } ></input> </ListItem> {/* <ListItem title={Locale.Settings.TTS.Autoplay.Title} subTitle={Locale.Settings.TTS.Autoplay.SubTitle} > <input type="checkbox" checked={props.ttsConfig.autoplay} onChange={(e) => props.updateConfig( (config) => (config.autoplay = e.currentTarget.checked), ) } ></input> </ListItem> */} <ListItem title={Locale.Settings.TTS.Engine}> <Select value={props.ttsConfig.engine} onChange={(e) => { props.updateConfig( (config) => (config.engine = TTSConfigValidator.engine( e.currentTarget.value, )), ); }} > {DEFAULT_TTS_ENGINES.map((v, i) => ( <option value={v} key={i}> {v} </option> ))} </Select> </ListItem> {props.ttsConfig.engine === DEFAULT_TTS_ENGINE && ( <> <ListItem title={Locale.Settings.TTS.Model}> <Select value={props.ttsConfig.model} onChange={(e) => { props.updateConfig( (config) => (config.model = TTSConfigValidator.model( e.currentTarget.value, )), ); }} > {DEFAULT_TTS_MODELS.map((v, i) => ( <option value={v} key={i}> {v} </option> ))} </Select> </ListItem> <ListItem title={Locale.Settings.TTS.Voice.Title} subTitle={Locale.Settings.TTS.Voice.SubTitle} > <Select value={props.ttsConfig.voice} onChange={(e) => { props.updateConfig( (config) => (config.voice = TTSConfigValidator.voice( e.currentTarget.value, )), ); }} > {DEFAULT_TTS_VOICES.map((v, i) => ( <option value={v} key={i}> {v} </option> ))} </Select> </ListItem> <ListItem title={Locale.Settings.TTS.Speed.Title} subTitle={Locale.Settings.TTS.Speed.SubTitle} > <InputRange aria={Locale.Settings.TTS.Speed.Title} value={props.ttsConfig.speed?.toFixed(1)} min="0.3" max="4.0" step="0.1" onChange={(e) => { props.updateConfig( (config) => (config.speed = TTSConfigValidator.speed( e.currentTarget.valueAsNumber, )), ); }} ></InputRange> </ListItem> </> )} </> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/button.tsx
app/components/button.tsx
import * as React from "react"; import styles from "./button.module.scss"; import { CSSProperties } from "react"; import clsx from "clsx"; export type ButtonType = "primary" | "danger" | null; export function IconButton(props: { onClick?: () => void; icon?: JSX.Element; type?: ButtonType; text?: string; bordered?: boolean; shadow?: boolean; className?: string; title?: string; disabled?: boolean; tabIndex?: number; autoFocus?: boolean; style?: CSSProperties; aria?: string; }) { return ( <button className={clsx( "clickable", styles["icon-button"], { [styles.border]: props.bordered, [styles.shadow]: props.shadow, }, styles[props.type ?? ""], props.className, )} onClick={props.onClick} title={props.title} disabled={props.disabled} role="button" tabIndex={props.tabIndex} autoFocus={props.autoFocus} style={props.style} aria-label={props.aria} > {props.icon && ( <div aria-label={props.text || props.title} className={clsx(styles["icon-button-icon"], { "no-dark": props.type === "primary", })} > {props.icon} </div> )} {props.text && ( <div aria-label={props.text || props.title} className={styles["icon-button-text"]} > {props.text} </div> )} </button> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/sidebar.tsx
app/components/sidebar.tsx
import React, { Fragment, useEffect, useMemo, useRef, useState } from "react"; import styles from "./home.module.scss"; import { IconButton } from "./button"; import SettingsIcon from "../icons/settings.svg"; import GithubIcon from "../icons/github.svg"; import ChatGptIcon from "../icons/chatgpt.svg"; import AddIcon from "../icons/add.svg"; import DeleteIcon from "../icons/delete.svg"; import MaskIcon from "../icons/mask.svg"; import McpIcon from "../icons/mcp.svg"; import DragIcon from "../icons/drag.svg"; import DiscoveryIcon from "../icons/discovery.svg"; import Locale from "../locales"; import { useAppConfig, useChatStore } from "../store"; import { DEFAULT_SIDEBAR_WIDTH, MAX_SIDEBAR_WIDTH, MIN_SIDEBAR_WIDTH, NARROW_SIDEBAR_WIDTH, Path, REPO_URL, } from "../constant"; import { Link, useNavigate } from "react-router-dom"; import { isIOS, useMobileScreen } from "../utils"; import dynamic from "next/dynamic"; import { Selector, showConfirm } from "./ui-lib"; import clsx from "clsx"; import { isMcpEnabled } from "../mcp/actions"; const DISCOVERY = [ { name: Locale.Plugin.Name, path: Path.Plugins }, { name: "Stable Diffusion", path: Path.Sd }, { name: Locale.SearchChat.Page.Title, path: Path.SearchChat }, ]; const ChatList = dynamic(async () => (await import("./chat-list")).ChatList, { loading: () => null, }); export function useHotKey() { const chatStore = useChatStore(); useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { if (e.altKey || e.ctrlKey) { if (e.key === "ArrowUp") { chatStore.nextSession(-1); } else if (e.key === "ArrowDown") { chatStore.nextSession(1); } } }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }); } export function useDragSideBar() { const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x); const config = useAppConfig(); const startX = useRef(0); const startDragWidth = useRef(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH); const lastUpdateTime = useRef(Date.now()); const toggleSideBar = () => { config.update((config) => { if (config.sidebarWidth < MIN_SIDEBAR_WIDTH) { config.sidebarWidth = DEFAULT_SIDEBAR_WIDTH; } else { config.sidebarWidth = NARROW_SIDEBAR_WIDTH; } }); }; const onDragStart = (e: MouseEvent) => { // Remembers the initial width each time the mouse is pressed startX.current = e.clientX; startDragWidth.current = config.sidebarWidth; const dragStartTime = Date.now(); const handleDragMove = (e: MouseEvent) => { if (Date.now() < lastUpdateTime.current + 20) { return; } lastUpdateTime.current = Date.now(); const d = e.clientX - startX.current; const nextWidth = limit(startDragWidth.current + d); config.update((config) => { if (nextWidth < MIN_SIDEBAR_WIDTH) { config.sidebarWidth = NARROW_SIDEBAR_WIDTH; } else { config.sidebarWidth = nextWidth; } }); }; const handleDragEnd = () => { // In useRef the data is non-responsive, so `config.sidebarWidth` can't get the dynamic sidebarWidth window.removeEventListener("pointermove", handleDragMove); window.removeEventListener("pointerup", handleDragEnd); // if user click the drag icon, should toggle the sidebar const shouldFireClick = Date.now() - dragStartTime < 300; if (shouldFireClick) { toggleSideBar(); } }; window.addEventListener("pointermove", handleDragMove); window.addEventListener("pointerup", handleDragEnd); }; const isMobileScreen = useMobileScreen(); const shouldNarrow = !isMobileScreen && config.sidebarWidth < MIN_SIDEBAR_WIDTH; useEffect(() => { const barWidth = shouldNarrow ? NARROW_SIDEBAR_WIDTH : limit(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH); const sideBarWidth = isMobileScreen ? "100vw" : `${barWidth}px`; document.documentElement.style.setProperty("--sidebar-width", sideBarWidth); }, [config.sidebarWidth, isMobileScreen, shouldNarrow]); return { onDragStart, shouldNarrow, }; } export function SideBarContainer(props: { children: React.ReactNode; onDragStart: (e: MouseEvent) => void; shouldNarrow: boolean; className?: string; }) { const isMobileScreen = useMobileScreen(); const isIOSMobile = useMemo( () => isIOS() && isMobileScreen, [isMobileScreen], ); const { children, className, onDragStart, shouldNarrow } = props; return ( <div className={clsx(styles.sidebar, className, { [styles["narrow-sidebar"]]: shouldNarrow, })} style={{ // #3016 disable transition on ios mobile screen transition: isMobileScreen && isIOSMobile ? "none" : undefined, }} > {children} <div className={styles["sidebar-drag"]} onPointerDown={(e) => onDragStart(e as any)} > <DragIcon /> </div> </div> ); } export function SideBarHeader(props: { title?: string | React.ReactNode; subTitle?: string | React.ReactNode; logo?: React.ReactNode; children?: React.ReactNode; shouldNarrow?: boolean; }) { const { title, subTitle, logo, children, shouldNarrow } = props; return ( <Fragment> <div className={clsx(styles["sidebar-header"], { [styles["sidebar-header-narrow"]]: shouldNarrow, })} data-tauri-drag-region > <div className={styles["sidebar-title-container"]}> <div className={styles["sidebar-title"]} data-tauri-drag-region> {title} </div> <div className={styles["sidebar-sub-title"]}>{subTitle}</div> </div> <div className={clsx(styles["sidebar-logo"], "no-dark")}>{logo}</div> </div> {children} </Fragment> ); } export function SideBarBody(props: { children: React.ReactNode; onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void; }) { const { onClick, children } = props; return ( <div className={styles["sidebar-body"]} onClick={onClick}> {children} </div> ); } export function SideBarTail(props: { primaryAction?: React.ReactNode; secondaryAction?: React.ReactNode; }) { const { primaryAction, secondaryAction } = props; return ( <div className={styles["sidebar-tail"]}> <div className={styles["sidebar-actions"]}>{primaryAction}</div> <div className={styles["sidebar-actions"]}>{secondaryAction}</div> </div> ); } export function SideBar(props: { className?: string }) { useHotKey(); const { onDragStart, shouldNarrow } = useDragSideBar(); const [showDiscoverySelector, setshowDiscoverySelector] = useState(false); const navigate = useNavigate(); const config = useAppConfig(); const chatStore = useChatStore(); const [mcpEnabled, setMcpEnabled] = useState(false); useEffect(() => { // 检查 MCP 是否启用 const checkMcpStatus = async () => { const enabled = await isMcpEnabled(); setMcpEnabled(enabled); console.log("[SideBar] MCP enabled:", enabled); }; checkMcpStatus(); }, []); return ( <SideBarContainer onDragStart={onDragStart} shouldNarrow={shouldNarrow} {...props} > <SideBarHeader title="NextChat" subTitle="Build your own AI assistant." logo={<ChatGptIcon />} shouldNarrow={shouldNarrow} > <div className={styles["sidebar-header-bar"]}> <IconButton icon={<MaskIcon />} text={shouldNarrow ? undefined : Locale.Mask.Name} className={styles["sidebar-bar-button"]} onClick={() => { if (config.dontShowMaskSplashScreen !== true) { navigate(Path.NewChat, { state: { fromHome: true } }); } else { navigate(Path.Masks, { state: { fromHome: true } }); } }} shadow /> {mcpEnabled && ( <IconButton icon={<McpIcon />} text={shouldNarrow ? undefined : Locale.Mcp.Name} className={styles["sidebar-bar-button"]} onClick={() => { navigate(Path.McpMarket, { state: { fromHome: true } }); }} shadow /> )} <IconButton icon={<DiscoveryIcon />} text={shouldNarrow ? undefined : Locale.Discovery.Name} className={styles["sidebar-bar-button"]} onClick={() => setshowDiscoverySelector(true)} shadow /> </div> {showDiscoverySelector && ( <Selector items={[ ...DISCOVERY.map((item) => { return { title: item.name, value: item.path, }; }), ]} onClose={() => setshowDiscoverySelector(false)} onSelection={(s) => { navigate(s[0], { state: { fromHome: true } }); }} /> )} </SideBarHeader> <SideBarBody onClick={(e) => { if (e.target === e.currentTarget) { navigate(Path.Home); } }} > <ChatList narrow={shouldNarrow} /> </SideBarBody> <SideBarTail primaryAction={ <> <div className={clsx(styles["sidebar-action"], styles.mobile)}> <IconButton icon={<DeleteIcon />} onClick={async () => { if (await showConfirm(Locale.Home.DeleteChat)) { chatStore.deleteSession(chatStore.currentSessionIndex); } }} /> </div> <div className={styles["sidebar-action"]}> <Link to={Path.Settings}> <IconButton aria={Locale.Settings.Title} icon={<SettingsIcon />} shadow /> </Link> </div> <div className={styles["sidebar-action"]}> <a href={REPO_URL} target="_blank" rel="noopener noreferrer"> <IconButton aria={Locale.Export.MessageFromChatGPT} icon={<GithubIcon />} shadow /> </a> </div> </> } secondaryAction={ <IconButton icon={<AddIcon />} text={shouldNarrow ? undefined : Locale.Home.NewChat} onClick={() => { if (config.dontShowMaskSplashScreen) { chatStore.newSession(); navigate(Path.Chat); } else { navigate(Path.NewChat); } }} shadow /> } /> </SideBarContainer> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/markdown.tsx
app/components/markdown.tsx
import ReactMarkdown from "react-markdown"; import "katex/dist/katex.min.css"; import RemarkMath from "remark-math"; import RemarkBreaks from "remark-breaks"; import RehypeKatex from "rehype-katex"; import RemarkGfm from "remark-gfm"; import RehypeHighlight from "rehype-highlight"; import { useRef, useState, RefObject, useEffect, useMemo } from "react"; import { copyToClipboard, useWindowSize } from "../utils"; import mermaid from "mermaid"; import Locale from "../locales"; import LoadingIcon from "../icons/three-dots.svg"; import ReloadButtonIcon from "../icons/reload.svg"; import React from "react"; import { useDebouncedCallback } from "use-debounce"; import { showImageModal, FullScreen } from "./ui-lib"; import { ArtifactsShareButton, HTMLPreview, HTMLPreviewHandler, } from "./artifacts"; import { useChatStore } from "../store"; import { IconButton } from "./button"; import { useAppConfig } from "../store/config"; import clsx from "clsx"; export function Mermaid(props: { code: string }) { const ref = useRef<HTMLDivElement>(null); const [hasError, setHasError] = useState(false); useEffect(() => { if (props.code && ref.current) { mermaid .run({ nodes: [ref.current], suppressErrors: true, }) .catch((e) => { setHasError(true); console.error("[Mermaid] ", e.message); }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [props.code]); function viewSvgInNewWindow() { const svg = ref.current?.querySelector("svg"); if (!svg) return; const text = new XMLSerializer().serializeToString(svg); const blob = new Blob([text], { type: "image/svg+xml" }); showImageModal(URL.createObjectURL(blob)); } if (hasError) { return null; } return ( <div className={clsx("no-dark", "mermaid")} style={{ cursor: "pointer", overflow: "auto", }} ref={ref} onClick={() => viewSvgInNewWindow()} > {props.code} </div> ); } export function PreCode(props: { children: any }) { const ref = useRef<HTMLPreElement>(null); const previewRef = useRef<HTMLPreviewHandler>(null); const [mermaidCode, setMermaidCode] = useState(""); const [htmlCode, setHtmlCode] = useState(""); const { height } = useWindowSize(); const chatStore = useChatStore(); const session = chatStore.currentSession(); const renderArtifacts = useDebouncedCallback(() => { if (!ref.current) return; const mermaidDom = ref.current.querySelector("code.language-mermaid"); if (mermaidDom) { setMermaidCode((mermaidDom as HTMLElement).innerText); } const htmlDom = ref.current.querySelector("code.language-html"); const refText = ref.current.querySelector("code")?.innerText; if (htmlDom) { setHtmlCode((htmlDom as HTMLElement).innerText); } else if ( refText?.startsWith("<!DOCTYPE") || refText?.startsWith("<svg") || refText?.startsWith("<?xml") ) { setHtmlCode(refText); } }, 600); const config = useAppConfig(); const enableArtifacts = session.mask?.enableArtifacts !== false && config.enableArtifacts; //Wrap the paragraph for plain-text useEffect(() => { if (ref.current) { const codeElements = ref.current.querySelectorAll( "code", ) as NodeListOf<HTMLElement>; const wrapLanguages = [ "", "md", "markdown", "text", "txt", "plaintext", "tex", "latex", ]; codeElements.forEach((codeElement) => { let languageClass = codeElement.className.match(/language-(\w+)/); let name = languageClass ? languageClass[1] : ""; if (wrapLanguages.includes(name)) { codeElement.style.whiteSpace = "pre-wrap"; } }); setTimeout(renderArtifacts, 1); } }, []); return ( <> <pre ref={ref}> <span className="copy-code-button" onClick={() => { if (ref.current) { copyToClipboard( ref.current.querySelector("code")?.innerText ?? "", ); } }} ></span> {props.children} </pre> {mermaidCode.length > 0 && ( <Mermaid code={mermaidCode} key={mermaidCode} /> )} {htmlCode.length > 0 && enableArtifacts && ( <FullScreen className="no-dark html" right={70}> <ArtifactsShareButton style={{ position: "absolute", right: 20, top: 10 }} getCode={() => htmlCode} /> <IconButton style={{ position: "absolute", right: 120, top: 10 }} bordered icon={<ReloadButtonIcon />} shadow onClick={() => previewRef.current?.reload()} /> <HTMLPreview ref={previewRef} code={htmlCode} autoHeight={!document.fullscreenElement} height={!document.fullscreenElement ? 600 : height} /> </FullScreen> )} </> ); } function CustomCode(props: { children: any; className?: string }) { const chatStore = useChatStore(); const session = chatStore.currentSession(); const config = useAppConfig(); const enableCodeFold = session.mask?.enableCodeFold !== false && config.enableCodeFold; const ref = useRef<HTMLPreElement>(null); const [collapsed, setCollapsed] = useState(true); const [showToggle, setShowToggle] = useState(false); useEffect(() => { if (ref.current) { const codeHeight = ref.current.scrollHeight; setShowToggle(codeHeight > 400); ref.current.scrollTop = ref.current.scrollHeight; } }, [props.children]); const toggleCollapsed = () => { setCollapsed((collapsed) => !collapsed); }; const renderShowMoreButton = () => { if (showToggle && enableCodeFold && collapsed) { return ( <div className={clsx("show-hide-button", { collapsed, expanded: !collapsed, })} > <button onClick={toggleCollapsed}>{Locale.NewChat.More}</button> </div> ); } return null; }; return ( <> <code className={clsx(props?.className)} ref={ref} style={{ maxHeight: enableCodeFold && collapsed ? "400px" : "none", overflowY: "hidden", }} > {props.children} </code> {renderShowMoreButton()} </> ); } function escapeBrackets(text: string) { const pattern = /(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g; return text.replace( pattern, (match, codeBlock, squareBracket, roundBracket) => { if (codeBlock) { return codeBlock; } else if (squareBracket) { return `$$${squareBracket}$$`; } else if (roundBracket) { return `$${roundBracket}$`; } return match; }, ); } function tryWrapHtmlCode(text: string) { // try add wrap html code (fixed: html codeblock include 2 newline) // ignore embed codeblock if (text.includes("```")) { return text; } return text .replace( /([`]*?)(\w*?)([\n\r]*?)(<!DOCTYPE html>)/g, (match, quoteStart, lang, newLine, doctype) => { return !quoteStart ? "\n```html\n" + doctype : match; }, ) .replace( /(<\/body>)([\r\n\s]*?)(<\/html>)([\n\r]*)([`]*)([\n\r]*?)/g, (match, bodyEnd, space, htmlEnd, newLine, quoteEnd) => { return !quoteEnd ? bodyEnd + space + htmlEnd + "\n```\n" : match; }, ); } function _MarkDownContent(props: { content: string }) { const escapedContent = useMemo(() => { return tryWrapHtmlCode(escapeBrackets(props.content)); }, [props.content]); return ( <ReactMarkdown remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]} rehypePlugins={[ RehypeKatex, [ RehypeHighlight, { detect: false, ignoreMissing: true, }, ], ]} components={{ pre: PreCode, code: CustomCode, p: (pProps) => <p {...pProps} dir="auto" />, a: (aProps) => { const href = aProps.href || ""; if (/\.(aac|mp3|opus|wav)$/.test(href)) { return ( <figure> <audio controls src={href}></audio> </figure> ); } if (/\.(3gp|3g2|webm|ogv|mpeg|mp4|avi)$/.test(href)) { return ( <video controls width="99.9%"> <source src={href} /> </video> ); } const isInternal = /^\/#/i.test(href); const target = isInternal ? "_self" : aProps.target ?? "_blank"; return <a {...aProps} target={target} />; }, }} > {escapedContent} </ReactMarkdown> ); } export const MarkdownContent = React.memo(_MarkDownContent); export function Markdown( props: { content: string; loading?: boolean; fontSize?: number; fontFamily?: string; parentRef?: RefObject<HTMLDivElement>; defaultShow?: boolean; } & React.DOMAttributes<HTMLDivElement>, ) { const mdRef = useRef<HTMLDivElement>(null); return ( <div className="markdown-body" style={{ fontSize: `${props.fontSize ?? 14}px`, fontFamily: props.fontFamily || "inherit", }} ref={mdRef} onContextMenu={props.onContextMenu} onDoubleClickCapture={props.onDoubleClickCapture} dir="auto" > {props.loading ? ( <LoadingIcon /> ) : ( <MarkdownContent content={props.content} /> )} </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/emoji.tsx
app/components/emoji.tsx
import EmojiPicker, { Emoji, EmojiStyle, Theme as EmojiTheme, } from "emoji-picker-react"; import { ModelType } from "../store"; import BotIconDefault from "../icons/llm-icons/default.svg"; import BotIconOpenAI from "../icons/llm-icons/openai.svg"; import BotIconGemini from "../icons/llm-icons/gemini.svg"; import BotIconGemma from "../icons/llm-icons/gemma.svg"; import BotIconClaude from "../icons/llm-icons/claude.svg"; import BotIconMeta from "../icons/llm-icons/meta.svg"; import BotIconMistral from "../icons/llm-icons/mistral.svg"; import BotIconDeepseek from "../icons/llm-icons/deepseek.svg"; import BotIconMoonshot from "../icons/llm-icons/moonshot.svg"; import BotIconQwen from "../icons/llm-icons/qwen.svg"; import BotIconWenxin from "../icons/llm-icons/wenxin.svg"; import BotIconGrok from "../icons/llm-icons/grok.svg"; import BotIconHunyuan from "../icons/llm-icons/hunyuan.svg"; import BotIconDoubao from "../icons/llm-icons/doubao.svg"; import BotIconChatglm from "../icons/llm-icons/chatglm.svg"; export function getEmojiUrl(unified: string, style: EmojiStyle) { // Whoever owns this Content Delivery Network (CDN), I am using your CDN to serve emojis // Old CDN broken, so I had to switch to this one // Author: https://github.com/H0llyW00dzZ return `https://fastly.jsdelivr.net/npm/emoji-datasource-apple/img/${style}/64/${unified}.png`; } export function AvatarPicker(props: { onEmojiClick: (emojiId: string) => void; }) { return ( <EmojiPicker width={"100%"} lazyLoadEmojis theme={EmojiTheme.AUTO} getEmojiUrl={getEmojiUrl} onEmojiClick={(e) => { props.onEmojiClick(e.unified); }} /> ); } export function Avatar(props: { model?: ModelType; avatar?: string }) { let LlmIcon = BotIconDefault; if (props.model) { const modelName = props.model.toLowerCase(); if ( modelName.startsWith("gpt") || modelName.startsWith("chatgpt") || modelName.startsWith("dall-e") || modelName.startsWith("dalle") || modelName.startsWith("o1") || modelName.startsWith("o3") ) { LlmIcon = BotIconOpenAI; } else if (modelName.startsWith("gemini")) { LlmIcon = BotIconGemini; } else if (modelName.startsWith("gemma")) { LlmIcon = BotIconGemma; } else if (modelName.startsWith("claude")) { LlmIcon = BotIconClaude; } else if (modelName.includes("llama")) { LlmIcon = BotIconMeta; } else if (modelName.startsWith("mixtral") || modelName.startsWith("codestral")) { LlmIcon = BotIconMistral; } else if (modelName.includes("deepseek")) { LlmIcon = BotIconDeepseek; } else if (modelName.startsWith("moonshot")) { LlmIcon = BotIconMoonshot; } else if (modelName.startsWith("qwen")) { LlmIcon = BotIconQwen; } else if (modelName.startsWith("ernie")) { LlmIcon = BotIconWenxin; } else if (modelName.startsWith("grok")) { LlmIcon = BotIconGrok; } else if (modelName.startsWith("hunyuan")) { LlmIcon = BotIconHunyuan; } else if (modelName.startsWith("doubao") || modelName.startsWith("ep-")) { LlmIcon = BotIconDoubao; } else if ( modelName.includes("glm") || modelName.startsWith("cogview-") || modelName.startsWith("cogvideox-") ) { LlmIcon = BotIconChatglm; } return ( <div className="no-dark"> <LlmIcon className="user-avatar" width={30} height={30} /> </div> ); } return ( <div className="user-avatar"> {props.avatar && <EmojiAvatar avatar={props.avatar} />} </div> ); } export function EmojiAvatar(props: { avatar: string; size?: number }) { return ( <Emoji unified={props.avatar} size={props.size ?? 18} getEmojiUrl={getEmojiUrl} /> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/input-range.tsx
app/components/input-range.tsx
import * as React from "react"; import styles from "./input-range.module.scss"; import clsx from "clsx"; interface InputRangeProps { onChange: React.ChangeEventHandler<HTMLInputElement>; title?: string; value: number | string; className?: string; min: string; max: string; step: string; aria: string; } export function InputRange({ onChange, title, value, className, min, max, step, aria, }: InputRangeProps) { return ( <div className={clsx(styles["input-range"], className)}> {title || value} <input aria-label={aria} type="range" title={title} value={value} min={min} max={max} step={step} onChange={onChange} ></input> </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/error.tsx
app/components/error.tsx
"use client"; import React from "react"; import { IconButton } from "./button"; import GithubIcon from "../icons/github.svg"; import ResetIcon from "../icons/reload.svg"; import { ISSUE_URL } from "../constant"; import Locale from "../locales"; import { showConfirm } from "./ui-lib"; import { useSyncStore } from "../store/sync"; import { useChatStore } from "../store/chat"; interface IErrorBoundaryState { hasError: boolean; error: Error | null; info: React.ErrorInfo | null; } export class ErrorBoundary extends React.Component<any, IErrorBoundaryState> { constructor(props: any) { super(props); this.state = { hasError: false, error: null, info: null }; } componentDidCatch(error: Error, info: React.ErrorInfo) { // Update state with error details this.setState({ hasError: true, error, info }); } clearAndSaveData() { try { useSyncStore.getState().export(); } finally { useChatStore.getState().clearAllData(); } } render() { if (this.state.hasError) { // Render error message return ( <div className="error"> <h2>Oops, something went wrong!</h2> <pre> <code>{this.state.error?.toString()}</code> <code>{this.state.info?.componentStack}</code> </pre> <div style={{ display: "flex", justifyContent: "space-between" }}> <a href={ISSUE_URL} className="report"> <IconButton text="Report This Error" icon={<GithubIcon />} bordered /> </a> <IconButton icon={<ResetIcon />} text="Clear All Data" onClick={async () => { if (await showConfirm(Locale.Settings.Danger.Reset.Confirm)) { this.clearAndSaveData(); } }} bordered /> </div> </div> ); } // if no error occurred, render children return this.props.children; } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/message-selector.tsx
app/components/message-selector.tsx
import { useEffect, useMemo, useState } from "react"; import { ChatMessage, useAppConfig, useChatStore } from "../store"; import { Updater } from "../typing"; import { IconButton } from "./button"; import { Avatar } from "./emoji"; import { MaskAvatar } from "./mask"; import Locale from "../locales"; import styles from "./message-selector.module.scss"; import { getMessageTextContent } from "../utils"; import clsx from "clsx"; function useShiftRange() { const [startIndex, setStartIndex] = useState<number>(); const [endIndex, setEndIndex] = useState<number>(); const [shiftDown, setShiftDown] = useState(false); const onClickIndex = (index: number) => { if (shiftDown && startIndex !== undefined) { setEndIndex(index); } else { setStartIndex(index); setEndIndex(undefined); } }; useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { if (e.key !== "Shift") return; setShiftDown(true); }; const onKeyUp = (e: KeyboardEvent) => { if (e.key !== "Shift") return; setShiftDown(false); setStartIndex(undefined); setEndIndex(undefined); }; window.addEventListener("keyup", onKeyUp); window.addEventListener("keydown", onKeyDown); return () => { window.removeEventListener("keyup", onKeyUp); window.removeEventListener("keydown", onKeyDown); }; }, []); return { onClickIndex, startIndex, endIndex, }; } export function useMessageSelector() { const [selection, setSelection] = useState(new Set<string>()); const updateSelection: Updater<Set<string>> = (updater) => { const newSelection = new Set<string>(selection); updater(newSelection); setSelection(newSelection); }; return { selection, updateSelection, }; } export function MessageSelector(props: { selection: Set<string>; updateSelection: Updater<Set<string>>; defaultSelectAll?: boolean; onSelected?: (messages: ChatMessage[]) => void; }) { const LATEST_COUNT = 4; const chatStore = useChatStore(); const session = chatStore.currentSession(); const isValid = (m: ChatMessage) => m.content && !m.isError && !m.streaming; const allMessages = useMemo(() => { let startIndex = Math.max(0, session.clearContextIndex ?? 0); if (startIndex === session.messages.length - 1) { startIndex = 0; } return session.messages.slice(startIndex); }, [session.messages, session.clearContextIndex]); const messages = useMemo( () => allMessages.filter( (m, i) => m.id && // message must have id isValid(m) && (i >= allMessages.length - 1 || isValid(allMessages[i + 1])), ), [allMessages], ); const messageCount = messages.length; const config = useAppConfig(); const [searchInput, setSearchInput] = useState(""); const [searchIds, setSearchIds] = useState(new Set<string>()); const isInSearchResult = (id: string) => { return searchInput.length === 0 || searchIds.has(id); }; const doSearch = (text: string) => { const searchResults = new Set<string>(); if (text.length > 0) { messages.forEach((m) => getMessageTextContent(m).includes(text) ? searchResults.add(m.id!) : null, ); } setSearchIds(searchResults); }; // for range selection const { startIndex, endIndex, onClickIndex } = useShiftRange(); const selectAll = () => { props.updateSelection((selection) => messages.forEach((m) => selection.add(m.id!)), ); }; useEffect(() => { if (props.defaultSelectAll) { selectAll(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { if (startIndex === undefined || endIndex === undefined) { return; } const [start, end] = [startIndex, endIndex].sort((a, b) => a - b); props.updateSelection((selection) => { for (let i = start; i <= end; i += 1) { selection.add(messages[i].id ?? i); } }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [startIndex, endIndex]); return ( <div className={styles["message-selector"]}> <div className={styles["message-filter"]}> <input type="text" placeholder={Locale.Select.Search} className={clsx(styles["filter-item"], styles["search-bar"])} value={searchInput} onInput={(e) => { setSearchInput(e.currentTarget.value); doSearch(e.currentTarget.value); }} ></input> <div className={styles["actions"]}> <IconButton text={Locale.Select.All} bordered className={styles["filter-item"]} onClick={selectAll} /> <IconButton text={Locale.Select.Latest} bordered className={styles["filter-item"]} onClick={() => props.updateSelection((selection) => { selection.clear(); messages .slice(messageCount - LATEST_COUNT) .forEach((m) => selection.add(m.id!)); }) } /> <IconButton text={Locale.Select.Clear} bordered className={styles["filter-item"]} onClick={() => props.updateSelection((selection) => selection.clear()) } /> </div> </div> <div className={styles["messages"]}> {messages.map((m, i) => { if (!isInSearchResult(m.id!)) return null; const id = m.id ?? i; const isSelected = props.selection.has(id); return ( <div className={clsx(styles["message"], { [styles["message-selected"]]: props.selection.has(m.id!), })} key={i} onClick={() => { props.updateSelection((selection) => { selection.has(id) ? selection.delete(id) : selection.add(id); }); onClickIndex(i); }} > <div className={styles["avatar"]}> {m.role === "user" ? ( <Avatar avatar={config.avatar}></Avatar> ) : ( <MaskAvatar avatar={session.mask.avatar} model={m.model || session.mask.modelConfig.model} /> )} </div> <div className={styles["body"]}> <div className={styles["date"]}> {new Date(m.date).toLocaleString()} </div> <div className={clsx(styles["content"], "one-line")}> {getMessageTextContent(m)} </div> </div> <div className={styles["checkbox"]}> <input type="checkbox" checked={isSelected} readOnly></input> </div> </div> ); })} </div> </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/chat-list.tsx
app/components/chat-list.tsx
import DeleteIcon from "../icons/delete.svg"; import styles from "./home.module.scss"; import { DragDropContext, Droppable, Draggable, OnDragEndResponder, } from "@hello-pangea/dnd"; import { useChatStore } from "../store"; import Locale from "../locales"; import { useLocation, useNavigate } from "react-router-dom"; import { Path } from "../constant"; import { MaskAvatar } from "./mask"; import { Mask } from "../store/mask"; import { useRef, useEffect } from "react"; import { showConfirm } from "./ui-lib"; import { useMobileScreen } from "../utils"; import clsx from "clsx"; export function ChatItem(props: { onClick?: () => void; onDelete?: () => void; title: string; count: number; time: string; selected: boolean; id: string; index: number; narrow?: boolean; mask: Mask; }) { const draggableRef = useRef<HTMLDivElement | null>(null); useEffect(() => { if (props.selected && draggableRef.current) { draggableRef.current?.scrollIntoView({ block: "center", }); } }, [props.selected]); const { pathname: currentPath } = useLocation(); return ( <Draggable draggableId={`${props.id}`} index={props.index}> {(provided) => ( <div className={clsx(styles["chat-item"], { [styles["chat-item-selected"]]: props.selected && (currentPath === Path.Chat || currentPath === Path.Home), })} onClick={props.onClick} ref={(ele) => { draggableRef.current = ele; provided.innerRef(ele); }} {...provided.draggableProps} {...provided.dragHandleProps} title={`${props.title}\n${Locale.ChatItem.ChatItemCount( props.count, )}`} > {props.narrow ? ( <div className={styles["chat-item-narrow"]}> <div className={clsx(styles["chat-item-avatar"], "no-dark")}> <MaskAvatar avatar={props.mask.avatar} model={props.mask.modelConfig.model} /> </div> <div className={styles["chat-item-narrow-count"]}> {props.count} </div> </div> ) : ( <> <div className={styles["chat-item-title"]}>{props.title}</div> <div className={styles["chat-item-info"]}> <div className={styles["chat-item-count"]}> {Locale.ChatItem.ChatItemCount(props.count)} </div> <div className={styles["chat-item-date"]}>{props.time}</div> </div> </> )} <div className={styles["chat-item-delete"]} onClickCapture={(e) => { props.onDelete?.(); e.preventDefault(); e.stopPropagation(); }} > <DeleteIcon /> </div> </div> )} </Draggable> ); } export function ChatList(props: { narrow?: boolean }) { const [sessions, selectedIndex, selectSession, moveSession] = useChatStore( (state) => [ state.sessions, state.currentSessionIndex, state.selectSession, state.moveSession, ], ); const chatStore = useChatStore(); const navigate = useNavigate(); const isMobileScreen = useMobileScreen(); const onDragEnd: OnDragEndResponder = (result) => { const { destination, source } = result; if (!destination) { return; } if ( destination.droppableId === source.droppableId && destination.index === source.index ) { return; } moveSession(source.index, destination.index); }; return ( <DragDropContext onDragEnd={onDragEnd}> <Droppable droppableId="chat-list"> {(provided) => ( <div className={styles["chat-list"]} ref={provided.innerRef} {...provided.droppableProps} > {sessions.map((item, i) => ( <ChatItem title={item.topic} time={new Date(item.lastUpdate).toLocaleString()} count={item.messages.length} key={item.id} id={item.id} index={i} selected={i === selectedIndex} onClick={() => { navigate(Path.Chat); selectSession(i); }} onDelete={async () => { if ( (!props.narrow && !isMobileScreen) || (await showConfirm(Locale.Home.DeleteChat)) ) { chatStore.deleteSession(i); } }} narrow={props.narrow} mask={item.mask} /> ))} {provided.placeholder} </div> )} </Droppable> </DragDropContext> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/search-chat.tsx
app/components/search-chat.tsx
import { useState, useEffect, useRef, useCallback } from "react"; import { ErrorBoundary } from "./error"; import styles from "./mask.module.scss"; import { useNavigate } from "react-router-dom"; import { IconButton } from "./button"; import CloseIcon from "../icons/close.svg"; import EyeIcon from "../icons/eye.svg"; import Locale from "../locales"; import { Path } from "../constant"; import { useChatStore } from "../store"; type Item = { id: number; name: string; content: string; }; export function SearchChatPage() { const navigate = useNavigate(); const chatStore = useChatStore(); const sessions = chatStore.sessions; const selectSession = chatStore.selectSession; const [searchResults, setSearchResults] = useState<Item[]>([]); const previousValueRef = useRef<string>(""); const searchInputRef = useRef<HTMLInputElement>(null); const doSearch = useCallback((text: string) => { const lowerCaseText = text.toLowerCase(); const results: Item[] = []; sessions.forEach((session, index) => { const fullTextContents: string[] = []; session.messages.forEach((message) => { const content = message.content as string; if (!content.toLowerCase || content === "") return; const lowerCaseContent = content.toLowerCase(); // full text search let pos = lowerCaseContent.indexOf(lowerCaseText); while (pos !== -1) { const start = Math.max(0, pos - 35); const end = Math.min(content.length, pos + lowerCaseText.length + 35); fullTextContents.push(content.substring(start, end)); pos = lowerCaseContent.indexOf( lowerCaseText, pos + lowerCaseText.length, ); } }); if (fullTextContents.length > 0) { results.push({ id: index, name: session.topic, content: fullTextContents.join("... "), // concat content with... }); } }); // sort by length of matching content results.sort((a, b) => b.content.length - a.content.length); return results; }, []); useEffect(() => { const intervalId = setInterval(() => { if (searchInputRef.current) { const currentValue = searchInputRef.current.value; if (currentValue !== previousValueRef.current) { if (currentValue.length > 0) { const result = doSearch(currentValue); setSearchResults(result); } previousValueRef.current = currentValue; } } }, 1000); // Cleanup the interval on component unmount return () => clearInterval(intervalId); }, [doSearch]); return ( <ErrorBoundary> <div className={styles["mask-page"]}> {/* header */} <div className="window-header"> <div className="window-header-title"> <div className="window-header-main-title"> {Locale.SearchChat.Page.Title} </div> <div className="window-header-submai-title"> {Locale.SearchChat.Page.SubTitle(searchResults.length)} </div> </div> <div className="window-actions"> <div className="window-action-button"> <IconButton icon={<CloseIcon />} bordered onClick={() => navigate(-1)} /> </div> </div> </div> <div className={styles["mask-page-body"]}> <div className={styles["mask-filter"]}> {/**搜索输入框 */} <input type="text" className={styles["search-bar"]} placeholder={Locale.SearchChat.Page.Search} autoFocus ref={searchInputRef} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); const searchText = e.currentTarget.value; if (searchText.length > 0) { const result = doSearch(searchText); setSearchResults(result); } } }} /> </div> <div> {searchResults.map((item) => ( <div className={styles["mask-item"]} key={item.id} onClick={() => { navigate(Path.Chat); selectSession(item.id); }} style={{ cursor: "pointer" }} > {/** 搜索匹配的文本 */} <div className={styles["mask-header"]}> <div className={styles["mask-title"]}> <div className={styles["mask-name"]}>{item.name}</div> {item.content.slice(0, 70)} </div> </div> {/** 操作按钮 */} <div className={styles["mask-actions"]}> <IconButton icon={<EyeIcon />} text={Locale.SearchChat.Item.View} /> </div> </div> ))} </div> </div> </div> </ErrorBoundary> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/mask.tsx
app/components/mask.tsx
import { IconButton } from "./button"; import { ErrorBoundary } from "./error"; import styles from "./mask.module.scss"; import DownloadIcon from "../icons/download.svg"; import UploadIcon from "../icons/upload.svg"; import EditIcon from "../icons/edit.svg"; import AddIcon from "../icons/add.svg"; import CloseIcon from "../icons/close.svg"; import DeleteIcon from "../icons/delete.svg"; import EyeIcon from "../icons/eye.svg"; import CopyIcon from "../icons/copy.svg"; import DragIcon from "../icons/drag.svg"; import { DEFAULT_MASK_AVATAR, Mask, useMaskStore } from "../store/mask"; import { ChatMessage, createMessage, ModelConfig, ModelType, useAppConfig, useChatStore, } from "../store"; import { MultimodalContent, ROLES } from "../client/api"; import { Input, List, ListItem, Modal, Popover, Select, showConfirm, } from "./ui-lib"; import { Avatar, AvatarPicker } from "./emoji"; import Locale, { AllLangs, ALL_LANG_OPTIONS, Lang } from "../locales"; import { useNavigate } from "react-router-dom"; import chatStyle from "./chat.module.scss"; import { useState } from "react"; import { copyToClipboard, downloadAs, getMessageImages, readFromFile, } from "../utils"; import { Updater } from "../typing"; import { ModelConfigList } from "./model-config"; import { FileName, Path } from "../constant"; import { BUILTIN_MASK_STORE } from "../masks"; import { DragDropContext, Droppable, Draggable, OnDragEndResponder, } from "@hello-pangea/dnd"; import { getMessageTextContent } from "../utils"; import clsx from "clsx"; // drag and drop helper function function reorder<T>(list: T[], startIndex: number, endIndex: number): T[] { const result = [...list]; const [removed] = result.splice(startIndex, 1); result.splice(endIndex, 0, removed); return result; } export function MaskAvatar(props: { avatar: string; model?: ModelType }) { return props.avatar !== DEFAULT_MASK_AVATAR ? ( <Avatar avatar={props.avatar} /> ) : ( <Avatar model={props.model} /> ); } export function MaskConfig(props: { mask: Mask; updateMask: Updater<Mask>; extraListItems?: JSX.Element; readonly?: boolean; shouldSyncFromGlobal?: boolean; }) { const [showPicker, setShowPicker] = useState(false); const updateConfig = (updater: (config: ModelConfig) => void) => { if (props.readonly) return; const config = { ...props.mask.modelConfig }; updater(config); props.updateMask((mask) => { mask.modelConfig = config; // if user changed current session mask, it will disable auto sync mask.syncGlobalConfig = false; }); }; const copyMaskLink = () => { const maskLink = `${location.protocol}//${location.host}/#${Path.NewChat}?mask=${props.mask.id}`; copyToClipboard(maskLink); }; const globalConfig = useAppConfig(); return ( <> <ContextPrompts context={props.mask.context} updateContext={(updater) => { const context = props.mask.context.slice(); updater(context); props.updateMask((mask) => (mask.context = context)); }} /> <List> <ListItem title={Locale.Mask.Config.Avatar}> <Popover content={ <AvatarPicker onEmojiClick={(emoji) => { props.updateMask((mask) => (mask.avatar = emoji)); setShowPicker(false); }} ></AvatarPicker> } open={showPicker} onClose={() => setShowPicker(false)} > <div tabIndex={0} aria-label={Locale.Mask.Config.Avatar} onClick={() => setShowPicker(true)} style={{ cursor: "pointer" }} > <MaskAvatar avatar={props.mask.avatar} model={props.mask.modelConfig.model} /> </div> </Popover> </ListItem> <ListItem title={Locale.Mask.Config.Name}> <input aria-label={Locale.Mask.Config.Name} type="text" value={props.mask.name} onInput={(e) => props.updateMask((mask) => { mask.name = e.currentTarget.value; }) } ></input> </ListItem> <ListItem title={Locale.Mask.Config.HideContext.Title} subTitle={Locale.Mask.Config.HideContext.SubTitle} > <input aria-label={Locale.Mask.Config.HideContext.Title} type="checkbox" checked={props.mask.hideContext} onChange={(e) => { props.updateMask((mask) => { mask.hideContext = e.currentTarget.checked; }); }} ></input> </ListItem> {globalConfig.enableArtifacts && ( <ListItem title={Locale.Mask.Config.Artifacts.Title} subTitle={Locale.Mask.Config.Artifacts.SubTitle} > <input aria-label={Locale.Mask.Config.Artifacts.Title} type="checkbox" checked={props.mask.enableArtifacts !== false} onChange={(e) => { props.updateMask((mask) => { mask.enableArtifacts = e.currentTarget.checked; }); }} ></input> </ListItem> )} {globalConfig.enableCodeFold && ( <ListItem title={Locale.Mask.Config.CodeFold.Title} subTitle={Locale.Mask.Config.CodeFold.SubTitle} > <input aria-label={Locale.Mask.Config.CodeFold.Title} type="checkbox" checked={props.mask.enableCodeFold !== false} onChange={(e) => { props.updateMask((mask) => { mask.enableCodeFold = e.currentTarget.checked; }); }} ></input> </ListItem> )} {!props.shouldSyncFromGlobal ? ( <ListItem title={Locale.Mask.Config.Share.Title} subTitle={Locale.Mask.Config.Share.SubTitle} > <IconButton aria={Locale.Mask.Config.Share.Title} icon={<CopyIcon />} text={Locale.Mask.Config.Share.Action} onClick={copyMaskLink} /> </ListItem> ) : null} {props.shouldSyncFromGlobal ? ( <ListItem title={Locale.Mask.Config.Sync.Title} subTitle={Locale.Mask.Config.Sync.SubTitle} > <input aria-label={Locale.Mask.Config.Sync.Title} type="checkbox" checked={props.mask.syncGlobalConfig} onChange={async (e) => { const checked = e.currentTarget.checked; if ( checked && (await showConfirm(Locale.Mask.Config.Sync.Confirm)) ) { props.updateMask((mask) => { mask.syncGlobalConfig = checked; mask.modelConfig = { ...globalConfig.modelConfig }; }); } else if (!checked) { props.updateMask((mask) => { mask.syncGlobalConfig = checked; }); } }} ></input> </ListItem> ) : null} </List> <List> <ModelConfigList modelConfig={{ ...props.mask.modelConfig }} updateConfig={updateConfig} /> {props.extraListItems} </List> </> ); } function ContextPromptItem(props: { index: number; prompt: ChatMessage; update: (prompt: ChatMessage) => void; remove: () => void; }) { const [focusingInput, setFocusingInput] = useState(false); return ( <div className={chatStyle["context-prompt-row"]}> {!focusingInput && ( <> <div className={chatStyle["context-drag"]}> <DragIcon /> </div> <Select value={props.prompt.role} className={chatStyle["context-role"]} onChange={(e) => props.update({ ...props.prompt, role: e.target.value as any, }) } > {ROLES.map((r) => ( <option key={r} value={r}> {r} </option> ))} </Select> </> )} <Input value={getMessageTextContent(props.prompt)} type="text" className={chatStyle["context-content"]} rows={focusingInput ? 5 : 1} onFocus={() => setFocusingInput(true)} onBlur={() => { setFocusingInput(false); // If the selection is not removed when the user loses focus, some // extensions like "Translate" will always display a floating bar window?.getSelection()?.removeAllRanges(); }} onInput={(e) => props.update({ ...props.prompt, content: e.currentTarget.value as any, }) } /> {!focusingInput && ( <IconButton icon={<DeleteIcon />} className={chatStyle["context-delete-button"]} onClick={() => props.remove()} bordered /> )} </div> ); } export function ContextPrompts(props: { context: ChatMessage[]; updateContext: (updater: (context: ChatMessage[]) => void) => void; }) { const context = props.context; const addContextPrompt = (prompt: ChatMessage, i: number) => { props.updateContext((context) => context.splice(i, 0, prompt)); }; const removeContextPrompt = (i: number) => { props.updateContext((context) => context.splice(i, 1)); }; const updateContextPrompt = (i: number, prompt: ChatMessage) => { props.updateContext((context) => { const images = getMessageImages(context[i]); context[i] = prompt; if (images.length > 0) { const text = getMessageTextContent(context[i]); const newContext: MultimodalContent[] = [{ type: "text", text }]; for (const img of images) { newContext.push({ type: "image_url", image_url: { url: img } }); } context[i].content = newContext; } }); }; const onDragEnd: OnDragEndResponder = (result) => { if (!result.destination) { return; } const newContext = reorder( context, result.source.index, result.destination.index, ); props.updateContext((context) => { context.splice(0, context.length, ...newContext); }); }; return ( <> <div className={chatStyle["context-prompt"]} style={{ marginBottom: 20 }}> <DragDropContext onDragEnd={onDragEnd}> <Droppable droppableId="context-prompt-list"> {(provided) => ( <div ref={provided.innerRef} {...provided.droppableProps}> {context.map((c, i) => ( <Draggable draggableId={c.id || i.toString()} index={i} key={c.id} > {(provided) => ( <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} > <ContextPromptItem index={i} prompt={c} update={(prompt) => updateContextPrompt(i, prompt)} remove={() => removeContextPrompt(i)} /> <div className={chatStyle["context-prompt-insert"]} onClick={() => { addContextPrompt( createMessage({ role: "user", content: "", date: new Date().toLocaleString(), }), i + 1, ); }} > <AddIcon /> </div> </div> )} </Draggable> ))} {provided.placeholder} </div> )} </Droppable> </DragDropContext> {props.context.length === 0 && ( <div className={chatStyle["context-prompt-row"]}> <IconButton icon={<AddIcon />} text={Locale.Context.Add} bordered className={chatStyle["context-prompt-button"]} onClick={() => addContextPrompt( createMessage({ role: "user", content: "", date: "", }), props.context.length, ) } /> </div> )} </div> </> ); } export function MaskPage() { const navigate = useNavigate(); const maskStore = useMaskStore(); const chatStore = useChatStore(); const filterLang = maskStore.language; const allMasks = maskStore .getAll() .filter((m) => !filterLang || m.lang === filterLang); const [searchMasks, setSearchMasks] = useState<Mask[]>([]); const [searchText, setSearchText] = useState(""); const masks = searchText.length > 0 ? searchMasks : allMasks; // refactored already, now it accurate const onSearch = (text: string) => { setSearchText(text); if (text.length > 0) { const result = allMasks.filter((m) => m.name.toLowerCase().includes(text.toLowerCase()), ); setSearchMasks(result); } else { setSearchMasks(allMasks); } }; const [editingMaskId, setEditingMaskId] = useState<string | undefined>(); const editingMask = maskStore.get(editingMaskId) ?? BUILTIN_MASK_STORE.get(editingMaskId); const closeMaskModal = () => setEditingMaskId(undefined); const downloadAll = () => { downloadAs(JSON.stringify(masks.filter((v) => !v.builtin)), FileName.Masks); }; const importFromFile = () => { readFromFile().then((content) => { try { const importMasks = JSON.parse(content); if (Array.isArray(importMasks)) { for (const mask of importMasks) { if (mask.name) { maskStore.create(mask); } } return; } //if the content is a single mask. if (importMasks.name) { maskStore.create(importMasks); } } catch {} }); }; return ( <ErrorBoundary> <div className={styles["mask-page"]}> <div className="window-header"> <div className="window-header-title"> <div className="window-header-main-title"> {Locale.Mask.Page.Title} </div> <div className="window-header-submai-title"> {Locale.Mask.Page.SubTitle(allMasks.length)} </div> </div> <div className="window-actions"> <div className="window-action-button"> <IconButton icon={<DownloadIcon />} bordered onClick={downloadAll} text={Locale.UI.Export} /> </div> <div className="window-action-button"> <IconButton icon={<UploadIcon />} text={Locale.UI.Import} bordered onClick={() => importFromFile()} /> </div> <div className="window-action-button"> <IconButton icon={<CloseIcon />} bordered onClick={() => navigate(-1)} /> </div> </div> </div> <div className={styles["mask-page-body"]}> <div className={styles["mask-filter"]}> <input type="text" className={styles["search-bar"]} placeholder={Locale.Mask.Page.Search} autoFocus onInput={(e) => onSearch(e.currentTarget.value)} /> <Select className={styles["mask-filter-lang"]} value={filterLang ?? Locale.Settings.Lang.All} onChange={(e) => { const value = e.currentTarget.value; if (value === Locale.Settings.Lang.All) { maskStore.setLanguage(undefined); } else { maskStore.setLanguage(value as Lang); } }} > <option key="all" value={Locale.Settings.Lang.All}> {Locale.Settings.Lang.All} </option> {AllLangs.map((lang) => ( <option value={lang} key={lang}> {ALL_LANG_OPTIONS[lang]} </option> ))} </Select> <IconButton className={styles["mask-create"]} icon={<AddIcon />} text={Locale.Mask.Page.Create} bordered onClick={() => { const createdMask = maskStore.create(); setEditingMaskId(createdMask.id); }} /> </div> <div> {masks.map((m) => ( <div className={styles["mask-item"]} key={m.id}> <div className={styles["mask-header"]}> <div className={styles["mask-icon"]}> <MaskAvatar avatar={m.avatar} model={m.modelConfig.model} /> </div> <div className={styles["mask-title"]}> <div className={styles["mask-name"]}>{m.name}</div> <div className={clsx(styles["mask-info"], "one-line")}> {`${Locale.Mask.Item.Info(m.context.length)} / ${ ALL_LANG_OPTIONS[m.lang] } / ${m.modelConfig.model}`} </div> </div> </div> <div className={styles["mask-actions"]}> <IconButton icon={<AddIcon />} text={Locale.Mask.Item.Chat} onClick={() => { chatStore.newSession(m); navigate(Path.Chat); }} /> {m.builtin ? ( <IconButton icon={<EyeIcon />} text={Locale.Mask.Item.View} onClick={() => setEditingMaskId(m.id)} /> ) : ( <IconButton icon={<EditIcon />} text={Locale.Mask.Item.Edit} onClick={() => setEditingMaskId(m.id)} /> )} {!m.builtin && ( <IconButton icon={<DeleteIcon />} text={Locale.Mask.Item.Delete} onClick={async () => { if (await showConfirm(Locale.Mask.Item.DeleteConfirm)) { maskStore.delete(m.id); } }} /> )} </div> </div> ))} </div> </div> </div> {editingMask && ( <div className="modal-mask"> <Modal title={Locale.Mask.EditModal.Title(editingMask?.builtin)} onClose={closeMaskModal} actions={[ <IconButton icon={<DownloadIcon />} text={Locale.Mask.EditModal.Download} key="export" bordered onClick={() => downloadAs( JSON.stringify(editingMask), `${editingMask.name}.json`, ) } />, <IconButton key="copy" icon={<CopyIcon />} bordered text={Locale.Mask.EditModal.Clone} onClick={() => { navigate(Path.Masks); maskStore.create(editingMask); setEditingMaskId(undefined); }} />, ]} > <MaskConfig mask={editingMask} updateMask={(updater) => maskStore.updateMask(editingMaskId!, updater) } readonly={editingMask.builtin} /> </Modal> </div> )} </ErrorBoundary> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/settings.tsx
app/components/settings.tsx
import { useState, useEffect, useMemo } from "react"; import styles from "./settings.module.scss"; import ResetIcon from "../icons/reload.svg"; import AddIcon from "../icons/add.svg"; import CloseIcon from "../icons/close.svg"; import CopyIcon from "../icons/copy.svg"; import ClearIcon from "../icons/clear.svg"; import LoadingIcon from "../icons/three-dots.svg"; import EditIcon from "../icons/edit.svg"; import FireIcon from "../icons/fire.svg"; import EyeIcon from "../icons/eye.svg"; import DownloadIcon from "../icons/download.svg"; import UploadIcon from "../icons/upload.svg"; import ConfigIcon from "../icons/config.svg"; import ConfirmIcon from "../icons/confirm.svg"; import ConnectionIcon from "../icons/connection.svg"; import CloudSuccessIcon from "../icons/cloud-success.svg"; import CloudFailIcon from "../icons/cloud-fail.svg"; import { trackSettingsPageGuideToCPaymentClick } from "../utils/auth-settings-events"; import { Input, List, ListItem, Modal, PasswordInput, Popover, Select, showConfirm, showToast, } from "./ui-lib"; import { ModelConfigList } from "./model-config"; import { IconButton } from "./button"; import { SubmitKey, useChatStore, Theme, useUpdateStore, useAccessStore, useAppConfig, } from "../store"; import Locale, { AllLangs, ALL_LANG_OPTIONS, changeLang, getLang, } from "../locales"; import { copyToClipboard, clientUpdate, semverCompare } from "../utils"; import Link from "next/link"; import { Anthropic, Azure, Baidu, Tencent, ByteDance, Alibaba, Moonshot, XAI, Google, GoogleSafetySettingsThreshold, OPENAI_BASE_URL, Path, RELEASE_URL, STORAGE_KEY, ServiceProvider, SlotID, UPDATE_URL, Stability, Iflytek, SAAS_CHAT_URL, ChatGLM, DeepSeek, SiliconFlow, AI302, } from "../constant"; import { Prompt, SearchService, usePromptStore } from "../store/prompt"; import { ErrorBoundary } from "./error"; import { InputRange } from "./input-range"; import { useNavigate } from "react-router-dom"; import { Avatar, AvatarPicker } from "./emoji"; import { getClientConfig } from "../config/client"; import { useSyncStore } from "../store/sync"; import { nanoid } from "nanoid"; import { useMaskStore } from "../store/mask"; import { ProviderType } from "../utils/cloud"; import { TTSConfigList } from "./tts-config"; import { RealtimeConfigList } from "./realtime-chat/realtime-config"; function EditPromptModal(props: { id: string; onClose: () => void }) { const promptStore = usePromptStore(); const prompt = promptStore.get(props.id); return prompt ? ( <div className="modal-mask"> <Modal title={Locale.Settings.Prompt.EditModal.Title} onClose={props.onClose} actions={[ <IconButton key="" onClick={props.onClose} text={Locale.UI.Confirm} bordered />, ]} > <div className={styles["edit-prompt-modal"]}> <input type="text" value={prompt.title} readOnly={!prompt.isUser} className={styles["edit-prompt-title"]} onInput={(e) => promptStore.updatePrompt( props.id, (prompt) => (prompt.title = e.currentTarget.value), ) } ></input> <Input value={prompt.content} readOnly={!prompt.isUser} className={styles["edit-prompt-content"]} rows={10} onInput={(e) => promptStore.updatePrompt( props.id, (prompt) => (prompt.content = e.currentTarget.value), ) } ></Input> </div> </Modal> </div> ) : null; } function UserPromptModal(props: { onClose?: () => void }) { const promptStore = usePromptStore(); const userPrompts = promptStore.getUserPrompts(); const builtinPrompts = SearchService.builtinPrompts; const allPrompts = userPrompts.concat(builtinPrompts); const [searchInput, setSearchInput] = useState(""); const [searchPrompts, setSearchPrompts] = useState<Prompt[]>([]); const prompts = searchInput.length > 0 ? searchPrompts : allPrompts; const [editingPromptId, setEditingPromptId] = useState<string>(); useEffect(() => { if (searchInput.length > 0) { const searchResult = SearchService.search(searchInput); setSearchPrompts(searchResult); } else { setSearchPrompts([]); } }, [searchInput]); return ( <div className="modal-mask"> <Modal title={Locale.Settings.Prompt.Modal.Title} onClose={() => props.onClose?.()} actions={[ <IconButton key="add" onClick={() => { const promptId = promptStore.add({ id: nanoid(), createdAt: Date.now(), title: "Empty Prompt", content: "Empty Prompt Content", }); setEditingPromptId(promptId); }} icon={<AddIcon />} bordered text={Locale.Settings.Prompt.Modal.Add} />, ]} > <div className={styles["user-prompt-modal"]}> <input type="text" className={styles["user-prompt-search"]} placeholder={Locale.Settings.Prompt.Modal.Search} value={searchInput} onInput={(e) => setSearchInput(e.currentTarget.value)} ></input> <div className={styles["user-prompt-list"]}> {prompts.map((v, _) => ( <div className={styles["user-prompt-item"]} key={v.id ?? v.title}> <div className={styles["user-prompt-header"]}> <div className={styles["user-prompt-title"]}>{v.title}</div> <div className={styles["user-prompt-content"] + " one-line"}> {v.content} </div> </div> <div className={styles["user-prompt-buttons"]}> {v.isUser && ( <IconButton icon={<ClearIcon />} className={styles["user-prompt-button"]} onClick={() => promptStore.remove(v.id!)} /> )} {v.isUser ? ( <IconButton icon={<EditIcon />} className={styles["user-prompt-button"]} onClick={() => setEditingPromptId(v.id)} /> ) : ( <IconButton icon={<EyeIcon />} className={styles["user-prompt-button"]} onClick={() => setEditingPromptId(v.id)} /> )} <IconButton icon={<CopyIcon />} className={styles["user-prompt-button"]} onClick={() => copyToClipboard(v.content)} /> </div> </div> ))} </div> </div> </Modal> {editingPromptId !== undefined && ( <EditPromptModal id={editingPromptId!} onClose={() => setEditingPromptId(undefined)} /> )} </div> ); } function DangerItems() { const chatStore = useChatStore(); const appConfig = useAppConfig(); return ( <List> <ListItem title={Locale.Settings.Danger.Reset.Title} subTitle={Locale.Settings.Danger.Reset.SubTitle} > <IconButton aria={Locale.Settings.Danger.Reset.Title} text={Locale.Settings.Danger.Reset.Action} onClick={async () => { if (await showConfirm(Locale.Settings.Danger.Reset.Confirm)) { appConfig.reset(); } }} type="danger" /> </ListItem> <ListItem title={Locale.Settings.Danger.Clear.Title} subTitle={Locale.Settings.Danger.Clear.SubTitle} > <IconButton aria={Locale.Settings.Danger.Clear.Title} text={Locale.Settings.Danger.Clear.Action} onClick={async () => { if (await showConfirm(Locale.Settings.Danger.Clear.Confirm)) { chatStore.clearAllData(); } }} type="danger" /> </ListItem> </List> ); } function CheckButton() { const syncStore = useSyncStore(); const couldCheck = useMemo(() => { return syncStore.cloudSync(); }, [syncStore]); const [checkState, setCheckState] = useState< "none" | "checking" | "success" | "failed" >("none"); async function check() { setCheckState("checking"); const valid = await syncStore.check(); setCheckState(valid ? "success" : "failed"); } if (!couldCheck) return null; return ( <IconButton text={Locale.Settings.Sync.Config.Modal.Check} bordered onClick={check} icon={ checkState === "none" ? ( <ConnectionIcon /> ) : checkState === "checking" ? ( <LoadingIcon /> ) : checkState === "success" ? ( <CloudSuccessIcon /> ) : checkState === "failed" ? ( <CloudFailIcon /> ) : ( <ConnectionIcon /> ) } ></IconButton> ); } function SyncConfigModal(props: { onClose?: () => void }) { const syncStore = useSyncStore(); return ( <div className="modal-mask"> <Modal title={Locale.Settings.Sync.Config.Modal.Title} onClose={() => props.onClose?.()} actions={[ <CheckButton key="check" />, <IconButton key="confirm" onClick={props.onClose} icon={<ConfirmIcon />} bordered text={Locale.UI.Confirm} />, ]} > <List> <ListItem title={Locale.Settings.Sync.Config.SyncType.Title} subTitle={Locale.Settings.Sync.Config.SyncType.SubTitle} > <select value={syncStore.provider} onChange={(e) => { syncStore.update( (config) => (config.provider = e.target.value as ProviderType), ); }} > {Object.entries(ProviderType).map(([k, v]) => ( <option value={v} key={k}> {k} </option> ))} </select> </ListItem> <ListItem title={Locale.Settings.Sync.Config.Proxy.Title} subTitle={Locale.Settings.Sync.Config.Proxy.SubTitle} > <input type="checkbox" checked={syncStore.useProxy} onChange={(e) => { syncStore.update( (config) => (config.useProxy = e.currentTarget.checked), ); }} ></input> </ListItem> {syncStore.useProxy ? ( <ListItem title={Locale.Settings.Sync.Config.ProxyUrl.Title} subTitle={Locale.Settings.Sync.Config.ProxyUrl.SubTitle} > <input type="text" value={syncStore.proxyUrl} onChange={(e) => { syncStore.update( (config) => (config.proxyUrl = e.currentTarget.value), ); }} ></input> </ListItem> ) : null} </List> {syncStore.provider === ProviderType.WebDAV && ( <> <List> <ListItem title={Locale.Settings.Sync.Config.WebDav.Endpoint}> <input type="text" value={syncStore.webdav.endpoint} onChange={(e) => { syncStore.update( (config) => (config.webdav.endpoint = e.currentTarget.value), ); }} ></input> </ListItem> <ListItem title={Locale.Settings.Sync.Config.WebDav.UserName}> <input type="text" value={syncStore.webdav.username} onChange={(e) => { syncStore.update( (config) => (config.webdav.username = e.currentTarget.value), ); }} ></input> </ListItem> <ListItem title={Locale.Settings.Sync.Config.WebDav.Password}> <PasswordInput value={syncStore.webdav.password} onChange={(e) => { syncStore.update( (config) => (config.webdav.password = e.currentTarget.value), ); }} ></PasswordInput> </ListItem> </List> </> )} {syncStore.provider === ProviderType.UpStash && ( <List> <ListItem title={Locale.Settings.Sync.Config.UpStash.Endpoint}> <input type="text" value={syncStore.upstash.endpoint} onChange={(e) => { syncStore.update( (config) => (config.upstash.endpoint = e.currentTarget.value), ); }} ></input> </ListItem> <ListItem title={Locale.Settings.Sync.Config.UpStash.UserName}> <input type="text" value={syncStore.upstash.username} placeholder={STORAGE_KEY} onChange={(e) => { syncStore.update( (config) => (config.upstash.username = e.currentTarget.value), ); }} ></input> </ListItem> <ListItem title={Locale.Settings.Sync.Config.UpStash.Password}> <PasswordInput value={syncStore.upstash.apiKey} onChange={(e) => { syncStore.update( (config) => (config.upstash.apiKey = e.currentTarget.value), ); }} ></PasswordInput> </ListItem> </List> )} </Modal> </div> ); } function SyncItems() { const syncStore = useSyncStore(); const chatStore = useChatStore(); const promptStore = usePromptStore(); const maskStore = useMaskStore(); const couldSync = useMemo(() => { return syncStore.cloudSync(); }, [syncStore]); const [showSyncConfigModal, setShowSyncConfigModal] = useState(false); const stateOverview = useMemo(() => { const sessions = chatStore.sessions; const messageCount = sessions.reduce((p, c) => p + c.messages.length, 0); return { chat: sessions.length, message: messageCount, prompt: Object.keys(promptStore.prompts).length, mask: Object.keys(maskStore.masks).length, }; }, [chatStore.sessions, maskStore.masks, promptStore.prompts]); return ( <> <List> <ListItem title={Locale.Settings.Sync.CloudState} subTitle={ syncStore.lastProvider ? `${new Date(syncStore.lastSyncTime).toLocaleString()} [${ syncStore.lastProvider }]` : Locale.Settings.Sync.NotSyncYet } > <div style={{ display: "flex" }}> <IconButton aria={Locale.Settings.Sync.CloudState + Locale.UI.Config} icon={<ConfigIcon />} text={Locale.UI.Config} onClick={() => { setShowSyncConfigModal(true); }} /> {couldSync && ( <IconButton icon={<ResetIcon />} text={Locale.UI.Sync} onClick={async () => { try { await syncStore.sync(); showToast(Locale.Settings.Sync.Success); } catch (e) { showToast(Locale.Settings.Sync.Fail); console.error("[Sync]", e); } }} /> )} </div> </ListItem> <ListItem title={Locale.Settings.Sync.LocalState} subTitle={Locale.Settings.Sync.Overview(stateOverview)} > <div style={{ display: "flex" }}> <IconButton aria={Locale.Settings.Sync.LocalState + Locale.UI.Export} icon={<UploadIcon />} text={Locale.UI.Export} onClick={() => { syncStore.export(); }} /> <IconButton aria={Locale.Settings.Sync.LocalState + Locale.UI.Import} icon={<DownloadIcon />} text={Locale.UI.Import} onClick={() => { syncStore.import(); }} /> </div> </ListItem> </List> {showSyncConfigModal && ( <SyncConfigModal onClose={() => setShowSyncConfigModal(false)} /> )} </> ); } export function Settings() { const navigate = useNavigate(); const [showEmojiPicker, setShowEmojiPicker] = useState(false); const config = useAppConfig(); const updateConfig = config.update; const updateStore = useUpdateStore(); const [checkingUpdate, setCheckingUpdate] = useState(false); const currentVersion = updateStore.formatVersion(updateStore.version); const remoteId = updateStore.formatVersion(updateStore.remoteVersion); const hasNewVersion = semverCompare(currentVersion, remoteId) === -1; const updateUrl = getClientConfig()?.isApp ? RELEASE_URL : UPDATE_URL; function checkUpdate(force = false) { setCheckingUpdate(true); updateStore.getLatestVersion(force).then(() => { setCheckingUpdate(false); }); console.log("[Update] local version ", updateStore.version); console.log("[Update] remote version ", updateStore.remoteVersion); } const accessStore = useAccessStore(); const shouldHideBalanceQuery = useMemo(() => { const isOpenAiUrl = accessStore.openaiUrl.includes(OPENAI_BASE_URL); return ( accessStore.hideBalanceQuery || isOpenAiUrl || accessStore.provider === ServiceProvider.Azure ); }, [ accessStore.hideBalanceQuery, accessStore.openaiUrl, accessStore.provider, ]); const usage = { used: updateStore.used, subscription: updateStore.subscription, }; const [loadingUsage, setLoadingUsage] = useState(false); function checkUsage(force = false) { if (shouldHideBalanceQuery) { return; } setLoadingUsage(true); updateStore.updateUsage(force).finally(() => { setLoadingUsage(false); }); } const enabledAccessControl = useMemo( () => accessStore.enabledAccessControl(), // eslint-disable-next-line react-hooks/exhaustive-deps [], ); const promptStore = usePromptStore(); const builtinCount = SearchService.count.builtin; const customCount = promptStore.getUserPrompts().length ?? 0; const [shouldShowPromptModal, setShowPromptModal] = useState(false); const showUsage = accessStore.isAuthorized(); useEffect(() => { // checks per minutes checkUpdate(); showUsage && checkUsage(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { const keydownEvent = (e: KeyboardEvent) => { if (e.key === "Escape") { navigate(Path.Home); } }; if (clientConfig?.isApp) { // Force to set custom endpoint to true if it's app accessStore.update((state) => { state.useCustomConfig = true; }); } document.addEventListener("keydown", keydownEvent); return () => { document.removeEventListener("keydown", keydownEvent); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const clientConfig = useMemo(() => getClientConfig(), []); const showAccessCode = enabledAccessControl && !clientConfig?.isApp; const accessCodeComponent = showAccessCode && ( <ListItem title={Locale.Settings.Access.AccessCode.Title} subTitle={Locale.Settings.Access.AccessCode.SubTitle} > <PasswordInput value={accessStore.accessCode} type="text" placeholder={Locale.Settings.Access.AccessCode.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.accessCode = e.currentTarget.value), ); }} /> </ListItem> ); const saasStartComponent = ( <ListItem className={styles["subtitle-button"]} title={ Locale.Settings.Access.SaasStart.Title + `${Locale.Settings.Access.SaasStart.Label}` } subTitle={Locale.Settings.Access.SaasStart.SubTitle} > <IconButton aria={ Locale.Settings.Access.SaasStart.Title + Locale.Settings.Access.SaasStart.ChatNow } icon={<FireIcon />} type={"primary"} text={Locale.Settings.Access.SaasStart.ChatNow} onClick={() => { trackSettingsPageGuideToCPaymentClick(); window.location.href = SAAS_CHAT_URL; }} /> </ListItem> ); const useCustomConfigComponent = // Conditionally render the following ListItem based on clientConfig.isApp !clientConfig?.isApp && ( // only show if isApp is false <ListItem title={Locale.Settings.Access.CustomEndpoint.Title} subTitle={Locale.Settings.Access.CustomEndpoint.SubTitle} > <input aria-label={Locale.Settings.Access.CustomEndpoint.Title} type="checkbox" checked={accessStore.useCustomConfig} onChange={(e) => accessStore.update( (access) => (access.useCustomConfig = e.currentTarget.checked), ) } ></input> </ListItem> ); const openAIConfigComponent = accessStore.provider === ServiceProvider.OpenAI && ( <> <ListItem title={Locale.Settings.Access.OpenAI.Endpoint.Title} subTitle={Locale.Settings.Access.OpenAI.Endpoint.SubTitle} > <input aria-label={Locale.Settings.Access.OpenAI.Endpoint.Title} type="text" value={accessStore.openaiUrl} placeholder={OPENAI_BASE_URL} onChange={(e) => accessStore.update( (access) => (access.openaiUrl = e.currentTarget.value), ) } ></input> </ListItem> <ListItem title={Locale.Settings.Access.OpenAI.ApiKey.Title} subTitle={Locale.Settings.Access.OpenAI.ApiKey.SubTitle} > <PasswordInput aria={Locale.Settings.ShowPassword} aria-label={Locale.Settings.Access.OpenAI.ApiKey.Title} value={accessStore.openaiApiKey} type="text" placeholder={Locale.Settings.Access.OpenAI.ApiKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.openaiApiKey = e.currentTarget.value), ); }} /> </ListItem> </> ); const azureConfigComponent = accessStore.provider === ServiceProvider.Azure && ( <> <ListItem title={Locale.Settings.Access.Azure.Endpoint.Title} subTitle={ Locale.Settings.Access.Azure.Endpoint.SubTitle + Azure.ExampleEndpoint } > <input aria-label={Locale.Settings.Access.Azure.Endpoint.Title} type="text" value={accessStore.azureUrl} placeholder={Azure.ExampleEndpoint} onChange={(e) => accessStore.update( (access) => (access.azureUrl = e.currentTarget.value), ) } ></input> </ListItem> <ListItem title={Locale.Settings.Access.Azure.ApiKey.Title} subTitle={Locale.Settings.Access.Azure.ApiKey.SubTitle} > <PasswordInput aria-label={Locale.Settings.Access.Azure.ApiKey.Title} value={accessStore.azureApiKey} type="text" placeholder={Locale.Settings.Access.Azure.ApiKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.azureApiKey = e.currentTarget.value), ); }} /> </ListItem> <ListItem title={Locale.Settings.Access.Azure.ApiVerion.Title} subTitle={Locale.Settings.Access.Azure.ApiVerion.SubTitle} > <input aria-label={Locale.Settings.Access.Azure.ApiVerion.Title} type="text" value={accessStore.azureApiVersion} placeholder="2023-08-01-preview" onChange={(e) => accessStore.update( (access) => (access.azureApiVersion = e.currentTarget.value), ) } ></input> </ListItem> </> ); const googleConfigComponent = accessStore.provider === ServiceProvider.Google && ( <> <ListItem title={Locale.Settings.Access.Google.Endpoint.Title} subTitle={ Locale.Settings.Access.Google.Endpoint.SubTitle + Google.ExampleEndpoint } > <input aria-label={Locale.Settings.Access.Google.Endpoint.Title} type="text" value={accessStore.googleUrl} placeholder={Google.ExampleEndpoint} onChange={(e) => accessStore.update( (access) => (access.googleUrl = e.currentTarget.value), ) } ></input> </ListItem> <ListItem title={Locale.Settings.Access.Google.ApiKey.Title} subTitle={Locale.Settings.Access.Google.ApiKey.SubTitle} > <PasswordInput aria-label={Locale.Settings.Access.Google.ApiKey.Title} value={accessStore.googleApiKey} type="text" placeholder={Locale.Settings.Access.Google.ApiKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.googleApiKey = e.currentTarget.value), ); }} /> </ListItem> <ListItem title={Locale.Settings.Access.Google.ApiVersion.Title} subTitle={Locale.Settings.Access.Google.ApiVersion.SubTitle} > <input aria-label={Locale.Settings.Access.Google.ApiVersion.Title} type="text" value={accessStore.googleApiVersion} placeholder="2023-08-01-preview" onChange={(e) => accessStore.update( (access) => (access.googleApiVersion = e.currentTarget.value), ) } ></input> </ListItem> <ListItem title={Locale.Settings.Access.Google.GoogleSafetySettings.Title} subTitle={Locale.Settings.Access.Google.GoogleSafetySettings.SubTitle} > <Select aria-label={Locale.Settings.Access.Google.GoogleSafetySettings.Title} value={accessStore.googleSafetySettings} onChange={(e) => { accessStore.update( (access) => (access.googleSafetySettings = e.target .value as GoogleSafetySettingsThreshold), ); }} > {Object.entries(GoogleSafetySettingsThreshold).map(([k, v]) => ( <option value={v} key={k}> {k} </option> ))} </Select> </ListItem> </> ); const anthropicConfigComponent = accessStore.provider === ServiceProvider.Anthropic && ( <> <ListItem title={Locale.Settings.Access.Anthropic.Endpoint.Title} subTitle={ Locale.Settings.Access.Anthropic.Endpoint.SubTitle + Anthropic.ExampleEndpoint } > <input aria-label={Locale.Settings.Access.Anthropic.Endpoint.Title} type="text" value={accessStore.anthropicUrl} placeholder={Anthropic.ExampleEndpoint} onChange={(e) => accessStore.update( (access) => (access.anthropicUrl = e.currentTarget.value), ) } ></input> </ListItem> <ListItem title={Locale.Settings.Access.Anthropic.ApiKey.Title} subTitle={Locale.Settings.Access.Anthropic.ApiKey.SubTitle} > <PasswordInput aria-label={Locale.Settings.Access.Anthropic.ApiKey.Title} value={accessStore.anthropicApiKey} type="text" placeholder={Locale.Settings.Access.Anthropic.ApiKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.anthropicApiKey = e.currentTarget.value), ); }} /> </ListItem> <ListItem title={Locale.Settings.Access.Anthropic.ApiVerion.Title} subTitle={Locale.Settings.Access.Anthropic.ApiVerion.SubTitle} > <input aria-label={Locale.Settings.Access.Anthropic.ApiVerion.Title} type="text" value={accessStore.anthropicApiVersion} placeholder={Anthropic.Vision} onChange={(e) => accessStore.update( (access) => (access.anthropicApiVersion = e.currentTarget.value), ) } ></input> </ListItem> </> ); const baiduConfigComponent = accessStore.provider === ServiceProvider.Baidu && ( <> <ListItem title={Locale.Settings.Access.Baidu.Endpoint.Title} subTitle={Locale.Settings.Access.Baidu.Endpoint.SubTitle} > <input aria-label={Locale.Settings.Access.Baidu.Endpoint.Title} type="text" value={accessStore.baiduUrl} placeholder={Baidu.ExampleEndpoint} onChange={(e) => accessStore.update( (access) => (access.baiduUrl = e.currentTarget.value), ) } ></input> </ListItem> <ListItem title={Locale.Settings.Access.Baidu.ApiKey.Title} subTitle={Locale.Settings.Access.Baidu.ApiKey.SubTitle} > <PasswordInput aria-label={Locale.Settings.Access.Baidu.ApiKey.Title} value={accessStore.baiduApiKey} type="text" placeholder={Locale.Settings.Access.Baidu.ApiKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.baiduApiKey = e.currentTarget.value), ); }} /> </ListItem> <ListItem title={Locale.Settings.Access.Baidu.SecretKey.Title} subTitle={Locale.Settings.Access.Baidu.SecretKey.SubTitle} > <PasswordInput aria-label={Locale.Settings.Access.Baidu.SecretKey.Title} value={accessStore.baiduSecretKey} type="text" placeholder={Locale.Settings.Access.Baidu.SecretKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.baiduSecretKey = e.currentTarget.value), ); }} /> </ListItem> </> ); const tencentConfigComponent = accessStore.provider === ServiceProvider.Tencent && ( <> <ListItem title={Locale.Settings.Access.Tencent.Endpoint.Title} subTitle={Locale.Settings.Access.Tencent.Endpoint.SubTitle} > <input aria-label={Locale.Settings.Access.Tencent.Endpoint.Title} type="text" value={accessStore.tencentUrl} placeholder={Tencent.ExampleEndpoint} onChange={(e) => accessStore.update( (access) => (access.tencentUrl = e.currentTarget.value), ) } ></input> </ListItem> <ListItem title={Locale.Settings.Access.Tencent.ApiKey.Title} subTitle={Locale.Settings.Access.Tencent.ApiKey.SubTitle} > <PasswordInput aria-label={Locale.Settings.Access.Tencent.ApiKey.Title} value={accessStore.tencentSecretId} type="text" placeholder={Locale.Settings.Access.Tencent.ApiKey.Placeholder} onChange={(e) => { accessStore.update( (access) => (access.tencentSecretId = e.currentTarget.value),
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
true
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/new-chat.tsx
app/components/new-chat.tsx
import { useEffect, useRef, useState } from "react"; import { Path, SlotID } from "../constant"; import { IconButton } from "./button"; import { EmojiAvatar } from "./emoji"; import styles from "./new-chat.module.scss"; import LeftIcon from "../icons/left.svg"; import LightningIcon from "../icons/lightning.svg"; import EyeIcon from "../icons/eye.svg"; import { useLocation, useNavigate } from "react-router-dom"; import { Mask, useMaskStore } from "../store/mask"; import Locale from "../locales"; import { useAppConfig, useChatStore } from "../store"; import { MaskAvatar } from "./mask"; import { useCommand } from "../command"; import { showConfirm } from "./ui-lib"; import { BUILTIN_MASK_STORE } from "../masks"; import clsx from "clsx"; function MaskItem(props: { mask: Mask; onClick?: () => void }) { return ( <div className={styles["mask"]} onClick={props.onClick}> <MaskAvatar avatar={props.mask.avatar} model={props.mask.modelConfig.model} /> <div className={clsx(styles["mask-name"], "one-line")}> {props.mask.name} </div> </div> ); } function useMaskGroup(masks: Mask[]) { const [groups, setGroups] = useState<Mask[][]>([]); useEffect(() => { const computeGroup = () => { const appBody = document.getElementById(SlotID.AppBody); if (!appBody || masks.length === 0) return; const rect = appBody.getBoundingClientRect(); const maxWidth = rect.width; const maxHeight = rect.height * 0.6; const maskItemWidth = 120; const maskItemHeight = 50; const randomMask = () => masks[Math.floor(Math.random() * masks.length)]; let maskIndex = 0; const nextMask = () => masks[maskIndex++ % masks.length]; const rows = Math.ceil(maxHeight / maskItemHeight); const cols = Math.ceil(maxWidth / maskItemWidth); const newGroups = new Array(rows) .fill(0) .map((_, _i) => new Array(cols) .fill(0) .map((_, j) => (j < 1 || j > cols - 2 ? randomMask() : nextMask())), ); setGroups(newGroups); }; computeGroup(); window.addEventListener("resize", computeGroup); return () => window.removeEventListener("resize", computeGroup); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return groups; } export function NewChat() { const chatStore = useChatStore(); const maskStore = useMaskStore(); const masks = maskStore.getAll(); const groups = useMaskGroup(masks); const navigate = useNavigate(); const config = useAppConfig(); const maskRef = useRef<HTMLDivElement>(null); const { state } = useLocation(); const startChat = (mask?: Mask) => { setTimeout(() => { chatStore.newSession(mask); navigate(Path.Chat); }, 10); }; useCommand({ mask: (id) => { try { const mask = maskStore.get(id) ?? BUILTIN_MASK_STORE.get(id); startChat(mask ?? undefined); } catch { console.error("[New Chat] failed to create chat from mask id=", id); } }, }); useEffect(() => { if (maskRef.current) { maskRef.current.scrollLeft = (maskRef.current.scrollWidth - maskRef.current.clientWidth) / 2; } }, [groups]); return ( <div className={styles["new-chat"]}> <div className={styles["mask-header"]}> <IconButton icon={<LeftIcon />} text={Locale.NewChat.Return} onClick={() => navigate(Path.Home)} ></IconButton> {!state?.fromHome && ( <IconButton text={Locale.NewChat.NotShow} onClick={async () => { if (await showConfirm(Locale.NewChat.ConfirmNoShow)) { startChat(); config.update( (config) => (config.dontShowMaskSplashScreen = true), ); } }} ></IconButton> )} </div> <div className={styles["mask-cards"]}> <div className={styles["mask-card"]}> <EmojiAvatar avatar="1f606" size={24} /> </div> <div className={styles["mask-card"]}> <EmojiAvatar avatar="1f916" size={24} /> </div> <div className={styles["mask-card"]}> <EmojiAvatar avatar="1f479" size={24} /> </div> </div> <div className={styles["title"]}>{Locale.NewChat.Title}</div> <div className={styles["sub-title"]}>{Locale.NewChat.SubTitle}</div> <div className={styles["actions"]}> <IconButton text={Locale.NewChat.More} onClick={() => navigate(Path.Masks)} icon={<EyeIcon />} bordered shadow /> <IconButton text={Locale.NewChat.Skip} onClick={() => startChat()} icon={<LightningIcon />} type="primary" shadow className={styles["skip"]} /> </div> <div className={styles["masks"]} ref={maskRef}> {groups.map((masks, i) => ( <div key={i} className={styles["mask-row"]}> {masks.map((mask, index) => ( <MaskItem key={index} mask={mask} onClick={() => startChat(mask)} /> ))} </div> ))} </div> </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/chat.tsx
app/components/chat.tsx
import { useDebouncedCallback } from "use-debounce"; import React, { Fragment, RefObject, useCallback, useEffect, useMemo, useRef, useState, } from "react"; import SendWhiteIcon from "../icons/send-white.svg"; import BrainIcon from "../icons/brain.svg"; import RenameIcon from "../icons/rename.svg"; import EditIcon from "../icons/rename.svg"; import ExportIcon from "../icons/share.svg"; import ReturnIcon from "../icons/return.svg"; import CopyIcon from "../icons/copy.svg"; import SpeakIcon from "../icons/speak.svg"; import SpeakStopIcon from "../icons/speak-stop.svg"; import LoadingIcon from "../icons/three-dots.svg"; import LoadingButtonIcon from "../icons/loading.svg"; import PromptIcon from "../icons/prompt.svg"; import MaskIcon from "../icons/mask.svg"; import MaxIcon from "../icons/max.svg"; import MinIcon from "../icons/min.svg"; import ResetIcon from "../icons/reload.svg"; import ReloadIcon from "../icons/reload.svg"; import BreakIcon from "../icons/break.svg"; import SettingsIcon from "../icons/chat-settings.svg"; import DeleteIcon from "../icons/clear.svg"; import PinIcon from "../icons/pin.svg"; import ConfirmIcon from "../icons/confirm.svg"; import CloseIcon from "../icons/close.svg"; import CancelIcon from "../icons/cancel.svg"; import ImageIcon from "../icons/image.svg"; import LightIcon from "../icons/light.svg"; import DarkIcon from "../icons/dark.svg"; import AutoIcon from "../icons/auto.svg"; import BottomIcon from "../icons/bottom.svg"; import StopIcon from "../icons/pause.svg"; import RobotIcon from "../icons/robot.svg"; import SizeIcon from "../icons/size.svg"; import QualityIcon from "../icons/hd.svg"; import StyleIcon from "../icons/palette.svg"; import PluginIcon from "../icons/plugin.svg"; import ShortcutkeyIcon from "../icons/shortcutkey.svg"; import McpToolIcon from "../icons/tool.svg"; import HeadphoneIcon from "../icons/headphone.svg"; import { BOT_HELLO, ChatMessage, createMessage, DEFAULT_TOPIC, ModelType, SubmitKey, Theme, useAccessStore, useAppConfig, useChatStore, usePluginStore, } from "../store"; import { autoGrowTextArea, copyToClipboard, getMessageImages, getMessageTextContent, isDalle3, isVisionModel, safeLocalStorage, getModelSizes, supportsCustomSize, useMobileScreen, selectOrCopy, showPlugins, } from "../utils"; import { uploadImage as uploadImageRemote } from "@/app/utils/chat"; import dynamic from "next/dynamic"; import { ChatControllerPool } from "../client/controller"; import { DalleQuality, DalleStyle, ModelSize } from "../typing"; import { Prompt, usePromptStore } from "../store/prompt"; import Locale from "../locales"; import { IconButton } from "./button"; import styles from "./chat.module.scss"; import { List, ListItem, Modal, Selector, showConfirm, showPrompt, showToast, } from "./ui-lib"; import { useNavigate } from "react-router-dom"; import { CHAT_PAGE_SIZE, DEFAULT_TTS_ENGINE, ModelProvider, Path, REQUEST_TIMEOUT_MS, ServiceProvider, UNFINISHED_INPUT, } from "../constant"; import { Avatar } from "./emoji"; import { ContextPrompts, MaskAvatar, MaskConfig } from "./mask"; import { useMaskStore } from "../store/mask"; import { ChatCommandPrefix, useChatCommand, useCommand } from "../command"; import { prettyObject } from "../utils/format"; import { ExportMessageModal } from "./exporter"; import { getClientConfig } from "../config/client"; import { useAllModels } from "../utils/hooks"; import { ClientApi, MultimodalContent } from "../client/api"; import { createTTSPlayer } from "../utils/audio"; import { MsEdgeTTS, OUTPUT_FORMAT } from "../utils/ms_edge_tts"; import { isEmpty } from "lodash-es"; import { getModelProvider } from "../utils/model"; import { RealtimeChat } from "@/app/components/realtime-chat"; import clsx from "clsx"; import { getAvailableClientsCount, isMcpEnabled } from "../mcp/actions"; const localStorage = safeLocalStorage(); const ttsPlayer = createTTSPlayer(); const Markdown = dynamic(async () => (await import("./markdown")).Markdown, { loading: () => <LoadingIcon />, }); const MCPAction = () => { const navigate = useNavigate(); const [count, setCount] = useState<number>(0); const [mcpEnabled, setMcpEnabled] = useState(false); useEffect(() => { const checkMcpStatus = async () => { const enabled = await isMcpEnabled(); setMcpEnabled(enabled); if (enabled) { const count = await getAvailableClientsCount(); setCount(count); } }; checkMcpStatus(); }, []); if (!mcpEnabled) return null; return ( <ChatAction onClick={() => navigate(Path.McpMarket)} text={`MCP${count ? ` (${count})` : ""}`} icon={<McpToolIcon />} /> ); }; export function SessionConfigModel(props: { onClose: () => void }) { const chatStore = useChatStore(); const session = chatStore.currentSession(); const maskStore = useMaskStore(); const navigate = useNavigate(); return ( <div className="modal-mask"> <Modal title={Locale.Context.Edit} onClose={() => props.onClose()} actions={[ <IconButton key="reset" icon={<ResetIcon />} bordered text={Locale.Chat.Config.Reset} onClick={async () => { if (await showConfirm(Locale.Memory.ResetConfirm)) { chatStore.updateTargetSession( session, (session) => (session.memoryPrompt = ""), ); } }} />, <IconButton key="copy" icon={<CopyIcon />} bordered text={Locale.Chat.Config.SaveAs} onClick={() => { navigate(Path.Masks); setTimeout(() => { maskStore.create(session.mask); }, 500); }} />, ]} > <MaskConfig mask={session.mask} updateMask={(updater) => { const mask = { ...session.mask }; updater(mask); chatStore.updateTargetSession( session, (session) => (session.mask = mask), ); }} shouldSyncFromGlobal extraListItems={ session.mask.modelConfig.sendMemory ? ( <ListItem className="copyable" title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`} subTitle={session.memoryPrompt || Locale.Memory.EmptyContent} ></ListItem> ) : ( <></> ) } ></MaskConfig> </Modal> </div> ); } function PromptToast(props: { showToast?: boolean; showModal?: boolean; setShowModal: (_: boolean) => void; }) { const chatStore = useChatStore(); const session = chatStore.currentSession(); const context = session.mask.context; return ( <div className={styles["prompt-toast"]} key="prompt-toast"> {props.showToast && context.length > 0 && ( <div className={clsx(styles["prompt-toast-inner"], "clickable")} role="button" onClick={() => props.setShowModal(true)} > <BrainIcon /> <span className={styles["prompt-toast-content"]}> {Locale.Context.Toast(context.length)} </span> </div> )} {props.showModal && ( <SessionConfigModel onClose={() => props.setShowModal(false)} /> )} </div> ); } function useSubmitHandler() { const config = useAppConfig(); const submitKey = config.submitKey; const isComposing = useRef(false); useEffect(() => { const onCompositionStart = () => { isComposing.current = true; }; const onCompositionEnd = () => { isComposing.current = false; }; window.addEventListener("compositionstart", onCompositionStart); window.addEventListener("compositionend", onCompositionEnd); return () => { window.removeEventListener("compositionstart", onCompositionStart); window.removeEventListener("compositionend", onCompositionEnd); }; }, []); const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { // Fix Chinese input method "Enter" on Safari if (e.keyCode == 229) return false; if (e.key !== "Enter") return false; if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current)) return false; return ( (config.submitKey === SubmitKey.AltEnter && e.altKey) || (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) || (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) || (config.submitKey === SubmitKey.MetaEnter && e.metaKey) || (config.submitKey === SubmitKey.Enter && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) ); }; return { submitKey, shouldSubmit, }; } export type RenderPrompt = Pick<Prompt, "title" | "content">; export function PromptHints(props: { prompts: RenderPrompt[]; onPromptSelect: (prompt: RenderPrompt) => void; }) { const noPrompts = props.prompts.length === 0; const [selectIndex, setSelectIndex] = useState(0); const selectedRef = useRef<HTMLDivElement>(null); useEffect(() => { setSelectIndex(0); }, [props.prompts.length]); useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) { return; } // arrow up / down to select prompt const changeIndex = (delta: number) => { e.stopPropagation(); e.preventDefault(); const nextIndex = Math.max( 0, Math.min(props.prompts.length - 1, selectIndex + delta), ); setSelectIndex(nextIndex); selectedRef.current?.scrollIntoView({ block: "center", }); }; if (e.key === "ArrowUp") { changeIndex(1); } else if (e.key === "ArrowDown") { changeIndex(-1); } else if (e.key === "Enter") { const selectedPrompt = props.prompts.at(selectIndex); if (selectedPrompt) { props.onPromptSelect(selectedPrompt); } } }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); // eslint-disable-next-line react-hooks/exhaustive-deps }, [props.prompts.length, selectIndex]); if (noPrompts) return null; return ( <div className={styles["prompt-hints"]}> {props.prompts.map((prompt, i) => ( <div ref={i === selectIndex ? selectedRef : null} className={clsx(styles["prompt-hint"], { [styles["prompt-hint-selected"]]: i === selectIndex, })} key={prompt.title + i.toString()} onClick={() => props.onPromptSelect(prompt)} onMouseEnter={() => setSelectIndex(i)} > <div className={styles["hint-title"]}>{prompt.title}</div> <div className={styles["hint-content"]}>{prompt.content}</div> </div> ))} </div> ); } function ClearContextDivider() { const chatStore = useChatStore(); const session = chatStore.currentSession(); return ( <div className={styles["clear-context"]} onClick={() => chatStore.updateTargetSession( session, (session) => (session.clearContextIndex = undefined), ) } > <div className={styles["clear-context-tips"]}>{Locale.Context.Clear}</div> <div className={styles["clear-context-revert-btn"]}> {Locale.Context.Revert} </div> </div> ); } export function ChatAction(props: { text: string; icon: JSX.Element; onClick: () => void; }) { const iconRef = useRef<HTMLDivElement>(null); const textRef = useRef<HTMLDivElement>(null); const [width, setWidth] = useState({ full: 16, icon: 16, }); function updateWidth() { if (!iconRef.current || !textRef.current) return; const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width; const textWidth = getWidth(textRef.current); const iconWidth = getWidth(iconRef.current); setWidth({ full: textWidth + iconWidth, icon: iconWidth, }); } return ( <div className={clsx(styles["chat-input-action"], "clickable")} onClick={() => { props.onClick(); setTimeout(updateWidth, 1); }} onMouseEnter={updateWidth} onTouchStart={updateWidth} style={ { "--icon-width": `${width.icon}px`, "--full-width": `${width.full}px`, } as React.CSSProperties } > <div ref={iconRef} className={styles["icon"]}> {props.icon} </div> <div className={styles["text"]} ref={textRef}> {props.text} </div> </div> ); } function useScrollToBottom( scrollRef: RefObject<HTMLDivElement>, detach: boolean = false, messages: ChatMessage[], ) { // for auto-scroll const [autoScroll, setAutoScroll] = useState(true); const scrollDomToBottom = useCallback(() => { const dom = scrollRef.current; if (dom) { requestAnimationFrame(() => { setAutoScroll(true); dom.scrollTo(0, dom.scrollHeight); }); } }, [scrollRef]); // auto scroll useEffect(() => { if (autoScroll && !detach) { scrollDomToBottom(); } }); // auto scroll when messages length changes const lastMessagesLength = useRef(messages.length); useEffect(() => { if (messages.length > lastMessagesLength.current && !detach) { scrollDomToBottom(); } lastMessagesLength.current = messages.length; }, [messages.length, detach, scrollDomToBottom]); return { scrollRef, autoScroll, setAutoScroll, scrollDomToBottom, }; } export function ChatActions(props: { uploadImage: () => void; setAttachImages: (images: string[]) => void; setUploading: (uploading: boolean) => void; showPromptModal: () => void; scrollToBottom: () => void; showPromptHints: () => void; hitBottom: boolean; uploading: boolean; setShowShortcutKeyModal: React.Dispatch<React.SetStateAction<boolean>>; setUserInput: (input: string) => void; setShowChatSidePanel: React.Dispatch<React.SetStateAction<boolean>>; }) { const config = useAppConfig(); const navigate = useNavigate(); const chatStore = useChatStore(); const pluginStore = usePluginStore(); const session = chatStore.currentSession(); // switch themes const theme = config.theme; function nextTheme() { const themes = [Theme.Auto, Theme.Light, Theme.Dark]; const themeIndex = themes.indexOf(theme); const nextIndex = (themeIndex + 1) % themes.length; const nextTheme = themes[nextIndex]; config.update((config) => (config.theme = nextTheme)); } // stop all responses const couldStop = ChatControllerPool.hasPending(); const stopAll = () => ChatControllerPool.stopAll(); // switch model const currentModel = session.mask.modelConfig.model; const currentProviderName = session.mask.modelConfig?.providerName || ServiceProvider.OpenAI; const allModels = useAllModels(); const models = useMemo(() => { const filteredModels = allModels.filter((m) => m.available); const defaultModel = filteredModels.find((m) => m.isDefault); if (defaultModel) { const arr = [ defaultModel, ...filteredModels.filter((m) => m !== defaultModel), ]; return arr; } else { return filteredModels; } }, [allModels]); const currentModelName = useMemo(() => { const model = models.find( (m) => m.name == currentModel && m?.provider?.providerName == currentProviderName, ); return model?.displayName ?? ""; }, [models, currentModel, currentProviderName]); const [showModelSelector, setShowModelSelector] = useState(false); const [showPluginSelector, setShowPluginSelector] = useState(false); const [showUploadImage, setShowUploadImage] = useState(false); const [showSizeSelector, setShowSizeSelector] = useState(false); const [showQualitySelector, setShowQualitySelector] = useState(false); const [showStyleSelector, setShowStyleSelector] = useState(false); const modelSizes = getModelSizes(currentModel); const dalle3Qualitys: DalleQuality[] = ["standard", "hd"]; const dalle3Styles: DalleStyle[] = ["vivid", "natural"]; const currentSize = session.mask.modelConfig?.size ?? ("1024x1024" as ModelSize); const currentQuality = session.mask.modelConfig?.quality ?? "standard"; const currentStyle = session.mask.modelConfig?.style ?? "vivid"; const isMobileScreen = useMobileScreen(); useEffect(() => { const show = isVisionModel(currentModel); setShowUploadImage(show); if (!show) { props.setAttachImages([]); props.setUploading(false); } // if current model is not available // switch to first available model const isUnavailableModel = !models.some((m) => m.name === currentModel); if (isUnavailableModel && models.length > 0) { // show next model to default model if exist let nextModel = models.find((model) => model.isDefault) || models[0]; chatStore.updateTargetSession(session, (session) => { session.mask.modelConfig.model = nextModel.name; session.mask.modelConfig.providerName = nextModel?.provider ?.providerName as ServiceProvider; }); showToast( nextModel?.provider?.providerName == "ByteDance" ? nextModel.displayName : nextModel.name, ); } }, [chatStore, currentModel, models, session]); return ( <div className={styles["chat-input-actions"]}> <> {couldStop && ( <ChatAction onClick={stopAll} text={Locale.Chat.InputActions.Stop} icon={<StopIcon />} /> )} {!props.hitBottom && ( <ChatAction onClick={props.scrollToBottom} text={Locale.Chat.InputActions.ToBottom} icon={<BottomIcon />} /> )} {props.hitBottom && ( <ChatAction onClick={props.showPromptModal} text={Locale.Chat.InputActions.Settings} icon={<SettingsIcon />} /> )} {showUploadImage && ( <ChatAction onClick={props.uploadImage} text={Locale.Chat.InputActions.UploadImage} icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />} /> )} <ChatAction onClick={nextTheme} text={Locale.Chat.InputActions.Theme[theme]} icon={ <> {theme === Theme.Auto ? ( <AutoIcon /> ) : theme === Theme.Light ? ( <LightIcon /> ) : theme === Theme.Dark ? ( <DarkIcon /> ) : null} </> } /> <ChatAction onClick={props.showPromptHints} text={Locale.Chat.InputActions.Prompt} icon={<PromptIcon />} /> <ChatAction onClick={() => { navigate(Path.Masks); }} text={Locale.Chat.InputActions.Masks} icon={<MaskIcon />} /> <ChatAction text={Locale.Chat.InputActions.Clear} icon={<BreakIcon />} onClick={() => { chatStore.updateTargetSession(session, (session) => { if (session.clearContextIndex === session.messages.length) { session.clearContextIndex = undefined; } else { session.clearContextIndex = session.messages.length; session.memoryPrompt = ""; // will clear memory } }); }} /> <ChatAction onClick={() => setShowModelSelector(true)} text={currentModelName} icon={<RobotIcon />} /> {showModelSelector && ( <Selector defaultSelectedValue={`${currentModel}@${currentProviderName}`} items={models.map((m) => ({ title: `${m.displayName}${ m?.provider?.providerName ? " (" + m?.provider?.providerName + ")" : "" }`, value: `${m.name}@${m?.provider?.providerName}`, }))} onClose={() => setShowModelSelector(false)} onSelection={(s) => { if (s.length === 0) return; const [model, providerName] = getModelProvider(s[0]); chatStore.updateTargetSession(session, (session) => { session.mask.modelConfig.model = model as ModelType; session.mask.modelConfig.providerName = providerName as ServiceProvider; session.mask.syncGlobalConfig = false; }); if (providerName == "ByteDance") { const selectedModel = models.find( (m) => m.name == model && m?.provider?.providerName == providerName, ); showToast(selectedModel?.displayName ?? ""); } else { showToast(model); } }} /> )} {supportsCustomSize(currentModel) && ( <ChatAction onClick={() => setShowSizeSelector(true)} text={currentSize} icon={<SizeIcon />} /> )} {showSizeSelector && ( <Selector defaultSelectedValue={currentSize} items={modelSizes.map((m) => ({ title: m, value: m, }))} onClose={() => setShowSizeSelector(false)} onSelection={(s) => { if (s.length === 0) return; const size = s[0]; chatStore.updateTargetSession(session, (session) => { session.mask.modelConfig.size = size; }); showToast(size); }} /> )} {isDalle3(currentModel) && ( <ChatAction onClick={() => setShowQualitySelector(true)} text={currentQuality} icon={<QualityIcon />} /> )} {showQualitySelector && ( <Selector defaultSelectedValue={currentQuality} items={dalle3Qualitys.map((m) => ({ title: m, value: m, }))} onClose={() => setShowQualitySelector(false)} onSelection={(q) => { if (q.length === 0) return; const quality = q[0]; chatStore.updateTargetSession(session, (session) => { session.mask.modelConfig.quality = quality; }); showToast(quality); }} /> )} {isDalle3(currentModel) && ( <ChatAction onClick={() => setShowStyleSelector(true)} text={currentStyle} icon={<StyleIcon />} /> )} {showStyleSelector && ( <Selector defaultSelectedValue={currentStyle} items={dalle3Styles.map((m) => ({ title: m, value: m, }))} onClose={() => setShowStyleSelector(false)} onSelection={(s) => { if (s.length === 0) return; const style = s[0]; chatStore.updateTargetSession(session, (session) => { session.mask.modelConfig.style = style; }); showToast(style); }} /> )} {showPlugins(currentProviderName, currentModel) && ( <ChatAction onClick={() => { if (pluginStore.getAll().length == 0) { navigate(Path.Plugins); } else { setShowPluginSelector(true); } }} text={Locale.Plugin.Name} icon={<PluginIcon />} /> )} {showPluginSelector && ( <Selector multiple defaultSelectedValue={chatStore.currentSession().mask?.plugin} items={pluginStore.getAll().map((item) => ({ title: `${item?.title}@${item?.version}`, value: item?.id, }))} onClose={() => setShowPluginSelector(false)} onSelection={(s) => { chatStore.updateTargetSession(session, (session) => { session.mask.plugin = s as string[]; }); }} /> )} {!isMobileScreen && ( <ChatAction onClick={() => props.setShowShortcutKeyModal(true)} text={Locale.Chat.ShortcutKey.Title} icon={<ShortcutkeyIcon />} /> )} {!isMobileScreen && <MCPAction />} </> <div className={styles["chat-input-actions-end"]}> {config.realtimeConfig.enable && ( <ChatAction onClick={() => props.setShowChatSidePanel(true)} text={"Realtime Chat"} icon={<HeadphoneIcon />} /> )} </div> </div> ); } export function EditMessageModal(props: { onClose: () => void }) { const chatStore = useChatStore(); const session = chatStore.currentSession(); const [messages, setMessages] = useState(session.messages.slice()); return ( <div className="modal-mask"> <Modal title={Locale.Chat.EditMessage.Title} onClose={props.onClose} actions={[ <IconButton text={Locale.UI.Cancel} icon={<CancelIcon />} key="cancel" onClick={() => { props.onClose(); }} />, <IconButton type="primary" text={Locale.UI.Confirm} icon={<ConfirmIcon />} key="ok" onClick={() => { chatStore.updateTargetSession( session, (session) => (session.messages = messages), ); props.onClose(); }} />, ]} > <List> <ListItem title={Locale.Chat.EditMessage.Topic.Title} subTitle={Locale.Chat.EditMessage.Topic.SubTitle} > <input type="text" value={session.topic} onInput={(e) => chatStore.updateTargetSession( session, (session) => (session.topic = e.currentTarget.value), ) } ></input> </ListItem> </List> <ContextPrompts context={messages} updateContext={(updater) => { const newMessages = messages.slice(); updater(newMessages); setMessages(newMessages); }} /> </Modal> </div> ); } export function DeleteImageButton(props: { deleteImage: () => void }) { return ( <div className={styles["delete-image"]} onClick={props.deleteImage}> <DeleteIcon /> </div> ); } export function ShortcutKeyModal(props: { onClose: () => void }) { const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0; const shortcuts = [ { title: Locale.Chat.ShortcutKey.newChat, keys: isMac ? ["⌘", "Shift", "O"] : ["Ctrl", "Shift", "O"], }, { title: Locale.Chat.ShortcutKey.focusInput, keys: ["Shift", "Esc"] }, { title: Locale.Chat.ShortcutKey.copyLastCode, keys: isMac ? ["⌘", "Shift", ";"] : ["Ctrl", "Shift", ";"], }, { title: Locale.Chat.ShortcutKey.copyLastMessage, keys: isMac ? ["⌘", "Shift", "C"] : ["Ctrl", "Shift", "C"], }, { title: Locale.Chat.ShortcutKey.showShortcutKey, keys: isMac ? ["⌘", "/"] : ["Ctrl", "/"], }, { title: Locale.Chat.ShortcutKey.clearContext, keys: isMac ? ["⌘", "Shift", "backspace"] : ["Ctrl", "Shift", "backspace"], }, ]; return ( <div className="modal-mask"> <Modal title={Locale.Chat.ShortcutKey.Title} onClose={props.onClose} actions={[ <IconButton type="primary" text={Locale.UI.Confirm} icon={<ConfirmIcon />} key="ok" onClick={() => { props.onClose(); }} />, ]} > <div className={styles["shortcut-key-container"]}> <div className={styles["shortcut-key-grid"]}> {shortcuts.map((shortcut, index) => ( <div key={index} className={styles["shortcut-key-item"]}> <div className={styles["shortcut-key-title"]}> {shortcut.title} </div> <div className={styles["shortcut-key-keys"]}> {shortcut.keys.map((key, i) => ( <div key={i} className={styles["shortcut-key"]}> <span>{key}</span> </div> ))} </div> </div> ))} </div> </div> </Modal> </div> ); } function _Chat() { type RenderMessage = ChatMessage & { preview?: boolean }; const chatStore = useChatStore(); const session = chatStore.currentSession(); const config = useAppConfig(); const fontSize = config.fontSize; const fontFamily = config.fontFamily; const [showExport, setShowExport] = useState(false); const inputRef = useRef<HTMLTextAreaElement>(null); const [userInput, setUserInput] = useState(""); const [isLoading, setIsLoading] = useState(false); const { submitKey, shouldSubmit } = useSubmitHandler(); const scrollRef = useRef<HTMLDivElement>(null); const isScrolledToBottom = scrollRef?.current ? Math.abs( scrollRef.current.scrollHeight - (scrollRef.current.scrollTop + scrollRef.current.clientHeight), ) <= 1 : false; const isAttachWithTop = useMemo(() => { const lastMessage = scrollRef.current?.lastElementChild as HTMLElement; // if scrolllRef is not ready or no message, return false if (!scrollRef?.current || !lastMessage) return false; const topDistance = lastMessage!.getBoundingClientRect().top - scrollRef.current.getBoundingClientRect().top; // leave some space for user question return topDistance < 100; }, [scrollRef?.current?.scrollHeight]); const isTyping = userInput !== ""; // if user is typing, should auto scroll to bottom // if user is not typing, should auto scroll to bottom only if already at bottom const { setAutoScroll, scrollDomToBottom } = useScrollToBottom( scrollRef, (isScrolledToBottom || isAttachWithTop) && !isTyping, session.messages, ); const [hitBottom, setHitBottom] = useState(true); const isMobileScreen = useMobileScreen(); const navigate = useNavigate(); const [attachImages, setAttachImages] = useState<string[]>([]); const [uploading, setUploading] = useState(false); // prompt hints const promptStore = usePromptStore(); const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]); const onSearch = useDebouncedCallback( (text: string) => { const matchedPrompts = promptStore.search(text); setPromptHints(matchedPrompts); }, 100, { leading: true, trailing: true }, ); // auto grow input const [inputRows, setInputRows] = useState(2); const measure = useDebouncedCallback( () => { const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1; const inputRows = Math.min( 20, Math.max(2 + Number(!isMobileScreen), rows), ); setInputRows(inputRows); }, 100, { leading: true, trailing: true, }, ); // eslint-disable-next-line react-hooks/exhaustive-deps useEffect(measure, [userInput]); // chat commands shortcuts const chatCommands = useChatCommand({ new: () => chatStore.newSession(), newm: () => navigate(Path.NewChat), prev: () => chatStore.nextSession(-1), next: () => chatStore.nextSession(1), clear: () => chatStore.updateTargetSession( session, (session) => (session.clearContextIndex = session.messages.length), ), fork: () => chatStore.forkSession(), del: () => chatStore.deleteSession(chatStore.currentSessionIndex), });
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
true
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/model-config.tsx
app/components/model-config.tsx
import { ServiceProvider } from "@/app/constant"; import { ModalConfigValidator, ModelConfig } from "../store"; import Locale from "../locales"; import { InputRange } from "./input-range"; import { ListItem, Select } from "./ui-lib"; import { useAllModels } from "../utils/hooks"; import { groupBy } from "lodash-es"; import styles from "./model-config.module.scss"; import { getModelProvider } from "../utils/model"; export function ModelConfigList(props: { modelConfig: ModelConfig; updateConfig: (updater: (config: ModelConfig) => void) => void; }) { const allModels = useAllModels(); const groupModels = groupBy( allModels.filter((v) => v.available), "provider.providerName", ); const value = `${props.modelConfig.model}@${props.modelConfig?.providerName}`; const compressModelValue = `${props.modelConfig.compressModel}@${props.modelConfig?.compressProviderName}`; return ( <> <ListItem title={Locale.Settings.Model}> <Select aria-label={Locale.Settings.Model} value={value} align="left" onChange={(e) => { const [model, providerName] = getModelProvider( e.currentTarget.value, ); props.updateConfig((config) => { config.model = ModalConfigValidator.model(model); config.providerName = providerName as ServiceProvider; }); }} > {Object.keys(groupModels).map((providerName, index) => ( <optgroup label={providerName} key={index}> {groupModels[providerName].map((v, i) => ( <option value={`${v.name}@${v.provider?.providerName}`} key={i}> {v.displayName} </option> ))} </optgroup> ))} </Select> </ListItem> <ListItem title={Locale.Settings.Temperature.Title} subTitle={Locale.Settings.Temperature.SubTitle} > <InputRange aria={Locale.Settings.Temperature.Title} value={props.modelConfig.temperature?.toFixed(1)} min="0" max="1" // lets limit it to 0-1 step="0.1" onChange={(e) => { props.updateConfig( (config) => (config.temperature = ModalConfigValidator.temperature( e.currentTarget.valueAsNumber, )), ); }} ></InputRange> </ListItem> <ListItem title={Locale.Settings.TopP.Title} subTitle={Locale.Settings.TopP.SubTitle} > <InputRange aria={Locale.Settings.TopP.Title} value={(props.modelConfig.top_p ?? 1).toFixed(1)} min="0" max="1" step="0.1" onChange={(e) => { props.updateConfig( (config) => (config.top_p = ModalConfigValidator.top_p( e.currentTarget.valueAsNumber, )), ); }} ></InputRange> </ListItem> <ListItem title={Locale.Settings.MaxTokens.Title} subTitle={Locale.Settings.MaxTokens.SubTitle} > <input aria-label={Locale.Settings.MaxTokens.Title} type="number" min={1024} max={512000} value={props.modelConfig.max_tokens} onChange={(e) => props.updateConfig( (config) => (config.max_tokens = ModalConfigValidator.max_tokens( e.currentTarget.valueAsNumber, )), ) } ></input> </ListItem> {props.modelConfig?.providerName == ServiceProvider.Google ? null : ( <> <ListItem title={Locale.Settings.PresencePenalty.Title} subTitle={Locale.Settings.PresencePenalty.SubTitle} > <InputRange aria={Locale.Settings.PresencePenalty.Title} value={props.modelConfig.presence_penalty?.toFixed(1)} min="-2" max="2" step="0.1" onChange={(e) => { props.updateConfig( (config) => (config.presence_penalty = ModalConfigValidator.presence_penalty( e.currentTarget.valueAsNumber, )), ); }} ></InputRange> </ListItem> <ListItem title={Locale.Settings.FrequencyPenalty.Title} subTitle={Locale.Settings.FrequencyPenalty.SubTitle} > <InputRange aria={Locale.Settings.FrequencyPenalty.Title} value={props.modelConfig.frequency_penalty?.toFixed(1)} min="-2" max="2" step="0.1" onChange={(e) => { props.updateConfig( (config) => (config.frequency_penalty = ModalConfigValidator.frequency_penalty( e.currentTarget.valueAsNumber, )), ); }} ></InputRange> </ListItem> <ListItem title={Locale.Settings.InjectSystemPrompts.Title} subTitle={Locale.Settings.InjectSystemPrompts.SubTitle} > <input aria-label={Locale.Settings.InjectSystemPrompts.Title} type="checkbox" checked={props.modelConfig.enableInjectSystemPrompts} onChange={(e) => props.updateConfig( (config) => (config.enableInjectSystemPrompts = e.currentTarget.checked), ) } ></input> </ListItem> <ListItem title={Locale.Settings.InputTemplate.Title} subTitle={Locale.Settings.InputTemplate.SubTitle} > <input aria-label={Locale.Settings.InputTemplate.Title} type="text" value={props.modelConfig.template} onChange={(e) => props.updateConfig( (config) => (config.template = e.currentTarget.value), ) } ></input> </ListItem> </> )} <ListItem title={Locale.Settings.HistoryCount.Title} subTitle={Locale.Settings.HistoryCount.SubTitle} > <InputRange aria={Locale.Settings.HistoryCount.Title} title={props.modelConfig.historyMessageCount.toString()} value={props.modelConfig.historyMessageCount} min="0" max="64" step="1" onChange={(e) => props.updateConfig( (config) => (config.historyMessageCount = e.target.valueAsNumber), ) } ></InputRange> </ListItem> <ListItem title={Locale.Settings.CompressThreshold.Title} subTitle={Locale.Settings.CompressThreshold.SubTitle} > <input aria-label={Locale.Settings.CompressThreshold.Title} type="number" min={500} max={4000} value={props.modelConfig.compressMessageLengthThreshold} onChange={(e) => props.updateConfig( (config) => (config.compressMessageLengthThreshold = e.currentTarget.valueAsNumber), ) } ></input> </ListItem> <ListItem title={Locale.Memory.Title} subTitle={Locale.Memory.Send}> <input aria-label={Locale.Memory.Title} type="checkbox" checked={props.modelConfig.sendMemory} onChange={(e) => props.updateConfig( (config) => (config.sendMemory = e.currentTarget.checked), ) } ></input> </ListItem> <ListItem title={Locale.Settings.CompressModel.Title} subTitle={Locale.Settings.CompressModel.SubTitle} > <Select className={styles["select-compress-model"]} aria-label={Locale.Settings.CompressModel.Title} value={compressModelValue} onChange={(e) => { const [model, providerName] = getModelProvider( e.currentTarget.value, ); props.updateConfig((config) => { config.compressModel = ModalConfigValidator.model(model); config.compressProviderName = providerName as ServiceProvider; }); }} > {allModels .filter((v) => v.available) .map((v, i) => ( <option value={`${v.name}@${v.provider?.providerName}`} key={i}> {v.displayName}({v.provider?.providerName}) </option> ))} </Select> </ListItem> </> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/home.tsx
app/components/home.tsx
"use client"; require("../polyfill"); import { useEffect, useState } from "react"; import styles from "./home.module.scss"; import BotIcon from "../icons/bot.svg"; import LoadingIcon from "../icons/three-dots.svg"; import { getCSSVar, useMobileScreen } from "../utils"; import dynamic from "next/dynamic"; import { Path, SlotID } from "../constant"; import { ErrorBoundary } from "./error"; import { getISOLang, getLang } from "../locales"; import { HashRouter as Router, Route, Routes, useLocation, } from "react-router-dom"; import { SideBar } from "./sidebar"; import { useAppConfig } from "../store/config"; import { AuthPage } from "./auth"; import { getClientConfig } from "../config/client"; import { type ClientApi, getClientApi } from "../client/api"; import { useAccessStore } from "../store"; import clsx from "clsx"; import { initializeMcpSystem, isMcpEnabled } from "../mcp/actions"; export function Loading(props: { noLogo?: boolean }) { return ( <div className={clsx("no-dark", styles["loading-content"])}> {!props.noLogo && <BotIcon />} <LoadingIcon /> </div> ); } const Artifacts = dynamic(async () => (await import("./artifacts")).Artifacts, { loading: () => <Loading noLogo />, }); const Settings = dynamic(async () => (await import("./settings")).Settings, { loading: () => <Loading noLogo />, }); const Chat = dynamic(async () => (await import("./chat")).Chat, { loading: () => <Loading noLogo />, }); const NewChat = dynamic(async () => (await import("./new-chat")).NewChat, { loading: () => <Loading noLogo />, }); const MaskPage = dynamic(async () => (await import("./mask")).MaskPage, { loading: () => <Loading noLogo />, }); const PluginPage = dynamic(async () => (await import("./plugin")).PluginPage, { loading: () => <Loading noLogo />, }); const SearchChat = dynamic( async () => (await import("./search-chat")).SearchChatPage, { loading: () => <Loading noLogo />, }, ); const Sd = dynamic(async () => (await import("./sd")).Sd, { loading: () => <Loading noLogo />, }); const McpMarketPage = dynamic( async () => (await import("./mcp-market")).McpMarketPage, { loading: () => <Loading noLogo />, }, ); export function useSwitchTheme() { const config = useAppConfig(); useEffect(() => { document.body.classList.remove("light"); document.body.classList.remove("dark"); if (config.theme === "dark") { document.body.classList.add("dark"); } else if (config.theme === "light") { document.body.classList.add("light"); } const metaDescriptionDark = document.querySelector( 'meta[name="theme-color"][media*="dark"]', ); const metaDescriptionLight = document.querySelector( 'meta[name="theme-color"][media*="light"]', ); if (config.theme === "auto") { metaDescriptionDark?.setAttribute("content", "#151515"); metaDescriptionLight?.setAttribute("content", "#fafafa"); } else { const themeColor = getCSSVar("--theme-color"); metaDescriptionDark?.setAttribute("content", themeColor); metaDescriptionLight?.setAttribute("content", themeColor); } }, [config.theme]); } function useHtmlLang() { useEffect(() => { const lang = getISOLang(); const htmlLang = document.documentElement.lang; if (lang !== htmlLang) { document.documentElement.lang = lang; } }, []); } const useHasHydrated = () => { const [hasHydrated, setHasHydrated] = useState<boolean>(false); useEffect(() => { setHasHydrated(true); }, []); return hasHydrated; }; const loadAsyncGoogleFont = () => { const linkEl = document.createElement("link"); const proxyFontUrl = "/google-fonts"; const remoteFontUrl = "https://fonts.googleapis.com"; const googleFontUrl = getClientConfig()?.buildMode === "export" ? remoteFontUrl : proxyFontUrl; linkEl.rel = "stylesheet"; linkEl.href = googleFontUrl + "/css2?family=" + encodeURIComponent("Noto Sans:wght@300;400;700;900") + "&display=swap"; document.head.appendChild(linkEl); }; export function WindowContent(props: { children: React.ReactNode }) { return ( <div className={styles["window-content"]} id={SlotID.AppBody}> {props?.children} </div> ); } function Screen() { const config = useAppConfig(); const location = useLocation(); const isArtifact = location.pathname.includes(Path.Artifacts); const isHome = location.pathname === Path.Home; const isAuth = location.pathname === Path.Auth; const isSd = location.pathname === Path.Sd; const isSdNew = location.pathname === Path.SdNew; const isMobileScreen = useMobileScreen(); const shouldTightBorder = getClientConfig()?.isApp || (config.tightBorder && !isMobileScreen); useEffect(() => { loadAsyncGoogleFont(); }, []); if (isArtifact) { return ( <Routes> <Route path="/artifacts/:id" element={<Artifacts />} /> </Routes> ); } const renderContent = () => { if (isAuth) return <AuthPage />; if (isSd) return <Sd />; if (isSdNew) return <Sd />; return ( <> <SideBar className={clsx({ [styles["sidebar-show"]]: isHome, })} /> <WindowContent> <Routes> <Route path={Path.Home} element={<Chat />} /> <Route path={Path.NewChat} element={<NewChat />} /> <Route path={Path.Masks} element={<MaskPage />} /> <Route path={Path.Plugins} element={<PluginPage />} /> <Route path={Path.SearchChat} element={<SearchChat />} /> <Route path={Path.Chat} element={<Chat />} /> <Route path={Path.Settings} element={<Settings />} /> <Route path={Path.McpMarket} element={<McpMarketPage />} /> </Routes> </WindowContent> </> ); }; return ( <div className={clsx(styles.container, { [styles["tight-container"]]: shouldTightBorder, [styles["rtl-screen"]]: getLang() === "ar", })} > {renderContent()} </div> ); } export function useLoadData() { const config = useAppConfig(); const api: ClientApi = getClientApi(config.modelConfig.providerName); useEffect(() => { (async () => { const models = await api.llm.models(); config.mergeModels(models); })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); } export function Home() { useSwitchTheme(); useLoadData(); useHtmlLang(); useEffect(() => { console.log("[Config] got config from build time", getClientConfig()); useAccessStore.getState().fetch(); const initMcp = async () => { try { const enabled = await isMcpEnabled(); if (enabled) { console.log("[MCP] initializing..."); await initializeMcpSystem(); console.log("[MCP] initialized"); } } catch (err) { console.error("[MCP] failed to initialize:", err); } }; initMcp(); }, []); if (!useHasHydrated()) { return <Loading />; } return ( <ErrorBoundary> <Router> <Screen /> </Router> </ErrorBoundary> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/sd/index.tsx
app/components/sd/index.tsx
export * from "./sd"; export * from "./sd-panel";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/sd/sd-sidebar.tsx
app/components/sd/sd-sidebar.tsx
import { IconButton } from "@/app/components/button"; import GithubIcon from "@/app/icons/github.svg"; import SDIcon from "@/app/icons/sd.svg"; import ReturnIcon from "@/app/icons/return.svg"; import HistoryIcon from "@/app/icons/history.svg"; import Locale from "@/app/locales"; import { Path, REPO_URL } from "@/app/constant"; import { useNavigate } from "react-router-dom"; import dynamic from "next/dynamic"; import { SideBarContainer, SideBarBody, SideBarHeader, SideBarTail, useDragSideBar, useHotKey, } from "@/app/components/sidebar"; import { getParams, getModelParamBasicData } from "./sd-panel"; import { useSdStore } from "@/app/store/sd"; import { showToast } from "@/app/components/ui-lib"; import { useMobileScreen } from "@/app/utils"; const SdPanel = dynamic( async () => (await import("@/app/components/sd")).SdPanel, { loading: () => null, }, ); export function SideBar(props: { className?: string }) { useHotKey(); const isMobileScreen = useMobileScreen(); const { onDragStart, shouldNarrow } = useDragSideBar(); const navigate = useNavigate(); const sdStore = useSdStore(); const currentModel = sdStore.currentModel; const params = sdStore.currentParams; const setParams = sdStore.setCurrentParams; const handleSubmit = () => { const columns = getParams?.(currentModel, params); const reqParams: any = {}; for (let i = 0; i < columns.length; i++) { const item = columns[i]; reqParams[item.value] = params[item.value] ?? null; if (item.required) { if (!reqParams[item.value]) { showToast(Locale.SdPanel.ParamIsRequired(item.name)); return; } } } let data: any = { model: currentModel.value, model_name: currentModel.name, status: "wait", params: reqParams, created_at: new Date().toLocaleString(), img_data: "", }; sdStore.sendTask(data, () => { setParams(getModelParamBasicData(columns, params, true)); navigate(Path.SdNew); }); }; return ( <SideBarContainer onDragStart={onDragStart} shouldNarrow={shouldNarrow} {...props} > {isMobileScreen ? ( <div className="window-header" data-tauri-drag-region style={{ paddingLeft: 0, paddingRight: 0, }} > <div className="window-actions"> <div className="window-action-button"> <IconButton icon={<ReturnIcon />} bordered title={Locale.Sd.Actions.ReturnHome} onClick={() => navigate(Path.Home)} /> </div> </div> <SDIcon width={50} height={50} /> <div className="window-actions"> <div className="window-action-button"> <IconButton icon={<HistoryIcon />} bordered title={Locale.Sd.Actions.History} onClick={() => navigate(Path.SdNew)} /> </div> </div> </div> ) : ( <SideBarHeader title={ <IconButton icon={<ReturnIcon />} bordered title={Locale.Sd.Actions.ReturnHome} onClick={() => navigate(Path.Home)} /> } logo={<SDIcon width={38} height={"100%"} />} ></SideBarHeader> )} <SideBarBody> <SdPanel /> </SideBarBody> <SideBarTail primaryAction={ <a href={REPO_URL} target="_blank" rel="noopener noreferrer"> <IconButton icon={<GithubIcon />} shadow /> </a> } secondaryAction={ <IconButton text={Locale.SdPanel.Submit} type="primary" shadow onClick={handleSubmit} ></IconButton> } /> </SideBarContainer> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/sd/sd-panel.tsx
app/components/sd/sd-panel.tsx
import styles from "./sd-panel.module.scss"; import React from "react"; import { Select } from "@/app/components/ui-lib"; import { IconButton } from "@/app/components/button"; import Locale from "@/app/locales"; import { useSdStore } from "@/app/store/sd"; import clsx from "clsx"; export const params = [ { name: Locale.SdPanel.Prompt, value: "prompt", type: "textarea", placeholder: Locale.SdPanel.PleaseInput(Locale.SdPanel.Prompt), required: true, }, { name: Locale.SdPanel.ModelVersion, value: "model", type: "select", default: "sd3-medium", support: ["sd3"], options: [ { name: "SD3 Medium", value: "sd3-medium" }, { name: "SD3 Large", value: "sd3-large" }, { name: "SD3 Large Turbo", value: "sd3-large-turbo" }, ], }, { name: Locale.SdPanel.NegativePrompt, value: "negative_prompt", type: "textarea", placeholder: Locale.SdPanel.PleaseInput(Locale.SdPanel.NegativePrompt), }, { name: Locale.SdPanel.AspectRatio, value: "aspect_ratio", type: "select", default: "1:1", options: [ { name: "1:1", value: "1:1" }, { name: "16:9", value: "16:9" }, { name: "21:9", value: "21:9" }, { name: "2:3", value: "2:3" }, { name: "3:2", value: "3:2" }, { name: "4:5", value: "4:5" }, { name: "5:4", value: "5:4" }, { name: "9:16", value: "9:16" }, { name: "9:21", value: "9:21" }, ], }, { name: Locale.SdPanel.ImageStyle, value: "style", type: "select", default: "3d-model", support: ["core"], options: [ { name: Locale.SdPanel.Styles.D3Model, value: "3d-model" }, { name: Locale.SdPanel.Styles.AnalogFilm, value: "analog-film" }, { name: Locale.SdPanel.Styles.Anime, value: "anime" }, { name: Locale.SdPanel.Styles.Cinematic, value: "cinematic" }, { name: Locale.SdPanel.Styles.ComicBook, value: "comic-book" }, { name: Locale.SdPanel.Styles.DigitalArt, value: "digital-art" }, { name: Locale.SdPanel.Styles.Enhance, value: "enhance" }, { name: Locale.SdPanel.Styles.FantasyArt, value: "fantasy-art" }, { name: Locale.SdPanel.Styles.Isometric, value: "isometric" }, { name: Locale.SdPanel.Styles.LineArt, value: "line-art" }, { name: Locale.SdPanel.Styles.LowPoly, value: "low-poly" }, { name: Locale.SdPanel.Styles.ModelingCompound, value: "modeling-compound", }, { name: Locale.SdPanel.Styles.NeonPunk, value: "neon-punk" }, { name: Locale.SdPanel.Styles.Origami, value: "origami" }, { name: Locale.SdPanel.Styles.Photographic, value: "photographic" }, { name: Locale.SdPanel.Styles.PixelArt, value: "pixel-art" }, { name: Locale.SdPanel.Styles.TileTexture, value: "tile-texture" }, ], }, { name: "Seed", value: "seed", type: "number", default: 0, min: 0, max: 4294967294, }, { name: Locale.SdPanel.OutFormat, value: "output_format", type: "select", default: "png", options: [ { name: "PNG", value: "png" }, { name: "JPEG", value: "jpeg" }, { name: "WebP", value: "webp" }, ], }, ]; const sdCommonParams = (model: string, data: any) => { return params.filter((item) => { return !(item.support && !item.support.includes(model)); }); }; export const models = [ { name: "Stable Image Ultra", value: "ultra", params: (data: any) => sdCommonParams("ultra", data), }, { name: "Stable Image Core", value: "core", params: (data: any) => sdCommonParams("core", data), }, { name: "Stable Diffusion 3", value: "sd3", params: (data: any) => { return sdCommonParams("sd3", data).filter((item) => { return !( data.model === "sd3-large-turbo" && item.value == "negative_prompt" ); }); }, }, ]; export function ControlParamItem(props: { title: string; subTitle?: string; required?: boolean; children?: JSX.Element | JSX.Element[]; className?: string; }) { return ( <div className={clsx(styles["ctrl-param-item"], props.className)}> <div className={styles["ctrl-param-item-header"]}> <div className={styles["ctrl-param-item-title"]}> <div> {props.title} {props.required && <span style={{ color: "red" }}>*</span>} </div> </div> </div> {props.children} {props.subTitle && ( <div className={styles["ctrl-param-item-sub-title"]}> {props.subTitle} </div> )} </div> ); } export function ControlParam(props: { columns: any[]; data: any; onChange: (field: string, val: any) => void; }) { return ( <> {props.columns?.map((item) => { let element: null | JSX.Element; switch (item.type) { case "textarea": element = ( <ControlParamItem title={item.name} subTitle={item.sub} required={item.required} > <textarea rows={item.rows || 3} style={{ maxWidth: "100%", width: "100%", padding: "10px" }} placeholder={item.placeholder} onChange={(e) => { props.onChange(item.value, e.currentTarget.value); }} value={props.data[item.value]} ></textarea> </ControlParamItem> ); break; case "select": element = ( <ControlParamItem title={item.name} subTitle={item.sub} required={item.required} > <Select aria-label={item.name} value={props.data[item.value]} onChange={(e) => { props.onChange(item.value, e.currentTarget.value); }} > {item.options.map((opt: any) => { return ( <option value={opt.value} key={opt.value}> {opt.name} </option> ); })} </Select> </ControlParamItem> ); break; case "number": element = ( <ControlParamItem title={item.name} subTitle={item.sub} required={item.required} > <input aria-label={item.name} type="number" min={item.min} max={item.max} value={props.data[item.value] || 0} onChange={(e) => { props.onChange(item.value, parseInt(e.currentTarget.value)); }} /> </ControlParamItem> ); break; default: element = ( <ControlParamItem title={item.name} subTitle={item.sub} required={item.required} > <input aria-label={item.name} type="text" value={props.data[item.value]} style={{ maxWidth: "100%", width: "100%" }} onChange={(e) => { props.onChange(item.value, e.currentTarget.value); }} /> </ControlParamItem> ); } return <div key={item.value}>{element}</div>; })} </> ); } export const getModelParamBasicData = ( columns: any[], data: any, clearText?: boolean, ) => { const newParams: any = {}; columns.forEach((item: any) => { if (clearText && ["text", "textarea", "number"].includes(item.type)) { newParams[item.value] = item.default || ""; } else { // @ts-ignore newParams[item.value] = data[item.value] || item.default || ""; } }); return newParams; }; export const getParams = (model: any, params: any) => { return models.find((m) => m.value === model.value)?.params(params) || []; }; export function SdPanel() { const sdStore = useSdStore(); const currentModel = sdStore.currentModel; const setCurrentModel = sdStore.setCurrentModel; const params = sdStore.currentParams; const setParams = sdStore.setCurrentParams; const handleValueChange = (field: string, val: any) => { setParams({ ...params, [field]: val, }); }; const handleModelChange = (model: any) => { setCurrentModel(model); setParams(getModelParamBasicData(model.params({}), params)); }; return ( <> <ControlParamItem title={Locale.SdPanel.AIModel}> <div className={styles["ai-models"]}> {models.map((item) => { return ( <IconButton text={item.name} key={item.value} type={currentModel.value == item.value ? "primary" : null} shadow onClick={() => handleModelChange(item)} /> ); })} </div> </ControlParamItem> <ControlParam columns={getParams?.(currentModel, params) as any[]} data={params} onChange={handleValueChange} ></ControlParam> </> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/sd/sd.tsx
app/components/sd/sd.tsx
import chatStyles from "@/app/components/chat.module.scss"; import styles from "@/app/components/sd/sd.module.scss"; import homeStyles from "@/app/components/home.module.scss"; import { IconButton } from "@/app/components/button"; import ReturnIcon from "@/app/icons/return.svg"; import Locale from "@/app/locales"; import { Path } from "@/app/constant"; import React, { useEffect, useMemo, useRef, useState } from "react"; import { copyToClipboard, getMessageTextContent, useMobileScreen, } from "@/app/utils"; import { useNavigate, useLocation } from "react-router-dom"; import { useAppConfig } from "@/app/store"; import MinIcon from "@/app/icons/min.svg"; import MaxIcon from "@/app/icons/max.svg"; import { getClientConfig } from "@/app/config/client"; import { ChatAction } from "@/app/components/chat"; import DeleteIcon from "@/app/icons/clear.svg"; import CopyIcon from "@/app/icons/copy.svg"; import PromptIcon from "@/app/icons/prompt.svg"; import ResetIcon from "@/app/icons/reload.svg"; import { useSdStore } from "@/app/store/sd"; import LoadingIcon from "@/app/icons/three-dots.svg"; import ErrorIcon from "@/app/icons/delete.svg"; import SDIcon from "@/app/icons/sd.svg"; import { Property } from "csstype"; import { showConfirm, showImageModal, showModal, } from "@/app/components/ui-lib"; import { removeImage } from "@/app/utils/chat"; import { SideBar } from "./sd-sidebar"; import { WindowContent } from "@/app/components/home"; import { params } from "./sd-panel"; import clsx from "clsx"; function getSdTaskStatus(item: any) { let s: string; let color: Property.Color | undefined = undefined; switch (item.status) { case "success": s = Locale.Sd.Status.Success; color = "green"; break; case "error": s = Locale.Sd.Status.Error; color = "red"; break; case "wait": s = Locale.Sd.Status.Wait; color = "yellow"; break; case "running": s = Locale.Sd.Status.Running; color = "blue"; break; default: s = item.status.toUpperCase(); } return ( <p className={styles["line-1"]} title={item.error} style={{ color: color }}> <span> {Locale.Sd.Status.Name}: {s} </span> {item.status === "error" && ( <span className="clickable" onClick={() => { showModal({ title: Locale.Sd.Detail, children: ( <div style={{ color: color, userSelect: "text" }}> {item.error} </div> ), }); }} > - {item.error} </span> )} </p> ); } export function Sd() { const isMobileScreen = useMobileScreen(); const navigate = useNavigate(); const location = useLocation(); const clientConfig = useMemo(() => getClientConfig(), []); const showMaxIcon = !isMobileScreen && !clientConfig?.isApp; const config = useAppConfig(); const scrollRef = useRef<HTMLDivElement>(null); const sdStore = useSdStore(); const [sdImages, setSdImages] = useState(sdStore.draw); const isSd = location.pathname === Path.Sd; useEffect(() => { setSdImages(sdStore.draw); }, [sdStore.currentId]); return ( <> <SideBar className={clsx({ [homeStyles["sidebar-show"]]: isSd })} /> <WindowContent> <div className={chatStyles.chat} key={"1"}> <div className="window-header" data-tauri-drag-region> {isMobileScreen && ( <div className="window-actions"> <div className={"window-action-button"}> <IconButton icon={<ReturnIcon />} bordered title={Locale.Chat.Actions.ChatList} onClick={() => navigate(Path.Sd)} /> </div> </div> )} <div className={clsx( "window-header-title", chatStyles["chat-body-title"], )} > <div className={`window-header-main-title`}>Stability AI</div> <div className="window-header-sub-title"> {Locale.Sd.SubTitle(sdImages.length || 0)} </div> </div> <div className="window-actions"> {showMaxIcon && ( <div className="window-action-button"> <IconButton aria={Locale.Chat.Actions.FullScreen} icon={config.tightBorder ? <MinIcon /> : <MaxIcon />} bordered onClick={() => { config.update( (config) => (config.tightBorder = !config.tightBorder), ); }} /> </div> )} {isMobileScreen && <SDIcon width={50} height={50} />} </div> </div> <div className={chatStyles["chat-body"]} ref={scrollRef}> <div className={styles["sd-img-list"]}> {sdImages.length > 0 ? ( sdImages.map((item: any) => { return ( <div key={item.id} style={{ display: "flex" }} className={styles["sd-img-item"]} > {item.status === "success" ? ( <img className={styles["img"]} src={item.img_data} alt={item.id} onClick={(e) => showImageModal( item.img_data, true, isMobileScreen ? { width: "100%", height: "fit-content" } : { maxWidth: "100%", maxHeight: "100%" }, isMobileScreen ? { width: "100%", height: "fit-content" } : { width: "100%", height: "100%" }, ) } /> ) : item.status === "error" ? ( <div className={styles["pre-img"]}> <ErrorIcon /> </div> ) : ( <div className={styles["pre-img"]}> <LoadingIcon /> </div> )} <div style={{ marginLeft: "10px" }} className={styles["sd-img-item-info"]} > <p className={styles["line-1"]}> {Locale.SdPanel.Prompt}:{" "} <span className="clickable" title={item.params.prompt} onClick={() => { showModal({ title: Locale.Sd.Detail, children: ( <div style={{ userSelect: "text" }}> {item.params.prompt} </div> ), }); }} > {item.params.prompt} </span> </p> <p> {Locale.SdPanel.AIModel}: {item.model_name} </p> {getSdTaskStatus(item)} <p>{item.created_at}</p> <div className={chatStyles["chat-message-actions"]}> <div className={chatStyles["chat-input-actions"]}> <ChatAction text={Locale.Sd.Actions.Params} icon={<PromptIcon />} onClick={() => { showModal({ title: Locale.Sd.GenerateParams, children: ( <div style={{ userSelect: "text" }}> {Object.keys(item.params).map((key) => { let label = key; let value = item.params[key]; switch (label) { case "prompt": label = Locale.SdPanel.Prompt; break; case "negative_prompt": label = Locale.SdPanel.NegativePrompt; break; case "aspect_ratio": label = Locale.SdPanel.AspectRatio; break; case "seed": label = "Seed"; value = value || 0; break; case "output_format": label = Locale.SdPanel.OutFormat; value = value?.toUpperCase(); break; case "style": label = Locale.SdPanel.ImageStyle; value = params .find( (item) => item.value === "style", ) ?.options?.find( (item) => item.value === value, )?.name; break; default: break; } return ( <div key={key} style={{ margin: "10px" }} > <strong>{label}: </strong> {value} </div> ); })} </div> ), }); }} /> <ChatAction text={Locale.Sd.Actions.Copy} icon={<CopyIcon />} onClick={() => copyToClipboard( getMessageTextContent({ role: "user", content: item.params.prompt, }), ) } /> <ChatAction text={Locale.Sd.Actions.Retry} icon={<ResetIcon />} onClick={() => { const reqData = { model: item.model, model_name: item.model_name, status: "wait", params: { ...item.params }, created_at: new Date().toLocaleString(), img_data: "", }; sdStore.sendTask(reqData); }} /> <ChatAction text={Locale.Sd.Actions.Delete} icon={<DeleteIcon />} onClick={async () => { if ( await showConfirm(Locale.Sd.Danger.Delete) ) { // remove img_data + remove item in list removeImage(item.img_data).finally(() => { sdStore.draw = sdImages.filter( (i: any) => i.id !== item.id, ); sdStore.getNextId(); }); } }} /> </div> </div> </div> </div> ); }) ) : ( <div>{Locale.Sd.EmptyRecord}</div> )} </div> </div> </div> </WindowContent> </> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/voice-print/voice-print.tsx
app/components/voice-print/voice-print.tsx
import { useEffect, useRef, useCallback } from "react"; import styles from "./voice-print.module.scss"; interface VoicePrintProps { frequencies?: Uint8Array; isActive?: boolean; } export function VoicePrint({ frequencies, isActive }: VoicePrintProps) { // Canvas引用,用于获取绘图上下文 const canvasRef = useRef<HTMLCanvasElement>(null); // 存储历史频率数据,用于平滑处理 const historyRef = useRef<number[][]>([]); // 控制保留的历史数据帧数,影响平滑度 const historyLengthRef = useRef(10); // 存储动画帧ID,用于清理 const animationFrameRef = useRef<number>(); /** * 更新频率历史数据 * 使用FIFO队列维护固定长度的历史记录 */ const updateHistory = useCallback((freqArray: number[]) => { historyRef.current.push(freqArray); if (historyRef.current.length > historyLengthRef.current) { historyRef.current.shift(); } }, []); useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; const ctx = canvas.getContext("2d"); if (!ctx) return; /** * 处理高DPI屏幕显示 * 根据设备像素比例调整canvas实际渲染分辨率 */ const dpr = window.devicePixelRatio || 1; canvas.width = canvas.offsetWidth * dpr; canvas.height = canvas.offsetHeight * dpr; ctx.scale(dpr, dpr); /** * 主要绘制函数 * 使用requestAnimationFrame实现平滑动画 * 包含以下步骤: * 1. 清空画布 * 2. 更新历史数据 * 3. 计算波形点 * 4. 绘制上下对称的声纹 */ const draw = () => { // 清空画布 ctx.clearRect(0, 0, canvas.width, canvas.height); if (!frequencies || !isActive) { historyRef.current = []; return; } const freqArray = Array.from(frequencies); updateHistory(freqArray); // 绘制声纹 const points: [number, number][] = []; const centerY = canvas.height / 2; const width = canvas.width; const sliceWidth = width / (frequencies.length - 1); // 绘制主波形 ctx.beginPath(); ctx.moveTo(0, centerY); /** * 声纹绘制算法: * 1. 使用历史数据平均值实现平滑过渡 * 2. 通过正弦函数添加自然波动 * 3. 使用贝塞尔曲线连接点,使曲线更平滑 * 4. 绘制对称部分形成完整声纹 */ for (let i = 0; i < frequencies.length; i++) { const x = i * sliceWidth; let avgFrequency = frequencies[i]; /** * 波形平滑处理: * 1. 收集历史数据中对应位置的频率值 * 2. 计算当前值与历史值的加权平均 * 3. 根据平均值计算实际显示高度 */ if (historyRef.current.length > 0) { const historicalValues = historyRef.current.map((h) => h[i] || 0); avgFrequency = (avgFrequency + historicalValues.reduce((a, b) => a + b, 0)) / (historyRef.current.length + 1); } /** * 波形变换: * 1. 归一化频率值到0-1范围 * 2. 添加时间相关的正弦变换 * 3. 使用贝塞尔曲线平滑连接点 */ const normalized = avgFrequency / 255.0; const height = normalized * (canvas.height / 2); const y = centerY + height * Math.sin(i * 0.2 + Date.now() * 0.002); points.push([x, y]); if (i === 0) { ctx.moveTo(x, y); } else { // 使用贝塞尔曲线使波形更平滑 const prevPoint = points[i - 1]; const midX = (prevPoint[0] + x) / 2; ctx.quadraticCurveTo( prevPoint[0], prevPoint[1], midX, (prevPoint[1] + y) / 2, ); } } // 绘制对称的下半部分 for (let i = points.length - 1; i >= 0; i--) { const [x, y] = points[i]; const symmetricY = centerY - (y - centerY); if (i === points.length - 1) { ctx.lineTo(x, symmetricY); } else { const nextPoint = points[i + 1]; const midX = (nextPoint[0] + x) / 2; ctx.quadraticCurveTo( nextPoint[0], centerY - (nextPoint[1] - centerY), midX, centerY - ((nextPoint[1] + y) / 2 - centerY), ); } } ctx.closePath(); /** * 渐变效果: * 从左到右应用三色渐变,带透明度 * 使用蓝色系配色提升视觉效果 */ const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0); gradient.addColorStop(0, "rgba(100, 180, 255, 0.95)"); gradient.addColorStop(0.5, "rgba(140, 200, 255, 0.9)"); gradient.addColorStop(1, "rgba(180, 220, 255, 0.95)"); ctx.fillStyle = gradient; ctx.fill(); animationFrameRef.current = requestAnimationFrame(draw); }; // 启动动画循环 draw(); // 清理函数:在组件卸载时取消动画 return () => { if (animationFrameRef.current) { cancelAnimationFrame(animationFrameRef.current); } }; }, [frequencies, isActive, updateHistory]); return ( <div className={styles["voice-print"]}> <canvas ref={canvasRef} /> </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/voice-print/index.ts
app/components/voice-print/index.ts
export * from "./voice-print";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/realtime-chat/realtime-chat.tsx
app/components/realtime-chat/realtime-chat.tsx
import VoiceIcon from "@/app/icons/voice.svg"; import VoiceOffIcon from "@/app/icons/voice-off.svg"; import PowerIcon from "@/app/icons/power.svg"; import styles from "./realtime-chat.module.scss"; import clsx from "clsx"; import { useState, useRef, useEffect } from "react"; import { useChatStore, createMessage, useAppConfig } from "@/app/store"; import { IconButton } from "@/app/components/button"; import { Modality, RTClient, RTInputAudioItem, RTResponse, TurnDetection, } from "rt-client"; import { AudioHandler } from "@/app/lib/audio"; import { uploadImage } from "@/app/utils/chat"; import { VoicePrint } from "@/app/components/voice-print"; interface RealtimeChatProps { onClose?: () => void; onStartVoice?: () => void; onPausedVoice?: () => void; } export function RealtimeChat({ onClose, onStartVoice, onPausedVoice, }: RealtimeChatProps) { const chatStore = useChatStore(); const session = chatStore.currentSession(); const config = useAppConfig(); const [status, setStatus] = useState(""); const [isRecording, setIsRecording] = useState(false); const [isConnected, setIsConnected] = useState(false); const [isConnecting, setIsConnecting] = useState(false); const [modality, setModality] = useState("audio"); const [useVAD, setUseVAD] = useState(true); const [frequencies, setFrequencies] = useState<Uint8Array | undefined>(); const clientRef = useRef<RTClient | null>(null); const audioHandlerRef = useRef<AudioHandler | null>(null); const initRef = useRef(false); const temperature = config.realtimeConfig.temperature; const apiKey = config.realtimeConfig.apiKey; const model = config.realtimeConfig.model; const azure = config.realtimeConfig.provider === "Azure"; const azureEndpoint = config.realtimeConfig.azure.endpoint; const azureDeployment = config.realtimeConfig.azure.deployment; const voice = config.realtimeConfig.voice; const handleConnect = async () => { if (isConnecting) return; if (!isConnected) { try { setIsConnecting(true); clientRef.current = azure ? new RTClient( new URL(azureEndpoint), { key: apiKey }, { deployment: azureDeployment }, ) : new RTClient({ key: apiKey }, { model }); const modalities: Modality[] = modality === "audio" ? ["text", "audio"] : ["text"]; const turnDetection: TurnDetection = useVAD ? { type: "server_vad" } : null; await clientRef.current.configure({ instructions: "", voice, input_audio_transcription: { model: "whisper-1" }, turn_detection: turnDetection, tools: [], temperature, modalities, }); startResponseListener(); setIsConnected(true); // TODO // try { // const recentMessages = chatStore.getMessagesWithMemory(); // for (const message of recentMessages) { // const { role, content } = message; // if (typeof content === "string") { // await clientRef.current.sendItem({ // type: "message", // role: role as any, // content: [ // { // type: (role === "assistant" ? "text" : "input_text") as any, // text: content as string, // }, // ], // }); // } // } // // await clientRef.current.generateResponse(); // } catch (error) { // console.error("Set message failed:", error); // } } catch (error) { console.error("Connection failed:", error); setStatus("Connection failed"); } finally { setIsConnecting(false); } } else { await disconnect(); } }; const disconnect = async () => { if (clientRef.current) { try { await clientRef.current.close(); clientRef.current = null; setIsConnected(false); } catch (error) { console.error("Disconnect failed:", error); } } }; const startResponseListener = async () => { if (!clientRef.current) return; try { for await (const serverEvent of clientRef.current.events()) { if (serverEvent.type === "response") { await handleResponse(serverEvent); } else if (serverEvent.type === "input_audio") { await handleInputAudio(serverEvent); } } } catch (error) { if (clientRef.current) { console.error("Response iteration error:", error); } } }; const handleResponse = async (response: RTResponse) => { for await (const item of response) { if (item.type === "message" && item.role === "assistant") { const botMessage = createMessage({ role: item.role, content: "", }); // add bot message first chatStore.updateTargetSession(session, (session) => { session.messages = session.messages.concat([botMessage]); }); let hasAudio = false; for await (const content of item) { if (content.type === "text") { for await (const text of content.textChunks()) { botMessage.content += text; } } else if (content.type === "audio") { const textTask = async () => { for await (const text of content.transcriptChunks()) { botMessage.content += text; } }; const audioTask = async () => { audioHandlerRef.current?.startStreamingPlayback(); for await (const audio of content.audioChunks()) { hasAudio = true; audioHandlerRef.current?.playChunk(audio); } }; await Promise.all([textTask(), audioTask()]); } // update message.content chatStore.updateTargetSession(session, (session) => { session.messages = session.messages.concat(); }); } if (hasAudio) { // upload audio get audio_url const blob = audioHandlerRef.current?.savePlayFile(); uploadImage(blob!).then((audio_url) => { botMessage.audio_url = audio_url; // update text and audio_url chatStore.updateTargetSession(session, (session) => { session.messages = session.messages.concat(); }); }); } } } }; const handleInputAudio = async (item: RTInputAudioItem) => { await item.waitForCompletion(); if (item.transcription) { const userMessage = createMessage({ role: "user", content: item.transcription, }); chatStore.updateTargetSession(session, (session) => { session.messages = session.messages.concat([userMessage]); }); // save input audio_url, and update session const { audioStartMillis, audioEndMillis } = item; // upload audio get audio_url const blob = audioHandlerRef.current?.saveRecordFile( audioStartMillis, audioEndMillis, ); uploadImage(blob!).then((audio_url) => { userMessage.audio_url = audio_url; chatStore.updateTargetSession(session, (session) => { session.messages = session.messages.concat(); }); }); } // stop streaming play after get input audio. audioHandlerRef.current?.stopStreamingPlayback(); }; const toggleRecording = async () => { if (!isRecording && clientRef.current) { try { if (!audioHandlerRef.current) { audioHandlerRef.current = new AudioHandler(); await audioHandlerRef.current.initialize(); } await audioHandlerRef.current.startRecording(async (chunk) => { await clientRef.current?.sendAudio(chunk); }); setIsRecording(true); } catch (error) { console.error("Failed to start recording:", error); } } else if (audioHandlerRef.current) { try { audioHandlerRef.current.stopRecording(); if (!useVAD) { const inputAudio = await clientRef.current?.commitAudio(); await handleInputAudio(inputAudio!); await clientRef.current?.generateResponse(); } setIsRecording(false); } catch (error) { console.error("Failed to stop recording:", error); } } }; useEffect(() => { // 防止重复初始化 if (initRef.current) return; initRef.current = true; const initAudioHandler = async () => { const handler = new AudioHandler(); await handler.initialize(); audioHandlerRef.current = handler; await handleConnect(); await toggleRecording(); }; initAudioHandler().catch((error) => { setStatus(error); console.error(error); }); return () => { if (isRecording) { toggleRecording(); } audioHandlerRef.current?.close().catch(console.error); disconnect(); }; }, []); useEffect(() => { let animationFrameId: number; if (isConnected && isRecording) { const animationFrame = () => { if (audioHandlerRef.current) { const freqData = audioHandlerRef.current.getByteFrequencyData(); setFrequencies(freqData); } animationFrameId = requestAnimationFrame(animationFrame); }; animationFrameId = requestAnimationFrame(animationFrame); } else { setFrequencies(undefined); } return () => { if (animationFrameId) { cancelAnimationFrame(animationFrameId); } }; }, [isConnected, isRecording]); // update session params useEffect(() => { clientRef.current?.configure({ voice }); }, [voice]); useEffect(() => { clientRef.current?.configure({ temperature }); }, [temperature]); const handleClose = async () => { onClose?.(); if (isRecording) { await toggleRecording(); } disconnect().catch(console.error); }; return ( <div className={styles["realtime-chat"]}> <div className={clsx(styles["circle-mic"], { [styles["pulse"]]: isRecording, })} > <VoicePrint frequencies={frequencies} isActive={isRecording} /> </div> <div className={styles["bottom-icons"]}> <div> <IconButton icon={isRecording ? <VoiceIcon /> : <VoiceOffIcon />} onClick={toggleRecording} disabled={!isConnected} shadow bordered /> </div> <div className={styles["icon-center"]}>{status}</div> <div> <IconButton icon={<PowerIcon />} onClick={handleClose} shadow bordered /> </div> </div> </div> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/realtime-chat/index.ts
app/components/realtime-chat/index.ts
export * from "./realtime-chat";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/components/realtime-chat/realtime-config.tsx
app/components/realtime-chat/realtime-config.tsx
import { RealtimeConfig } from "@/app/store"; import Locale from "@/app/locales"; import { ListItem, Select, PasswordInput } from "@/app/components/ui-lib"; import { InputRange } from "@/app/components/input-range"; import { Voice } from "rt-client"; import { ServiceProvider } from "@/app/constant"; const providers = [ServiceProvider.OpenAI, ServiceProvider.Azure]; const models = ["gpt-4o-realtime-preview-2024-10-01"]; const voice = ["alloy", "shimmer", "echo"]; export function RealtimeConfigList(props: { realtimeConfig: RealtimeConfig; updateConfig: (updater: (config: RealtimeConfig) => void) => void; }) { const azureConfigComponent = props.realtimeConfig.provider === ServiceProvider.Azure && ( <> <ListItem title={Locale.Settings.Realtime.Azure.Endpoint.Title} subTitle={Locale.Settings.Realtime.Azure.Endpoint.SubTitle} > <input value={props.realtimeConfig?.azure?.endpoint} type="text" placeholder={Locale.Settings.Realtime.Azure.Endpoint.Title} onChange={(e) => { props.updateConfig( (config) => (config.azure.endpoint = e.currentTarget.value), ); }} /> </ListItem> <ListItem title={Locale.Settings.Realtime.Azure.Deployment.Title} subTitle={Locale.Settings.Realtime.Azure.Deployment.SubTitle} > <input value={props.realtimeConfig?.azure?.deployment} type="text" placeholder={Locale.Settings.Realtime.Azure.Deployment.Title} onChange={(e) => { props.updateConfig( (config) => (config.azure.deployment = e.currentTarget.value), ); }} /> </ListItem> </> ); return ( <> <ListItem title={Locale.Settings.Realtime.Enable.Title} subTitle={Locale.Settings.Realtime.Enable.SubTitle} > <input type="checkbox" checked={props.realtimeConfig.enable} onChange={(e) => props.updateConfig( (config) => (config.enable = e.currentTarget.checked), ) } ></input> </ListItem> {props.realtimeConfig.enable && ( <> <ListItem title={Locale.Settings.Realtime.Provider.Title} subTitle={Locale.Settings.Realtime.Provider.SubTitle} > <Select aria-label={Locale.Settings.Realtime.Provider.Title} value={props.realtimeConfig.provider} onChange={(e) => { props.updateConfig( (config) => (config.provider = e.target.value as ServiceProvider), ); }} > {providers.map((v, i) => ( <option value={v} key={i}> {v} </option> ))} </Select> </ListItem> <ListItem title={Locale.Settings.Realtime.Model.Title} subTitle={Locale.Settings.Realtime.Model.SubTitle} > <Select aria-label={Locale.Settings.Realtime.Model.Title} value={props.realtimeConfig.model} onChange={(e) => { props.updateConfig((config) => (config.model = e.target.value)); }} > {models.map((v, i) => ( <option value={v} key={i}> {v} </option> ))} </Select> </ListItem> <ListItem title={Locale.Settings.Realtime.ApiKey.Title} subTitle={Locale.Settings.Realtime.ApiKey.SubTitle} > <PasswordInput aria={Locale.Settings.ShowPassword} aria-label={Locale.Settings.Realtime.ApiKey.Title} value={props.realtimeConfig.apiKey} type="text" placeholder={Locale.Settings.Realtime.ApiKey.Placeholder} onChange={(e) => { props.updateConfig( (config) => (config.apiKey = e.currentTarget.value), ); }} /> </ListItem> {azureConfigComponent} <ListItem title={Locale.Settings.TTS.Voice.Title} subTitle={Locale.Settings.TTS.Voice.SubTitle} > <Select value={props.realtimeConfig.voice} onChange={(e) => { props.updateConfig( (config) => (config.voice = e.currentTarget.value as Voice), ); }} > {voice.map((v, i) => ( <option value={v} key={i}> {v} </option> ))} </Select> </ListItem> <ListItem title={Locale.Settings.Realtime.Temperature.Title} subTitle={Locale.Settings.Realtime.Temperature.SubTitle} > <InputRange aria={Locale.Settings.Temperature.Title} value={props.realtimeConfig?.temperature?.toFixed(1)} min="0.6" max="1" step="0.1" onChange={(e) => { props.updateConfig( (config) => (config.temperature = e.currentTarget.valueAsNumber), ); }} ></InputRange> </ListItem> </> )} </> ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/auth-settings-events.ts
app/utils/auth-settings-events.ts
import { sendGAEvent } from "@next/third-parties/google"; export function trackConversationGuideToCPaymentClick() { sendGAEvent("event", "ConversationGuideToCPaymentClick", { value: 1 }); } export function trackAuthorizationPageButtonToCPaymentClick() { sendGAEvent("event", "AuthorizationPageButtonToCPaymentClick", { value: 1 }); } export function trackAuthorizationPageBannerToCPaymentClick() { sendGAEvent("event", "AuthorizationPageBannerToCPaymentClick", { value: 1, }); } export function trackSettingsPageGuideToCPaymentClick() { sendGAEvent("event", "SettingsPageGuideToCPaymentClick", { value: 1 }); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/indexedDB-storage.ts
app/utils/indexedDB-storage.ts
import { StateStorage } from "zustand/middleware"; import { get, set, del, clear } from "idb-keyval"; import { safeLocalStorage } from "@/app/utils"; const localStorage = safeLocalStorage(); class IndexedDBStorage implements StateStorage { public async getItem(name: string): Promise<string | null> { try { const value = (await get(name)) || localStorage.getItem(name); return value; } catch (error) { return localStorage.getItem(name); } } public async setItem(name: string, value: string): Promise<void> { try { const _value = JSON.parse(value); if (!_value?.state?._hasHydrated) { console.warn("skip setItem", name); return; } await set(name, value); } catch (error) { localStorage.setItem(name, value); } } public async removeItem(name: string): Promise<void> { try { await del(name); } catch (error) { localStorage.removeItem(name); } } public async clear(): Promise<void> { try { await clear(); } catch (error) { localStorage.clear(); } } } export const indexedDBStorage = new IndexedDBStorage();
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/chat.ts
app/utils/chat.ts
import { CACHE_URL_PREFIX, UPLOAD_URL, REQUEST_TIMEOUT_MS, } from "@/app/constant"; import { MultimodalContent, RequestMessage } from "@/app/client/api"; import Locale from "@/app/locales"; import { EventStreamContentType, fetchEventSource, } from "@fortaine/fetch-event-source"; import { prettyObject } from "./format"; import { fetch as tauriFetch } from "./stream"; export function compressImage(file: Blob, maxSize: number): Promise<string> { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = (readerEvent: any) => { const image = new Image(); image.onload = () => { let canvas = document.createElement("canvas"); let ctx = canvas.getContext("2d"); let width = image.width; let height = image.height; let quality = 0.9; let dataUrl; do { canvas.width = width; canvas.height = height; ctx?.clearRect(0, 0, canvas.width, canvas.height); ctx?.drawImage(image, 0, 0, width, height); dataUrl = canvas.toDataURL("image/jpeg", quality); if (dataUrl.length < maxSize) break; if (quality > 0.5) { // Prioritize quality reduction quality -= 0.1; } else { // Then reduce the size width *= 0.9; height *= 0.9; } } while (dataUrl.length > maxSize); resolve(dataUrl); }; image.onerror = reject; image.src = readerEvent.target.result; }; reader.onerror = reject; if (file.type.includes("heic")) { try { const heic2any = require("heic2any"); heic2any({ blob: file, toType: "image/jpeg" }) .then((blob: Blob) => { reader.readAsDataURL(blob); }) .catch((e: any) => { reject(e); }); } catch (e) { reject(e); } } reader.readAsDataURL(file); }); } export async function preProcessImageContentBase( content: RequestMessage["content"], transformImageUrl: (url: string) => Promise<{ [key: string]: any }>, ) { if (typeof content === "string") { return content; } const result = []; for (const part of content) { if (part?.type == "image_url" && part?.image_url?.url) { try { const url = await cacheImageToBase64Image(part?.image_url?.url); result.push(await transformImageUrl(url)); } catch (error) { console.error("Error processing image URL:", error); } } else { result.push({ ...part }); } } return result; } export async function preProcessImageContent( content: RequestMessage["content"], ) { return preProcessImageContentBase(content, async (url) => ({ type: "image_url", image_url: { url }, })) as Promise<MultimodalContent[] | string>; } export async function preProcessImageContentForAlibabaDashScope( content: RequestMessage["content"], ) { return preProcessImageContentBase(content, async (url) => ({ image: url, })); } const imageCaches: Record<string, string> = {}; export function cacheImageToBase64Image(imageUrl: string) { if (imageUrl.includes(CACHE_URL_PREFIX)) { if (!imageCaches[imageUrl]) { const reader = new FileReader(); return fetch(imageUrl, { method: "GET", mode: "cors", credentials: "include", }) .then((res) => res.blob()) .then( async (blob) => (imageCaches[imageUrl] = await compressImage(blob, 256 * 1024)), ); // compressImage } return Promise.resolve(imageCaches[imageUrl]); } return Promise.resolve(imageUrl); } export function base64Image2Blob(base64Data: string, contentType: string) { const byteCharacters = atob(base64Data); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); return new Blob([byteArray], { type: contentType }); } export function uploadImage(file: Blob): Promise<string> { if (!window._SW_ENABLED) { // if serviceWorker register error, using compressImage return compressImage(file, 256 * 1024); } const body = new FormData(); body.append("file", file); return fetch(UPLOAD_URL, { method: "post", body, mode: "cors", credentials: "include", }) .then((res) => res.json()) .then((res) => { // console.log("res", res); if (res?.code == 0 && res?.data) { return res?.data; } throw Error(`upload Error: ${res?.msg}`); }); } export function removeImage(imageUrl: string) { return fetch(imageUrl, { method: "DELETE", mode: "cors", credentials: "include", }); } export function stream( chatPath: string, requestPayload: any, headers: any, tools: any[], funcs: Record<string, Function>, controller: AbortController, parseSSE: (text: string, runTools: any[]) => string | undefined, processToolMessage: ( requestPayload: any, toolCallMessage: any, toolCallResult: any[], ) => void, options: any, ) { let responseText = ""; let remainText = ""; let finished = false; let running = false; let runTools: any[] = []; let responseRes: Response; // animate response to make it looks smooth function animateResponseText() { if (finished || controller.signal.aborted) { responseText += remainText; console.log("[Response Animation] finished"); if (responseText?.length === 0) { options.onError?.(new Error("empty response from server")); } return; } if (remainText.length > 0) { const fetchCount = Math.max(1, Math.round(remainText.length / 60)); const fetchText = remainText.slice(0, fetchCount); responseText += fetchText; remainText = remainText.slice(fetchCount); options.onUpdate?.(responseText, fetchText); } requestAnimationFrame(animateResponseText); } // start animaion animateResponseText(); const finish = () => { if (!finished) { if (!running && runTools.length > 0) { const toolCallMessage = { role: "assistant", tool_calls: [...runTools], }; running = true; runTools.splice(0, runTools.length); // empty runTools return Promise.all( toolCallMessage.tool_calls.map((tool) => { options?.onBeforeTool?.(tool); return Promise.resolve( // @ts-ignore funcs[tool.function.name]( // @ts-ignore tool?.function?.arguments ? JSON.parse(tool?.function?.arguments) : {}, ), ) .then((res) => { let content = res.data || res?.statusText; // hotfix #5614 content = typeof content === "string" ? content : JSON.stringify(content); if (res.status >= 300) { return Promise.reject(content); } return content; }) .then((content) => { options?.onAfterTool?.({ ...tool, content, isError: false, }); return content; }) .catch((e) => { options?.onAfterTool?.({ ...tool, isError: true, errorMsg: e.toString(), }); return e.toString(); }) .then((content) => ({ name: tool.function.name, role: "tool", content, tool_call_id: tool.id, })); }), ).then((toolCallResult) => { processToolMessage(requestPayload, toolCallMessage, toolCallResult); setTimeout(() => { // call again console.debug("[ChatAPI] restart"); running = false; chatApi(chatPath, headers, requestPayload, tools); // call fetchEventSource }, 60); }); return; } if (running) { return; } console.debug("[ChatAPI] end"); finished = true; options.onFinish(responseText + remainText, responseRes); // 将res传递给onFinish } }; controller.signal.onabort = finish; function chatApi( chatPath: string, headers: any, requestPayload: any, tools: any, ) { const chatPayload = { method: "POST", body: JSON.stringify({ ...requestPayload, tools: tools && tools.length ? tools : undefined, }), signal: controller.signal, headers, }; const requestTimeoutId = setTimeout( () => controller.abort(), REQUEST_TIMEOUT_MS, ); fetchEventSource(chatPath, { fetch: tauriFetch as any, ...chatPayload, async onopen(res) { clearTimeout(requestTimeoutId); const contentType = res.headers.get("content-type"); console.log("[Request] response content type: ", contentType); responseRes = res; if (contentType?.startsWith("text/plain")) { responseText = await res.clone().text(); return finish(); } if ( !res.ok || !res.headers .get("content-type") ?.startsWith(EventStreamContentType) || res.status !== 200 ) { const responseTexts = [responseText]; let extraInfo = await res.clone().text(); try { const resJson = await res.clone().json(); extraInfo = prettyObject(resJson); } catch {} if (res.status === 401) { responseTexts.push(Locale.Error.Unauthorized); } if (extraInfo) { responseTexts.push(extraInfo); } responseText = responseTexts.join("\n\n"); return finish(); } }, onmessage(msg) { if (msg.data === "[DONE]" || finished) { return finish(); } const text = msg.data; // Skip empty messages if (!text || text.trim().length === 0) { return; } try { const chunk = parseSSE(text, runTools); if (chunk) { remainText += chunk; } } catch (e) { console.error("[Request] parse error", text, msg, e); } }, onclose() { finish(); }, onerror(e) { options?.onError?.(e); throw e; }, openWhenHidden: true, }); } console.debug("[ChatAPI] start"); chatApi(chatPath, headers, requestPayload, tools); // call fetchEventSource } export function streamWithThink( chatPath: string, requestPayload: any, headers: any, tools: any[], funcs: Record<string, Function>, controller: AbortController, parseSSE: ( text: string, runTools: any[], ) => { isThinking: boolean; content: string | undefined; }, processToolMessage: ( requestPayload: any, toolCallMessage: any, toolCallResult: any[], ) => void, options: any, ) { let responseText = ""; let remainText = ""; let finished = false; let running = false; let runTools: any[] = []; let responseRes: Response; let isInThinkingMode = false; let lastIsThinking = false; let lastIsThinkingTagged = false; //between <think> and </think> tags // animate response to make it looks smooth function animateResponseText() { if (finished || controller.signal.aborted) { responseText += remainText; console.log("[Response Animation] finished"); if (responseText?.length === 0) { options.onError?.(new Error("empty response from server")); } return; } if (remainText.length > 0) { const fetchCount = Math.max(1, Math.round(remainText.length / 60)); const fetchText = remainText.slice(0, fetchCount); responseText += fetchText; remainText = remainText.slice(fetchCount); options.onUpdate?.(responseText, fetchText); } requestAnimationFrame(animateResponseText); } // start animaion animateResponseText(); const finish = () => { if (!finished) { if (!running && runTools.length > 0) { const toolCallMessage = { role: "assistant", tool_calls: [...runTools], }; running = true; runTools.splice(0, runTools.length); // empty runTools return Promise.all( toolCallMessage.tool_calls.map((tool) => { options?.onBeforeTool?.(tool); return Promise.resolve( // @ts-ignore funcs[tool.function.name]( // @ts-ignore tool?.function?.arguments ? JSON.parse(tool?.function?.arguments) : {}, ), ) .then((res) => { let content = res.data || res?.statusText; // hotfix #5614 content = typeof content === "string" ? content : JSON.stringify(content); if (res.status >= 300) { return Promise.reject(content); } return content; }) .then((content) => { options?.onAfterTool?.({ ...tool, content, isError: false, }); return content; }) .catch((e) => { options?.onAfterTool?.({ ...tool, isError: true, errorMsg: e.toString(), }); return e.toString(); }) .then((content) => ({ name: tool.function.name, role: "tool", content, tool_call_id: tool.id, })); }), ).then((toolCallResult) => { processToolMessage(requestPayload, toolCallMessage, toolCallResult); setTimeout(() => { // call again console.debug("[ChatAPI] restart"); running = false; chatApi(chatPath, headers, requestPayload, tools); // call fetchEventSource }, 60); }); return; } if (running) { return; } console.debug("[ChatAPI] end"); finished = true; options.onFinish(responseText + remainText, responseRes); } }; controller.signal.onabort = finish; function chatApi( chatPath: string, headers: any, requestPayload: any, tools: any, ) { const chatPayload = { method: "POST", body: JSON.stringify({ ...requestPayload, tools: tools && tools.length ? tools : undefined, }), signal: controller.signal, headers, }; const requestTimeoutId = setTimeout( () => controller.abort(), REQUEST_TIMEOUT_MS, ); fetchEventSource(chatPath, { fetch: tauriFetch as any, ...chatPayload, async onopen(res) { clearTimeout(requestTimeoutId); const contentType = res.headers.get("content-type"); console.log("[Request] response content type: ", contentType); responseRes = res; if (contentType?.startsWith("text/plain")) { responseText = await res.clone().text(); return finish(); } if ( !res.ok || !res.headers .get("content-type") ?.startsWith(EventStreamContentType) || res.status !== 200 ) { const responseTexts = [responseText]; let extraInfo = await res.clone().text(); try { const resJson = await res.clone().json(); extraInfo = prettyObject(resJson); } catch {} if (res.status === 401) { responseTexts.push(Locale.Error.Unauthorized); } if (extraInfo) { responseTexts.push(extraInfo); } responseText = responseTexts.join("\n\n"); return finish(); } }, onmessage(msg) { if (msg.data === "[DONE]" || finished) { return finish(); } const text = msg.data; // Skip empty messages if (!text || text.trim().length === 0) { return; } try { const chunk = parseSSE(text, runTools); // Skip if content is empty if (!chunk?.content || chunk.content.length === 0) { return; } // deal with <think> and </think> tags start if (!chunk.isThinking) { if (chunk.content.startsWith("<think>")) { chunk.isThinking = true; chunk.content = chunk.content.slice(7).trim(); lastIsThinkingTagged = true; } else if (chunk.content.endsWith("</think>")) { chunk.isThinking = false; chunk.content = chunk.content.slice(0, -8).trim(); lastIsThinkingTagged = false; } else if (lastIsThinkingTagged) { chunk.isThinking = true; } } // deal with <think> and </think> tags start // Check if thinking mode changed const isThinkingChanged = lastIsThinking !== chunk.isThinking; lastIsThinking = chunk.isThinking; if (chunk.isThinking) { // If in thinking mode if (!isInThinkingMode || isThinkingChanged) { // If this is a new thinking block or mode changed, add prefix isInThinkingMode = true; if (remainText.length > 0) { remainText += "\n"; } remainText += "> " + chunk.content; } else { // Handle newlines in thinking content if (chunk.content.includes("\n\n")) { const lines = chunk.content.split("\n\n"); remainText += lines.join("\n\n> "); } else { remainText += chunk.content; } } } else { // If in normal mode if (isInThinkingMode || isThinkingChanged) { // If switching from thinking mode to normal mode isInThinkingMode = false; remainText += "\n\n" + chunk.content; } else { remainText += chunk.content; } } } catch (e) { console.error("[Request] parse error", text, msg, e); // Don't throw error for parse failures, just log them } }, onclose() { finish(); }, onerror(e) { options?.onError?.(e); throw e; }, openWhenHidden: true, }); } console.debug("[ChatAPI] start"); chatApi(chatPath, headers, requestPayload, tools); // call fetchEventSource }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/sync.ts
app/utils/sync.ts
import { ChatSession, useAccessStore, useAppConfig, useChatStore, } from "../store"; import { useMaskStore } from "../store/mask"; import { usePromptStore } from "../store/prompt"; import { StoreKey } from "../constant"; import { merge } from "./merge"; type NonFunctionKeys<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? never : K; }[keyof T]; type NonFunctionFields<T> = Pick<T, NonFunctionKeys<T>>; export function getNonFunctionFileds<T extends object>(obj: T) { const ret: any = {}; Object.entries(obj).map(([k, v]) => { if (typeof v !== "function") { ret[k] = v; } }); return ret as NonFunctionFields<T>; } export type GetStoreState<T> = T extends { getState: () => infer U } ? NonFunctionFields<U> : never; const LocalStateSetters = { [StoreKey.Chat]: useChatStore.setState, [StoreKey.Access]: useAccessStore.setState, [StoreKey.Config]: useAppConfig.setState, [StoreKey.Mask]: useMaskStore.setState, [StoreKey.Prompt]: usePromptStore.setState, } as const; const LocalStateGetters = { [StoreKey.Chat]: () => getNonFunctionFileds(useChatStore.getState()), [StoreKey.Access]: () => getNonFunctionFileds(useAccessStore.getState()), [StoreKey.Config]: () => getNonFunctionFileds(useAppConfig.getState()), [StoreKey.Mask]: () => getNonFunctionFileds(useMaskStore.getState()), [StoreKey.Prompt]: () => getNonFunctionFileds(usePromptStore.getState()), } as const; export type AppState = { [k in keyof typeof LocalStateGetters]: ReturnType< (typeof LocalStateGetters)[k] >; }; type Merger<T extends keyof AppState, U = AppState[T]> = ( localState: U, remoteState: U, ) => U; type StateMerger = { [K in keyof AppState]: Merger<K>; }; // we merge remote state to local state const MergeStates: StateMerger = { [StoreKey.Chat]: (localState, remoteState) => { // merge sessions const localSessions: Record<string, ChatSession> = {}; localState.sessions.forEach((s) => (localSessions[s.id] = s)); remoteState.sessions.forEach((remoteSession) => { // skip empty chats if (remoteSession.messages.length === 0) return; const localSession = localSessions[remoteSession.id]; if (!localSession) { // if remote session is new, just merge it localState.sessions.push(remoteSession); } else { // if both have the same session id, merge the messages const localMessageIds = new Set(localSession.messages.map((v) => v.id)); remoteSession.messages.forEach((m) => { if (!localMessageIds.has(m.id)) { localSession.messages.push(m); } }); // sort local messages with date field in asc order localSession.messages.sort( (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(), ); } }); // sort local sessions with date field in desc order localState.sessions.sort( (a, b) => new Date(b.lastUpdate).getTime() - new Date(a.lastUpdate).getTime(), ); return localState; }, [StoreKey.Prompt]: (localState, remoteState) => { localState.prompts = { ...remoteState.prompts, ...localState.prompts, }; return localState; }, [StoreKey.Mask]: (localState, remoteState) => { localState.masks = { ...remoteState.masks, ...localState.masks, }; return localState; }, [StoreKey.Config]: mergeWithUpdate<AppState[StoreKey.Config]>, [StoreKey.Access]: mergeWithUpdate<AppState[StoreKey.Access]>, }; export function getLocalAppState() { const appState = Object.fromEntries( Object.entries(LocalStateGetters).map(([key, getter]) => { return [key, getter()]; }), ) as AppState; return appState; } export function setLocalAppState(appState: AppState) { Object.entries(LocalStateSetters).forEach(([key, setter]) => { setter(appState[key as keyof AppState]); }); } export function mergeAppState(localState: AppState, remoteState: AppState) { Object.keys(localState).forEach(<T extends keyof AppState>(k: string) => { const key = k as T; const localStoreState = localState[key]; const remoteStoreState = remoteState[key]; MergeStates[key](localStoreState, remoteStoreState); }); return localState; } /** * Merge state with `lastUpdateTime`, older state will be override */ export function mergeWithUpdate<T extends { lastUpdateTime?: number }>( localState: T, remoteState: T, ) { const localUpdateTime = localState.lastUpdateTime ?? 0; const remoteUpdateTime = localState.lastUpdateTime ?? 1; if (localUpdateTime < remoteUpdateTime) { merge(remoteState, localState); return { ...remoteState }; } else { merge(localState, remoteState); return { ...localState }; } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/model.ts
app/utils/model.ts
import { DEFAULT_MODELS, ServiceProvider } from "../constant"; import { LLMModel } from "../client/api"; const CustomSeq = { val: -1000, //To ensure the custom model located at front, start from -1000, refer to constant.ts cache: new Map<string, number>(), next: (id: string) => { if (CustomSeq.cache.has(id)) { return CustomSeq.cache.get(id) as number; } else { let seq = CustomSeq.val++; CustomSeq.cache.set(id, seq); return seq; } }, }; const customProvider = (providerName: string) => ({ id: providerName.toLowerCase(), providerName: providerName, providerType: "custom", sorted: CustomSeq.next(providerName), }); /** * Sorts an array of models based on specified rules. * * First, sorted by provider; if the same, sorted by model */ const sortModelTable = (models: ReturnType<typeof collectModels>) => models.sort((a, b) => { if (a.provider && b.provider) { let cmp = a.provider.sorted - b.provider.sorted; return cmp === 0 ? a.sorted - b.sorted : cmp; } else { return a.sorted - b.sorted; } }); /** * get model name and provider from a formatted string, * e.g. `gpt-4@OpenAi` or `claude-3-5-sonnet@20240620@Google` * @param modelWithProvider model name with provider separated by last `@` char, * @returns [model, provider] tuple, if no `@` char found, provider is undefined */ export function getModelProvider(modelWithProvider: string): [string, string?] { const [model, provider] = modelWithProvider.split(/@(?!.*@)/); return [model, provider]; } export function collectModelTable( models: readonly LLMModel[], customModels: string, ) { const modelTable: Record< string, { available: boolean; name: string; displayName: string; sorted: number; provider?: LLMModel["provider"]; // Marked as optional isDefault?: boolean; } > = {}; // default models models.forEach((m) => { // using <modelName>@<providerId> as fullName modelTable[`${m.name}@${m?.provider?.id}`] = { ...m, displayName: m.name, // 'provider' is copied over if it exists }; }); // server custom models customModels .split(",") .filter((v) => !!v && v.length > 0) .forEach((m) => { const available = !m.startsWith("-"); const nameConfig = m.startsWith("+") || m.startsWith("-") ? m.slice(1) : m; let [name, displayName] = nameConfig.split("="); // enable or disable all models if (name === "all") { Object.values(modelTable).forEach( (model) => (model.available = available), ); } else { // 1. find model by name, and set available value const [customModelName, customProviderName] = getModelProvider(name); let count = 0; for (const fullName in modelTable) { const [modelName, providerName] = getModelProvider(fullName); if ( customModelName == modelName && (customProviderName === undefined || customProviderName === providerName) ) { count += 1; modelTable[fullName]["available"] = available; // swap name and displayName for bytedance if (providerName === "bytedance") { [name, displayName] = [displayName, modelName]; modelTable[fullName]["name"] = name; } if (displayName) { modelTable[fullName]["displayName"] = displayName; } } } // 2. if model not exists, create new model with available value if (count === 0) { let [customModelName, customProviderName] = getModelProvider(name); const provider = customProvider( customProviderName || customModelName, ); // swap name and displayName for bytedance if (displayName && provider.providerName == "ByteDance") { [customModelName, displayName] = [displayName, customModelName]; } modelTable[`${customModelName}@${provider?.id}`] = { name: customModelName, displayName: displayName || customModelName, available, provider, // Use optional chaining sorted: CustomSeq.next(`${customModelName}@${provider?.id}`), }; } } }); return modelTable; } export function collectModelTableWithDefaultModel( models: readonly LLMModel[], customModels: string, defaultModel: string, ) { let modelTable = collectModelTable(models, customModels); if (defaultModel && defaultModel !== "") { if (defaultModel.includes("@")) { if (defaultModel in modelTable) { modelTable[defaultModel].isDefault = true; } } else { for (const key of Object.keys(modelTable)) { if ( modelTable[key].available && getModelProvider(key)[0] == defaultModel ) { modelTable[key].isDefault = true; break; } } } } return modelTable; } /** * Generate full model table. */ export function collectModels( models: readonly LLMModel[], customModels: string, ) { const modelTable = collectModelTable(models, customModels); let allModels = Object.values(modelTable); allModels = sortModelTable(allModels); return allModels; } export function collectModelsWithDefaultModel( models: readonly LLMModel[], customModels: string, defaultModel: string, ) { const modelTable = collectModelTableWithDefaultModel( models, customModels, defaultModel, ); let allModels = Object.values(modelTable); allModels = sortModelTable(allModels); return allModels; } export function isModelAvailableInServer( customModels: string, modelName: string, providerName: string, ) { const fullName = `${modelName}@${providerName}`; const modelTable = collectModelTable(DEFAULT_MODELS, customModels); return modelTable[fullName]?.available === false; } /** * Check if the model name is a GPT-4 related model * * @param modelName The name of the model to check * @returns True if the model is a GPT-4 related model (excluding gpt-4o-mini) */ export function isGPT4Model(modelName: string): boolean { return ( (modelName.startsWith("gpt-4") || modelName.startsWith("chatgpt-4o") || modelName.startsWith("o1")) && !modelName.startsWith("gpt-4o-mini") ); } /** * Checks if a model is not available on any of the specified providers in the server. * * @param {string} customModels - A string of custom models, comma-separated. * @param {string} modelName - The name of the model to check. * @param {string|string[]} providerNames - A string or array of provider names to check against. * * @returns {boolean} True if the model is not available on any of the specified providers, false otherwise. */ export function isModelNotavailableInServer( customModels: string, modelName: string, providerNames: string | string[], ): boolean { // Check DISABLE_GPT4 environment variable if ( process.env.DISABLE_GPT4 === "1" && isGPT4Model(modelName.toLowerCase()) ) { return true; } const modelTable = collectModelTable(DEFAULT_MODELS, customModels); const providerNamesArray = Array.isArray(providerNames) ? providerNames : [providerNames]; for (const providerName of providerNamesArray) { // if model provider is bytedance, use model config name to check if not avaliable if (providerName === ServiceProvider.ByteDance) { return !Object.values(modelTable).filter((v) => v.name === modelName)?.[0] ?.available; } const fullName = `${modelName}@${providerName.toLowerCase()}`; if (modelTable?.[fullName]?.available === true) return false; } return true; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/ms_edge_tts.ts
app/utils/ms_edge_tts.ts
// import axios from "axios"; import { Buffer } from "buffer"; import { randomBytes } from "crypto"; import { Readable } from "stream"; // Modified according to https://github.com/Migushthe2nd/MsEdgeTTS /** * https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-synthesis-markup-voice#:~:text=Optional-,volume,-Indicates%20the%20volume */ export enum VOLUME { SILENT = "silent", X_SOFT = "x-soft", SOFT = "soft", MEDIUM = "medium", LOUD = "loud", X_LOUD = "x-LOUD", DEFAULT = "default", } /** * https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-synthesis-markup-voice#:~:text=Optional-,rate,-Indicates%20the%20speaking */ export enum RATE { X_SLOW = "x-slow", SLOW = "slow", MEDIUM = "medium", FAST = "fast", X_FAST = "x-fast", DEFAULT = "default", } /** * https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-synthesis-markup-voice#:~:text=Optional-,pitch,-Indicates%20the%20baseline */ export enum PITCH { X_LOW = "x-low", LOW = "low", MEDIUM = "medium", HIGH = "high", X_HIGH = "x-high", DEFAULT = "default", } /** * Only a few of the [possible formats](https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/rest-text-to-speech#audio-outputs) are accepted. */ export enum OUTPUT_FORMAT { // Streaming ============================= // AMR_WB_16000HZ = "amr-wb-16000hz", // AUDIO_16KHZ_16BIT_32KBPS_MONO_OPUS = "audio-16khz-16bit-32kbps-mono-opus", // AUDIO_16KHZ_32KBITRATE_MONO_MP3 = "audio-16khz-32kbitrate-mono-mp3", // AUDIO_16KHZ_64KBITRATE_MONO_MP3 = "audio-16khz-64kbitrate-mono-mp3", // AUDIO_16KHZ_128KBITRATE_MONO_MP3 = "audio-16khz-128kbitrate-mono-mp3", // AUDIO_24KHZ_16BIT_24KBPS_MONO_OPUS = "audio-24khz-16bit-24kbps-mono-opus", // AUDIO_24KHZ_16BIT_48KBPS_MONO_OPUS = "audio-24khz-16bit-48kbps-mono-opus", AUDIO_24KHZ_48KBITRATE_MONO_MP3 = "audio-24khz-48kbitrate-mono-mp3", AUDIO_24KHZ_96KBITRATE_MONO_MP3 = "audio-24khz-96kbitrate-mono-mp3", // AUDIO_24KHZ_160KBITRATE_MONO_MP3 = "audio-24khz-160kbitrate-mono-mp3", // AUDIO_48KHZ_96KBITRATE_MONO_MP3 = "audio-48khz-96kbitrate-mono-mp3", // AUDIO_48KHZ_192KBITRATE_MONO_MP3 = "audio-48khz-192kbitrate-mono-mp3", // OGG_16KHZ_16BIT_MONO_OPUS = "ogg-16khz-16bit-mono-opus", // OGG_24KHZ_16BIT_MONO_OPUS = "ogg-24khz-16bit-mono-opus", // OGG_48KHZ_16BIT_MONO_OPUS = "ogg-48khz-16bit-mono-opus", // RAW_8KHZ_8BIT_MONO_ALAW = "raw-8khz-8bit-mono-alaw", // RAW_8KHZ_8BIT_MONO_MULAW = "raw-8khz-8bit-mono-mulaw", // RAW_8KHZ_16BIT_MONO_PCM = "raw-8khz-16bit-mono-pcm", // RAW_16KHZ_16BIT_MONO_PCM = "raw-16khz-16bit-mono-pcm", // RAW_16KHZ_16BIT_MONO_TRUESILK = "raw-16khz-16bit-mono-truesilk", // RAW_22050HZ_16BIT_MONO_PCM = "raw-22050hz-16bit-mono-pcm", // RAW_24KHZ_16BIT_MONO_PCM = "raw-24khz-16bit-mono-pcm", // RAW_24KHZ_16BIT_MONO_TRUESILK = "raw-24khz-16bit-mono-truesilk", // RAW_44100HZ_16BIT_MONO_PCM = "raw-44100hz-16bit-mono-pcm", // RAW_48KHZ_16BIT_MONO_PCM = "raw-48khz-16bit-mono-pcm", // WEBM_16KHZ_16BIT_MONO_OPUS = "webm-16khz-16bit-mono-opus", // WEBM_24KHZ_16BIT_24KBPS_MONO_OPUS = "webm-24khz-16bit-24kbps-mono-opus", WEBM_24KHZ_16BIT_MONO_OPUS = "webm-24khz-16bit-mono-opus", // Non-streaming ============================= // RIFF_8KHZ_8BIT_MONO_ALAW = "riff-8khz-8bit-mono-alaw", // RIFF_8KHZ_8BIT_MONO_MULAW = "riff-8khz-8bit-mono-mulaw", // RIFF_8KHZ_16BIT_MONO_PCM = "riff-8khz-16bit-mono-pcm", // RIFF_22050HZ_16BIT_MONO_PCM = "riff-22050hz-16bit-mono-pcm", // RIFF_24KHZ_16BIT_MONO_PCM = "riff-24khz-16bit-mono-pcm", // RIFF_44100HZ_16BIT_MONO_PCM = "riff-44100hz-16bit-mono-pcm", // RIFF_48KHZ_16BIT_MONO_PCM = "riff-48khz-16bit-mono-pcm", } export type Voice = { Name: string; ShortName: string; Gender: string; Locale: string; SuggestedCodec: string; FriendlyName: string; Status: string; }; export class ProsodyOptions { /** * The pitch to use. * Can be any {@link PITCH}, or a relative frequency in Hz (+50Hz), a relative semitone (+2st), or a relative percentage (+50%). * [SSML documentation](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-synthesis-markup-voice#:~:text=Optional-,pitch,-Indicates%20the%20baseline) */ pitch?: PITCH | string = "+0Hz"; /** * The rate to use. * Can be any {@link RATE}, or a relative number (0.5), or string with a relative percentage (+50%). * [SSML documentation](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-synthesis-markup-voice#:~:text=Optional-,rate,-Indicates%20the%20speaking) */ rate?: RATE | string | number = 1.0; /** * The volume to use. * Can be any {@link VOLUME}, or an absolute number (0, 100), a string with a relative number (+50), or a relative percentage (+50%). * [SSML documentation](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-synthesis-markup-voice#:~:text=Optional-,volume,-Indicates%20the%20volume) */ volume?: VOLUME | string | number = 100.0; } export class MsEdgeTTS { static OUTPUT_FORMAT = OUTPUT_FORMAT; private static TRUSTED_CLIENT_TOKEN = "6A5AA1D4EAFF4E9FB37E23D68491D6F4"; private static VOICES_URL = `https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list?trustedclienttoken=${MsEdgeTTS.TRUSTED_CLIENT_TOKEN}`; private static SYNTH_URL = `wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken=${MsEdgeTTS.TRUSTED_CLIENT_TOKEN}`; private static BINARY_DELIM = "Path:audio\r\n"; private static VOICE_LANG_REGEX = /\w{2}-\w{2}/; private readonly _enableLogger; private _ws: WebSocket | undefined; private _voice: any; private _voiceLocale: any; private _outputFormat: any; private _streams: { [key: string]: Readable } = {}; private _startTime = 0; private _log(...o: any[]) { if (this._enableLogger) { console.log(...o); } } /** * Create a new `MsEdgeTTS` instance. * * @param agent (optional, **NOT SUPPORTED IN BROWSER**) Use a custom http.Agent implementation like [https-proxy-agent](https://github.com/TooTallNate/proxy-agents) or [socks-proxy-agent](https://github.com/TooTallNate/proxy-agents/tree/main/packages/socks-proxy-agent). * @param enableLogger=false whether to enable the built-in logger. This logs connections inits, disconnects, and incoming data to the console */ public constructor(enableLogger: boolean = false) { this._enableLogger = enableLogger; } private async _send(message: any) { for (let i = 1; i <= 3 && this._ws!.readyState !== this._ws!.OPEN; i++) { if (i == 1) { this._startTime = Date.now(); } this._log("connecting: ", i); await this._initClient(); } this._ws!.send(message); } private _initClient() { this._ws = new WebSocket(MsEdgeTTS.SYNTH_URL); this._ws.binaryType = "arraybuffer"; return new Promise((resolve, reject) => { this._ws!.onopen = () => { this._log( "Connected in", (Date.now() - this._startTime) / 1000, "seconds", ); this._send( `Content-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n { "context": { "synthesis": { "audio": { "metadataoptions": { "sentenceBoundaryEnabled": "false", "wordBoundaryEnabled": "false" }, "outputFormat": "${this._outputFormat}" } } } } `, ).then(resolve); }; this._ws!.onmessage = (m: any) => { const buffer = Buffer.from(m.data as ArrayBuffer); const message = buffer.toString(); const requestId = /X-RequestId:(.*?)\r\n/gm.exec(message)![1]; if (message.includes("Path:turn.start")) { // start of turn, ignore } else if (message.includes("Path:turn.end")) { // end of turn, close stream this._streams[requestId].push(null); } else if (message.includes("Path:response")) { // context response, ignore } else if ( message.includes("Path:audio") && m.data instanceof ArrayBuffer ) { this._pushAudioData(buffer, requestId); } else { this._log("UNKNOWN MESSAGE", message); } }; this._ws!.onclose = () => { this._log( "disconnected after:", (Date.now() - this._startTime) / 1000, "seconds", ); for (const requestId in this._streams) { this._streams[requestId].push(null); } }; this._ws!.onerror = function (error: any) { reject("Connect Error: " + error); }; }); } private _pushAudioData(audioBuffer: Buffer, requestId: string) { const audioStartIndex = audioBuffer.indexOf(MsEdgeTTS.BINARY_DELIM) + MsEdgeTTS.BINARY_DELIM.length; const audioData = audioBuffer.subarray(audioStartIndex); this._streams[requestId].push(audioData); this._log("received audio chunk, size: ", audioData?.length); } private _SSMLTemplate(input: string, options: ProsodyOptions = {}): string { // in case future updates to the edge API block these elements, we'll be concatenating strings. options = { ...new ProsodyOptions(), ...options }; return `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="${this._voiceLocale}"> <voice name="${this._voice}"> <prosody pitch="${options.pitch}" rate="${options.rate}" volume="${options.volume}"> ${input} </prosody> </voice> </speak>`; } /** * Fetch the list of voices available in Microsoft Edge. * These, however, are not all. The complete list of voices supported by this module [can be found here](https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/language-support) (neural, standard, and preview). */ // getVoices(): Promise<Voice[]> { // return new Promise((resolve, reject) => { // axios // .get(MsEdgeTTS.VOICES_URL) // .then((res) => resolve(res.data)) // .catch(reject); // }); // } getVoices(): Promise<Voice[]> { return fetch(MsEdgeTTS.VOICES_URL) .then((response) => { if (!response.ok) { throw new Error("Network response was not ok"); } return response.json(); }) .then((data) => data as Voice[]) .catch((error) => { throw error; }); } /** * Sets the required information for the speech to be synthesised and inits a new WebSocket connection. * Must be called at least once before text can be synthesised. * Saved in this instance. Can be called at any time times to update the metadata. * * @param voiceName a string with any `ShortName`. A list of all available neural voices can be found [here](https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/language-support#neural-voices). However, it is not limited to neural voices: standard voices can also be used. A list of standard voices can be found [here](https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/language-support#standard-voices) * @param outputFormat any {@link OUTPUT_FORMAT} * @param voiceLocale (optional) any voice locale that is supported by the voice. See the list of all voices for compatibility. If not provided, the locale will be inferred from the `voiceName` */ async setMetadata( voiceName: string, outputFormat: OUTPUT_FORMAT, voiceLocale?: string, ) { const oldVoice = this._voice; const oldVoiceLocale = this._voiceLocale; const oldOutputFormat = this._outputFormat; this._voice = voiceName; this._voiceLocale = voiceLocale; if (!this._voiceLocale) { const voiceLangMatch = MsEdgeTTS.VOICE_LANG_REGEX.exec(this._voice); if (!voiceLangMatch) throw new Error("Could not infer voiceLocale from voiceName!"); this._voiceLocale = voiceLangMatch[0]; } this._outputFormat = outputFormat; const changed = oldVoice !== this._voice || oldVoiceLocale !== this._voiceLocale || oldOutputFormat !== this._outputFormat; // create new client if (changed || this._ws!.readyState !== this._ws!.OPEN) { this._startTime = Date.now(); await this._initClient(); } } private _metadataCheck() { if (!this._ws) throw new Error( "Speech synthesis not configured yet. Run setMetadata before calling toStream or toFile.", ); } /** * Close the WebSocket connection. */ close() { this._ws!.close(); } /** * Writes raw audio synthesised from text in real-time to a {@link Readable}. Uses a basic {@link _SSMLTemplate SML template}. * * @param input the text to synthesise. Can include SSML elements. * @param options (optional) {@link ProsodyOptions} * @returns {Readable} - a `stream.Readable` with the audio data */ toStream(input: string, options?: ProsodyOptions): Readable { const { stream } = this._rawSSMLRequest(this._SSMLTemplate(input, options)); return stream; } toArrayBuffer(input: string, options?: ProsodyOptions): Promise<ArrayBuffer> { return new Promise((resolve, reject) => { let data: Uint8Array[] = []; const readable = this.toStream(input, options); readable.on("data", (chunk) => { data.push(chunk); }); readable.on("end", () => { resolve(Buffer.concat(data).buffer); }); readable.on("error", (err) => { reject(err); }); }); } /** * Writes raw audio synthesised from a request in real-time to a {@link Readable}. Has no SSML template. Basic SSML should be provided in the request. * * @param requestSSML the SSML to send. SSML elements required in order to work. * @returns {Readable} - a `stream.Readable` with the audio data */ rawToStream(requestSSML: string): Readable { const { stream } = this._rawSSMLRequest(requestSSML); return stream; } private _rawSSMLRequest(requestSSML: string): { stream: Readable; requestId: string; } { this._metadataCheck(); const requestId = randomBytes(16).toString("hex"); const request = `X-RequestId:${requestId}\r\nContent-Type:application/ssml+xml\r\nPath:ssml\r\n\r\n ` + requestSSML.trim(); // https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/speech-synthesis-markup const self = this; const stream = new Readable({ read() {}, destroy(error: Error | null, callback: (error: Error | null) => void) { delete self._streams[requestId]; callback(error); }, }); this._streams[requestId] = stream; this._send(request).then(); return { stream, requestId }; } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/merge.ts
app/utils/merge.ts
export function merge(target: any, source: any) { Object.keys(source).forEach(function (key) { if ( source.hasOwnProperty(key) && // Check if the property is not inherited source[key] && typeof source[key] === "object" || key === "__proto__" || key === "constructor" ) { merge((target[key] = target[key] || {}), source[key]); return; } target[key] = source[key]; }); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/clone.ts
app/utils/clone.ts
export function deepClone<T>(obj: T) { return JSON.parse(JSON.stringify(obj)); } export function ensure<T extends object>( obj: T, keys: Array<[keyof T][number]>, ) { return keys.every( (k) => obj[k] !== undefined && obj[k] !== null && obj[k] !== "", ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/stream.ts
app/utils/stream.ts
// using tauri command to send request // see src-tauri/src/stream.rs, and src-tauri/src/main.rs // 1. invoke('stream_fetch', {url, method, headers, body}), get response with headers. // 2. listen event: `stream-response` multi times to get body type ResponseEvent = { id: number; payload: { request_id: number; status?: number; chunk?: number[]; }; }; type StreamResponse = { request_id: number; status: number; status_text: string; headers: Record<string, string>; }; export function fetch(url: string, options?: RequestInit): Promise<Response> { if (window.__TAURI__) { const { signal, method = "GET", headers: _headers = {}, body = [], } = options || {}; let unlisten: Function | undefined; let setRequestId: Function | undefined; const requestIdPromise = new Promise((resolve) => (setRequestId = resolve)); const ts = new TransformStream(); const writer = ts.writable.getWriter(); let closed = false; const close = () => { if (closed) return; closed = true; unlisten && unlisten(); writer.ready.then(() => { writer.close().catch((e) => console.error(e)); }); }; if (signal) { signal.addEventListener("abort", () => close()); } // @ts-ignore 2. listen response multi times, and write to Response.body window.__TAURI__.event .listen("stream-response", (e: ResponseEvent) => requestIdPromise.then((request_id) => { const { request_id: rid, chunk, status } = e?.payload || {}; if (request_id != rid) { return; } if (chunk) { writer.ready.then(() => { writer.write(new Uint8Array(chunk)); }); } else if (status === 0) { // end of body close(); } }), ) .then((u: Function) => (unlisten = u)); const headers: Record<string, string> = { Accept: "application/json, text/plain, */*", "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7", "User-Agent": navigator.userAgent, }; for (const item of new Headers(_headers || {})) { headers[item[0]] = item[1]; } return window.__TAURI__ .invoke("stream_fetch", { method: method.toUpperCase(), url, headers, // TODO FormData body: typeof body === "string" ? Array.from(new TextEncoder().encode(body)) : [], }) .then((res: StreamResponse) => { const { request_id, status, status_text: statusText, headers } = res; setRequestId?.(request_id); const response = new Response(ts.readable, { status, statusText, headers, }); if (status >= 300) { setTimeout(close, 100); } return response; }) .catch((e) => { console.error("stream error", e); // throw e; return new Response("", { status: 599 }); }); } return window.fetch(url, options); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/token.ts
app/utils/token.ts
export function estimateTokenLength(input: string): number { let tokenLength = 0; for (let i = 0; i < input.length; i++) { const charCode = input.charCodeAt(i); if (charCode < 128) { // ASCII character if (charCode <= 122 && charCode >= 65) { // a-Z tokenLength += 0.25; } else { tokenLength += 0.5; } } else { // Unicode character tokenLength += 1.5; } } return tokenLength; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/hmac.ts
app/utils/hmac.ts
// From https://gist.github.com/guillermodlpa/f6d955f838e9b10d1ef95b8e259b2c58 // From https://gist.github.com/stevendesu/2d52f7b5e1f1184af3b667c0b5e054b8 // To ensure cross-browser support even without a proper SubtleCrypto // impelmentation (or without access to the impelmentation, as is the case with // Chrome loaded over HTTP instead of HTTPS), this library can create SHA-256 // HMAC signatures using nothing but raw JavaScript /* eslint-disable no-magic-numbers, id-length, no-param-reassign, new-cap */ // By giving internal functions names that we can mangle, future calls to // them are reduced to a single byte (minor space savings in minified file) const uint8Array = Uint8Array; const uint32Array = Uint32Array; const pow = Math.pow; // Will be initialized below // Using a Uint32Array instead of a simple array makes the minified code // a bit bigger (we lose our `unshift()` hack), but comes with huge // performance gains const DEFAULT_STATE = new uint32Array(8); const ROUND_CONSTANTS: number[] = []; // Reusable object for expanded message // Using a Uint32Array instead of a simple array makes the minified code // 7 bytes larger, but comes with huge performance gains const M = new uint32Array(64); // After minification the code to compute the default state and round // constants is smaller than the output. More importantly, this serves as a // good educational aide for anyone wondering where the magic numbers come // from. No magic numbers FTW! function getFractionalBits(n: number) { return ((n - (n | 0)) * pow(2, 32)) | 0; } let n = 2; let nPrime = 0; while (nPrime < 64) { // isPrime() was in-lined from its original function form to save // a few bytes let isPrime = true; // Math.sqrt() was replaced with pow(n, 1/2) to save a few bytes // var sqrtN = pow(n, 1 / 2); // So technically to determine if a number is prime you only need to // check numbers up to the square root. However this function only runs // once and we're only computing the first 64 primes (up to 311), so on // any modern CPU this whole function runs in a couple milliseconds. // By going to n / 2 instead of sqrt(n) we net 8 byte savings and no // scaling performance cost for (let factor = 2; factor <= n / 2; factor++) { if (n % factor === 0) { isPrime = false; } } if (isPrime) { if (nPrime < 8) { DEFAULT_STATE[nPrime] = getFractionalBits(pow(n, 1 / 2)); } ROUND_CONSTANTS[nPrime] = getFractionalBits(pow(n, 1 / 3)); nPrime++; } n++; } // For cross-platform support we need to ensure that all 32-bit words are // in the same endianness. A UTF-8 TextEncoder will return BigEndian data, // so upon reading or writing to our ArrayBuffer we'll only swap the bytes // if our system is LittleEndian (which is about 99% of CPUs) const LittleEndian = !!new uint8Array(new uint32Array([1]).buffer)[0]; function convertEndian(word: number) { if (LittleEndian) { return ( // byte 1 -> byte 4 (word >>> 24) | // byte 2 -> byte 3 (((word >>> 16) & 0xff) << 8) | // byte 3 -> byte 2 ((word & 0xff00) << 8) | // byte 4 -> byte 1 (word << 24) ); } else { return word; } } function rightRotate(word: number, bits: number) { return (word >>> bits) | (word << (32 - bits)); } function sha256(data: Uint8Array) { // Copy default state const STATE = DEFAULT_STATE.slice(); // Caching this reduces occurrences of ".length" in minified JavaScript // 3 more byte savings! :D const legth = data.length; // Pad data const bitLength = legth * 8; const newBitLength = 512 - ((bitLength + 64) % 512) - 1 + bitLength + 65; // "bytes" and "words" are stored BigEndian const bytes = new uint8Array(newBitLength / 8); const words = new uint32Array(bytes.buffer); bytes.set(data, 0); // Append a 1 bytes[legth] = 0b10000000; // Store length in BigEndian words[words.length - 1] = convertEndian(bitLength); // Loop iterator (avoid two instances of "var") -- saves 2 bytes let round; // Process blocks (512 bits / 64 bytes / 16 words at a time) for (let block = 0; block < newBitLength / 32; block += 16) { const workingState = STATE.slice(); // Rounds for (round = 0; round < 64; round++) { let MRound; // Expand message if (round < 16) { // Convert to platform Endianness for later math MRound = convertEndian(words[block + round]); } else { const gamma0x = M[round - 15]; const gamma1x = M[round - 2]; MRound = M[round - 7] + M[round - 16] + (rightRotate(gamma0x, 7) ^ rightRotate(gamma0x, 18) ^ (gamma0x >>> 3)) + (rightRotate(gamma1x, 17) ^ rightRotate(gamma1x, 19) ^ (gamma1x >>> 10)); } // M array matches platform endianness M[round] = MRound |= 0; // Computation const t1 = (rightRotate(workingState[4], 6) ^ rightRotate(workingState[4], 11) ^ rightRotate(workingState[4], 25)) + ((workingState[4] & workingState[5]) ^ (~workingState[4] & workingState[6])) + workingState[7] + MRound + ROUND_CONSTANTS[round]; const t2 = (rightRotate(workingState[0], 2) ^ rightRotate(workingState[0], 13) ^ rightRotate(workingState[0], 22)) + ((workingState[0] & workingState[1]) ^ (workingState[2] & (workingState[0] ^ workingState[1]))); for (let i = 7; i > 0; i--) { workingState[i] = workingState[i - 1]; } workingState[0] = (t1 + t2) | 0; workingState[4] = (workingState[4] + t1) | 0; } // Update state for (round = 0; round < 8; round++) { STATE[round] = (STATE[round] + workingState[round]) | 0; } } // Finally the state needs to be converted to BigEndian for output // And we want to return a Uint8Array, not a Uint32Array return new uint8Array( new uint32Array( STATE.map(function (val) { return convertEndian(val); }), ).buffer, ); } function hmac(key: Uint8Array, data: ArrayLike<number>) { if (key.length > 64) key = sha256(key); if (key.length < 64) { const tmp = new Uint8Array(64); tmp.set(key, 0); key = tmp; } // Generate inner and outer keys const innerKey = new Uint8Array(64); const outerKey = new Uint8Array(64); for (let i = 0; i < 64; i++) { innerKey[i] = 0x36 ^ key[i]; outerKey[i] = 0x5c ^ key[i]; } // Append the innerKey const msg = new Uint8Array(data.length + 64); msg.set(innerKey, 0); msg.set(data, 64); // Has the previous message and append the outerKey const result = new Uint8Array(64 + 32); result.set(outerKey, 0); result.set(sha256(msg), 64); // Hash the previous message return sha256(result); } // Convert a string to a Uint8Array, SHA-256 it, and convert back to string const encoder = new TextEncoder(); export function sign( inputKey: string | Uint8Array, inputData: string | Uint8Array, ) { const key = typeof inputKey === "string" ? encoder.encode(inputKey) : inputKey; const data = typeof inputData === "string" ? encoder.encode(inputData) : inputData; return hmac(key, data); } export function hex(bin: Uint8Array) { return bin.reduce((acc, val) => { const hexVal = "00" + val.toString(16); return acc + hexVal.substring(hexVal.length - 2); }, ""); } export function hash(str: string) { return hex(sha256(encoder.encode(str))); } export function hashWithSecret(str: string, secret: string) { return hex(sign(secret, str)).toString(); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/cloudflare.ts
app/utils/cloudflare.ts
export function cloudflareAIGatewayUrl(fetchUrl: string) { // rebuild fetchUrl, if using cloudflare ai gateway // document: https://developers.cloudflare.com/ai-gateway/providers/openai/ const paths = fetchUrl.split("/"); if ("gateway.ai.cloudflare.com" == paths[2]) { // is cloudflare.com ai gateway // https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/azure-openai/{resource_name}/{deployment_name}/chat/completions?api-version=2023-05-15' if ("azure-openai" == paths[6]) { // is azure gateway return paths.slice(0, 8).concat(paths.slice(-3)).join("/"); // rebuild ai gateway azure_url } // https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai/chat/completions if ("openai" == paths[6]) { // is openai gateway return paths.slice(0, 7).concat(paths.slice(-2)).join("/"); // rebuild ai gateway openai_url } // https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/anthropic/v1/messages \ if ("anthropic" == paths[6]) { // is anthropic gateway return paths.slice(0, 7).concat(paths.slice(-2)).join("/"); // rebuild ai gateway anthropic_url } // TODO: Amazon Bedrock, Groq, HuggingFace... } return fetchUrl; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/audio.ts
app/utils/audio.ts
type TTSPlayer = { init: () => void; play: (audioBuffer: ArrayBuffer, onended: () => void | null) => Promise<void>; stop: () => void; }; export function createTTSPlayer(): TTSPlayer { let audioContext: AudioContext | null = null; let audioBufferSourceNode: AudioBufferSourceNode | null = null; const init = () => { audioContext = new (window.AudioContext || window.webkitAudioContext)(); audioContext.suspend(); }; const play = async (audioBuffer: ArrayBuffer, onended: () => void | null) => { if (audioBufferSourceNode) { audioBufferSourceNode.stop(); audioBufferSourceNode.disconnect(); } const buffer = await audioContext!.decodeAudioData(audioBuffer); audioBufferSourceNode = audioContext!.createBufferSource(); audioBufferSourceNode.buffer = buffer; audioBufferSourceNode.connect(audioContext!.destination); audioContext!.resume().then(() => { audioBufferSourceNode!.start(); }); audioBufferSourceNode.onended = onended; }; const stop = () => { if (audioBufferSourceNode) { audioBufferSourceNode.stop(); audioBufferSourceNode.disconnect(); audioBufferSourceNode = null; } if (audioContext) { audioContext.close(); audioContext = null; } }; return { init, play, stop }; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/store.ts
app/utils/store.ts
import { create } from "zustand"; import { combine, persist, createJSONStorage } from "zustand/middleware"; import { Updater } from "../typing"; import { deepClone } from "./clone"; import { indexedDBStorage } from "@/app/utils/indexedDB-storage"; type SecondParam<T> = T extends ( _f: infer _F, _s: infer S, ...args: infer _U ) => any ? S : never; type MakeUpdater<T> = { lastUpdateTime: number; _hasHydrated: boolean; markUpdate: () => void; update: Updater<T>; setHasHydrated: (state: boolean) => void; }; type SetStoreState<T> = ( partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean | undefined, ) => void; export function createPersistStore<T extends object, M>( state: T, methods: ( set: SetStoreState<T & MakeUpdater<T>>, get: () => T & MakeUpdater<T>, ) => M, persistOptions: SecondParam<typeof persist<T & M & MakeUpdater<T>>>, ) { persistOptions.storage = createJSONStorage(() => indexedDBStorage); const oldOonRehydrateStorage = persistOptions?.onRehydrateStorage; persistOptions.onRehydrateStorage = (state) => { oldOonRehydrateStorage?.(state); return () => state.setHasHydrated(true); }; return create( persist( combine( { ...state, lastUpdateTime: 0, _hasHydrated: false, }, (set, get) => { return { ...methods(set, get as any), markUpdate() { set({ lastUpdateTime: Date.now() } as Partial< T & M & MakeUpdater<T> >); }, update(updater) { const state = deepClone(get()); updater(state); set({ ...state, lastUpdateTime: Date.now(), }); }, setHasHydrated: (state: boolean) => { set({ _hasHydrated: state } as Partial<T & M & MakeUpdater<T>>); }, } as M & MakeUpdater<T>; }, ), persistOptions as any, ), ); }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/tencent.ts
app/utils/tencent.ts
import { sign, hash as getHash, hex } from "./hmac"; // 使用 SHA-256 和 secret 进行 HMAC 加密 function sha256(message: any, secret: any, encoding?: string) { const result = sign(secret, message); return encoding == "hex" ? hex(result).toString() : result; } function getDate(timestamp: number) { const date = new Date(timestamp * 1000); const year = date.getUTCFullYear(); const month = ("0" + (date.getUTCMonth() + 1)).slice(-2); const day = ("0" + date.getUTCDate()).slice(-2); return `${year}-${month}-${day}`; } export async function getHeader( payload: any, SECRET_ID: string, SECRET_KEY: string, ) { // https://cloud.tencent.com/document/api/1729/105701 const endpoint = "hunyuan.tencentcloudapi.com"; const service = "hunyuan"; const region = ""; // optional const action = "ChatCompletions"; const version = "2023-09-01"; const timestamp = Math.floor(Date.now() / 1000); //时间处理, 获取世界时间日期 const date = getDate(timestamp); // ************* 步骤 1:拼接规范请求串 ************* const hashedRequestPayload = getHash(payload); const httpRequestMethod = "POST"; const contentType = "application/json"; const canonicalUri = "/"; const canonicalQueryString = ""; const canonicalHeaders = `content-type:${contentType}\n` + "host:" + endpoint + "\n" + "x-tc-action:" + action.toLowerCase() + "\n"; const signedHeaders = "content-type;host;x-tc-action"; const canonicalRequest = [ httpRequestMethod, canonicalUri, canonicalQueryString, canonicalHeaders, signedHeaders, hashedRequestPayload, ].join("\n"); // ************* 步骤 2:拼接待签名字符串 ************* const algorithm = "TC3-HMAC-SHA256"; const hashedCanonicalRequest = getHash(canonicalRequest); const credentialScope = date + "/" + service + "/" + "tc3_request"; const stringToSign = algorithm + "\n" + timestamp + "\n" + credentialScope + "\n" + hashedCanonicalRequest; // ************* 步骤 3:计算签名 ************* const kDate = sha256(date, "TC3" + SECRET_KEY); const kService = sha256(service, kDate); const kSigning = sha256("tc3_request", kService); const signature = sha256(stringToSign, kSigning, "hex"); // ************* 步骤 4:拼接 Authorization ************* const authorization = algorithm + " " + "Credential=" + SECRET_ID + "/" + credentialScope + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature; return { Authorization: authorization, "Content-Type": contentType, Host: endpoint, "X-TC-Action": action, "X-TC-Timestamp": timestamp.toString(), "X-TC-Version": version, "X-TC-Region": region, }; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/format.ts
app/utils/format.ts
export function prettyObject(msg: any) { const obj = msg; if (typeof msg !== "string") { msg = JSON.stringify(msg, null, " "); } if (msg === "{}") { return obj.toString(); } if (msg.startsWith("```json")) { return msg; } return ["```json", msg, "```"].join("\n"); } export function* chunks(s: string, maxBytes = 1000 * 1000) { const decoder = new TextDecoder("utf-8"); let buf = new TextEncoder().encode(s); while (buf.length) { let i = buf.lastIndexOf(32, maxBytes + 1); // If no space found, try forward search if (i < 0) i = buf.indexOf(32, maxBytes); // If there's no space at all, take all if (i < 0) i = buf.length; // This is a safe cut-off point; never half-way a multi-byte yield decoder.decode(buf.slice(0, i)); buf = buf.slice(i + 1); // Skip space (if any) } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/baidu.ts
app/utils/baidu.ts
import { BAIDU_OATUH_URL } from "../constant"; /** * 使用 AK,SK 生成鉴权签名(Access Token) * @return 鉴权签名信息 */ export async function getAccessToken( clientId: string, clientSecret: string, ): Promise<{ access_token: string; expires_in: number; error?: number; }> { const res = await fetch( `${BAIDU_OATUH_URL}?grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}`, { method: "POST", mode: "cors", }, ); const resJson = await res.json(); return resJson; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/object.ts
app/utils/object.ts
export function omit<T extends object, U extends (keyof T)[]>( obj: T, ...keys: U ): Omit<T, U[number]> { const ret: any = { ...obj }; keys.forEach((key) => delete ret[key]); return ret; } export function pick<T extends object, U extends (keyof T)[]>( obj: T, ...keys: U ): Pick<T, U[number]> { const ret: any = {}; keys.forEach((key) => (ret[key] = obj[key])); return ret; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/hooks.ts
app/utils/hooks.ts
import { useMemo } from "react"; import { useAccessStore, useAppConfig } from "../store"; import { collectModelsWithDefaultModel } from "./model"; export function useAllModels() { const accessStore = useAccessStore(); const configStore = useAppConfig(); const models = useMemo(() => { return collectModelsWithDefaultModel( configStore.models, [configStore.customModels, accessStore.customModels].join(","), accessStore.defaultModel, ); }, [ accessStore.customModels, accessStore.defaultModel, configStore.customModels, configStore.models, ]); return models; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/cloud/upstash.ts
app/utils/cloud/upstash.ts
import { STORAGE_KEY } from "@/app/constant"; import { SyncStore } from "@/app/store/sync"; import { chunks } from "../format"; export type UpstashConfig = SyncStore["upstash"]; export type UpStashClient = ReturnType<typeof createUpstashClient>; export function createUpstashClient(store: SyncStore) { const config = store.upstash; const storeKey = config.username.length === 0 ? STORAGE_KEY : config.username; const chunkCountKey = `${storeKey}-chunk-count`; const chunkIndexKey = (i: number) => `${storeKey}-chunk-${i}`; const proxyUrl = store.useProxy && store.proxyUrl.length > 0 ? store.proxyUrl : undefined; return { async check() { try { const res = await fetch(this.path(`get/${storeKey}`, proxyUrl), { method: "GET", headers: this.headers(), }); console.log("[Upstash] check", res.status, res.statusText); return [200].includes(res.status); } catch (e) { console.error("[Upstash] failed to check", e); } return false; }, async redisGet(key: string) { const res = await fetch(this.path(`get/${key}`, proxyUrl), { method: "GET", headers: this.headers(), }); console.log("[Upstash] get key = ", key, res.status, res.statusText); const resJson = (await res.json()) as { result: string }; return resJson.result; }, async redisSet(key: string, value: string) { const res = await fetch(this.path(`set/${key}`, proxyUrl), { method: "POST", headers: this.headers(), body: value, }); console.log("[Upstash] set key = ", key, res.status, res.statusText); }, async get() { const chunkCount = Number(await this.redisGet(chunkCountKey)); if (!Number.isInteger(chunkCount)) return; const chunks = await Promise.all( new Array(chunkCount) .fill(0) .map((_, i) => this.redisGet(chunkIndexKey(i))), ); console.log("[Upstash] get full chunks", chunks); return chunks.join(""); }, async set(_: string, value: string) { // upstash limit the max request size which is 1Mb for “Free” and “Pay as you go” // so we need to split the data to chunks let index = 0; for await (const chunk of chunks(value)) { await this.redisSet(chunkIndexKey(index), chunk); index += 1; } await this.redisSet(chunkCountKey, index.toString()); }, headers() { return { Authorization: `Bearer ${config.apiKey}`, }; }, path(path: string, proxyUrl: string = "") { if (!path.endsWith("/")) { path += "/"; } if (path.startsWith("/")) { path = path.slice(1); } if (proxyUrl.length > 0 && !proxyUrl.endsWith("/")) { proxyUrl += "/"; } let url; const pathPrefix = "/api/upstash/"; try { let u = new URL(proxyUrl + pathPrefix + path); // add query params u.searchParams.append("endpoint", config.endpoint); url = u.toString(); } catch (e) { url = pathPrefix + path + "?endpoint=" + config.endpoint; } return url; }, }; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/cloud/index.ts
app/utils/cloud/index.ts
import { createWebDavClient } from "./webdav"; import { createUpstashClient } from "./upstash"; export enum ProviderType { WebDAV = "webdav", UpStash = "upstash", } export const SyncClients = { [ProviderType.UpStash]: createUpstashClient, [ProviderType.WebDAV]: createWebDavClient, } as const; type SyncClientConfig = { [K in keyof typeof SyncClients]: (typeof SyncClients)[K] extends ( _: infer C, ) => any ? C : never; }; export type SyncClient = { get: (key: string) => Promise<string>; set: (key: string, value: string) => Promise<void>; check: () => Promise<boolean>; }; export function createSyncClient<T extends ProviderType>( provider: T, config: SyncClientConfig[T], ): SyncClient { return SyncClients[provider](config as any) as any; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/utils/cloud/webdav.ts
app/utils/cloud/webdav.ts
import { STORAGE_KEY } from "@/app/constant"; import { SyncStore } from "@/app/store/sync"; export type WebDAVConfig = SyncStore["webdav"]; export type WebDavClient = ReturnType<typeof createWebDavClient>; export function createWebDavClient(store: SyncStore) { const folder = STORAGE_KEY; const fileName = `${folder}/backup.json`; const config = store.webdav; const proxyUrl = store.useProxy && store.proxyUrl.length > 0 ? store.proxyUrl : undefined; return { async check() { try { const res = await fetch(this.path(folder, proxyUrl, "MKCOL"), { method: "GET", headers: this.headers(), }); const success = [201, 200, 404, 405, 301, 302, 307, 308].includes( res.status, ); console.log( `[WebDav] check ${success ? "success" : "failed"}, ${res.status} ${ res.statusText }`, ); return success; } catch (e) { console.error("[WebDav] failed to check", e); } return false; }, async get(key: string) { const res = await fetch(this.path(fileName, proxyUrl), { method: "GET", headers: this.headers(), }); console.log("[WebDav] get key = ", key, res.status, res.statusText); if (404 == res.status) { return ""; } return await res.text(); }, async set(key: string, value: string) { const res = await fetch(this.path(fileName, proxyUrl), { method: "PUT", headers: this.headers(), body: value, }); console.log("[WebDav] set key = ", key, res.status, res.statusText); }, headers() { const auth = btoa(config.username + ":" + config.password); return { authorization: `Basic ${auth}`, }; }, path(path: string, proxyUrl: string = "", proxyMethod: string = "") { if (path.startsWith("/")) { path = path.slice(1); } if (proxyUrl.endsWith("/")) { proxyUrl = proxyUrl.slice(0, -1); } let url; const pathPrefix = "/api/webdav/"; try { let u = new URL(proxyUrl + pathPrefix + path); // add query params u.searchParams.append("endpoint", config.endpoint); proxyMethod && u.searchParams.append("proxy_method", proxyMethod); url = u.toString(); } catch (e) { url = pathPrefix + path + "?endpoint=" + config.endpoint; if (proxyMethod) { url += "&proxy_method=" + proxyMethod; } } return url; }, }; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/anthropic.ts
app/api/anthropic.ts
import { getServerSideConfig } from "@/app/config/server"; import { ANTHROPIC_BASE_URL, Anthropic, ApiPath, ServiceProvider, ModelProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "./auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare"; const ALLOWD_PATH = new Set([Anthropic.ChatPath, Anthropic.ChatPath1]); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Anthropic Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const subpath = params.path.join("/"); if (!ALLOWD_PATH.has(subpath)) { console.log("[Anthropic Route] forbidden path ", subpath); return NextResponse.json( { error: true, msg: "you are not allowed to request " + subpath, }, { status: 403, }, ); } const authResult = auth(req, ModelProvider.Claude); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[Anthropic] ", e); return NextResponse.json(prettyObject(e)); } } const serverConfig = getServerSideConfig(); async function request(req: NextRequest) { const controller = new AbortController(); let authHeaderName = "x-api-key"; let authValue = req.headers.get(authHeaderName) || req.headers.get("Authorization")?.replaceAll("Bearer ", "").trim() || serverConfig.anthropicApiKey || ""; let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Anthropic, ""); let baseUrl = serverConfig.anthropicUrl || serverConfig.baseUrl || ANTHROPIC_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); // try rebuild url, when using cloudflare ai gateway in server const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}${path}`); const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", "Cache-Control": "no-store", "anthropic-dangerous-direct-browser-access": "true", [authHeaderName]: authValue, "anthropic-version": req.headers.get("anthropic-version") || serverConfig.anthropicApiVersion || Anthropic.Vision, }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.Anthropic as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[Anthropic] filter`, e); } } // console.log("[Anthropic request]", fetchOptions.headers, req.method); try { const res = await fetch(fetchUrl, fetchOptions); // console.log( // "[Anthropic response]", // res.status, // " ", // res.headers, // res.url, // ); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/glm.ts
app/api/glm.ts
import { getServerSideConfig } from "@/app/config/server"; import { CHATGLM_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[GLM Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.ChatGLM); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[GLM] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); // alibaba use base url or just remove the path let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.ChatGLM, ""); let baseUrl = serverConfig.chatglmUrl || CHATGLM_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; console.log("[Fetch Url] ", fetchUrl); const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.ChatGLM as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[GLM] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/bytedance.ts
app/api/bytedance.ts
import { getServerSideConfig } from "@/app/config/server"; import { BYTEDANCE_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[ByteDance Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.Doubao); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[ByteDance] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.ByteDance, ""); let baseUrl = serverConfig.bytedanceUrl || BYTEDANCE_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.ByteDance as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[ByteDance] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/deepseek.ts
app/api/deepseek.ts
import { getServerSideConfig } from "@/app/config/server"; import { DEEPSEEK_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[DeepSeek Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.DeepSeek); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[DeepSeek] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); // alibaba use base url or just remove the path let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.DeepSeek, ""); let baseUrl = serverConfig.deepseekUrl || DEEPSEEK_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.DeepSeek as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[DeepSeek] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/google.ts
app/api/google.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "./auth"; import { getServerSideConfig } from "@/app/config/server"; import { ApiPath, GEMINI_BASE_URL, ModelProvider } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { provider: string; path: string[] } }, ) { console.log("[Google Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.GeminiPro); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } const bearToken = req.headers.get("x-goog-api-key") || req.headers.get("Authorization") || ""; const token = bearToken.trim().replaceAll("Bearer ", "").trim(); const apiKey = token ? token : serverConfig.googleApiKey; if (!apiKey) { return NextResponse.json( { error: true, message: `missing GOOGLE_API_KEY in server env vars`, }, { status: 401, }, ); } try { const response = await request(req, apiKey); return response; } catch (e) { console.error("[Google] ", e); return NextResponse.json(prettyObject(e)); } } export const GET = handle; export const POST = handle; export const runtime = "edge"; export const preferredRegion = [ "bom1", "cle1", "cpt1", "gru1", "hnd1", "iad1", "icn1", "kix1", "pdx1", "sfo1", "sin1", "syd1", ]; async function request(req: NextRequest, apiKey: string) { const controller = new AbortController(); let baseUrl = serverConfig.googleUrl || GEMINI_BASE_URL; let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Google, ""); if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}${ req?.nextUrl?.searchParams?.get("alt") === "sse" ? "?alt=sse" : "" }`; console.log("[Fetch Url] ", fetchUrl); const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", "Cache-Control": "no-store", "x-goog-api-key": req.headers.get("x-goog-api-key") || (req.headers.get("Authorization") ?? "").replace("Bearer ", ""), }, method: req.method, body: req.body, // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/302ai.ts
app/api/302ai.ts
import { getServerSideConfig } from "@/app/config/server"; import { AI302_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[302.AI Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider["302.AI"]); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[302.AI] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); // alibaba use base url or just remove the path let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath["302.AI"], ""); let baseUrl = serverConfig.ai302Url || AI302_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider["302.AI"] as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[302.AI] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/openai.ts
app/api/openai.ts
import { type OpenAIListModelResponse } from "@/app/client/platforms/openai"; import { getServerSideConfig } from "@/app/config/server"; import { ModelProvider, OpenaiPath } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "./auth"; import { requestOpenai } from "./common"; const ALLOWED_PATH = new Set(Object.values(OpenaiPath)); function getModels(remoteModelRes: OpenAIListModelResponse) { const config = getServerSideConfig(); if (config.disableGPT4) { remoteModelRes.data = remoteModelRes.data.filter( (m) => !( m.id.startsWith("gpt-4") || m.id.startsWith("chatgpt-4o") || m.id.startsWith("o1") || m.id.startsWith("o3") ) || m.id.startsWith("gpt-4o-mini"), ); } return remoteModelRes; } export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[OpenAI Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const subpath = params.path.join("/"); if (!ALLOWED_PATH.has(subpath)) { console.log("[OpenAI Route] forbidden path ", subpath); return NextResponse.json( { error: true, msg: "you are not allowed to request " + subpath, }, { status: 403, }, ); } const authResult = auth(req, ModelProvider.GPT); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await requestOpenai(req); // list models if (subpath === OpenaiPath.ListModelPath && response.status === 200) { const resJson = (await response.json()) as OpenAIListModelResponse; const availableModels = getModels(resJson); return NextResponse.json(availableModels, { status: response.status, }); } return response; } catch (e) { console.error("[OpenAI] ", e); return NextResponse.json(prettyObject(e)); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/common.ts
app/api/common.ts
import { NextRequest, NextResponse } from "next/server"; import { getServerSideConfig } from "../config/server"; import { OPENAI_BASE_URL, ServiceProvider } from "../constant"; import { cloudflareAIGatewayUrl } from "../utils/cloudflare"; import { getModelProvider, isModelNotavailableInServer } from "../utils/model"; const serverConfig = getServerSideConfig(); export async function requestOpenai(req: NextRequest) { const controller = new AbortController(); const isAzure = req.nextUrl.pathname.includes("azure/deployments"); var authValue, authHeaderName = ""; if (isAzure) { authValue = req.headers .get("Authorization") ?.trim() .replaceAll("Bearer ", "") .trim() ?? ""; authHeaderName = "api-key"; } else { authValue = req.headers.get("Authorization") ?? ""; authHeaderName = "Authorization"; } let path = `${req.nextUrl.pathname}`.replaceAll("/api/openai/", ""); let baseUrl = (isAzure ? serverConfig.azureUrl : serverConfig.baseUrl) || OPENAI_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); if (isAzure) { const azureApiVersion = req?.nextUrl?.searchParams?.get("api-version") || serverConfig.azureApiVersion; baseUrl = baseUrl.split("/deployments").shift() as string; path = `${req.nextUrl.pathname.replaceAll( "/api/azure/", "", )}?api-version=${azureApiVersion}`; // Forward compatibility: // if display_name(deployment_name) not set, and '{deploy-id}' in AZURE_URL // then using default '{deploy-id}' if (serverConfig.customModels && serverConfig.azureUrl) { const modelName = path.split("/")[1]; let realDeployName = ""; serverConfig.customModels .split(",") .filter((v) => !!v && !v.startsWith("-") && v.includes(modelName)) .forEach((m) => { const [fullName, displayName] = m.split("="); const [_, providerName] = getModelProvider(fullName); if (providerName === "azure" && !displayName) { const [_, deployId] = (serverConfig?.azureUrl ?? "").split( "deployments/", ); if (deployId) { realDeployName = deployId; } } }); if (realDeployName) { console.log("[Replace with DeployId", realDeployName); path = path.replaceAll(modelName, realDeployName); } } } const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}/${path}`); console.log("fetchUrl", fetchUrl); const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", "Cache-Control": "no-store", [authHeaderName]: authValue, ...(serverConfig.openaiOrgId && { "OpenAI-Organization": serverConfig.openaiOrgId, }), }, method: req.method, body: req.body, // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse gpt4 request if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, [ ServiceProvider.OpenAI, ServiceProvider.Azure, jsonBody?.model as string, // support provider-unspecified model ], ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error("[OpenAI] gpt4 filter", e); } } try { const res = await fetch(fetchUrl, fetchOptions); // Extract the OpenAI-Organization header from the response const openaiOrganizationHeader = res.headers.get("OpenAI-Organization"); // Check if serverConfig.openaiOrgId is defined and not an empty string if (serverConfig.openaiOrgId && serverConfig.openaiOrgId.trim() !== "") { // If openaiOrganizationHeader is present, log it; otherwise, log that the header is not present console.log("[Org ID]", openaiOrganizationHeader); } else { console.log("[Org ID] is not set up."); } // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); // Conditionally delete the OpenAI-Organization header from the response if [Org ID] is undefined or empty (not setup in ENV) // Also, this is to prevent the header from being sent to the client if (!serverConfig.openaiOrgId || serverConfig.openaiOrgId.trim() === "") { newHeaders.delete("OpenAI-Organization"); } // The latest version of the OpenAI API forced the content-encoding to be "br" in json response // So if the streaming is disabled, we need to remove the content-encoding header // Because Vercel uses gzip to compress the response, if we don't remove the content-encoding header // The browser will try to decode the response with brotli and fail newHeaders.delete("content-encoding"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/auth.ts
app/api/auth.ts
import { NextRequest } from "next/server"; import { getServerSideConfig } from "../config/server"; import md5 from "spark-md5"; import { ACCESS_CODE_PREFIX, ModelProvider } from "../constant"; function getIP(req: NextRequest) { let ip = req.ip ?? req.headers.get("x-real-ip"); const forwardedFor = req.headers.get("x-forwarded-for"); if (!ip && forwardedFor) { ip = forwardedFor.split(",").at(0) ?? ""; } return ip; } function parseApiKey(bearToken: string) { const token = bearToken.trim().replaceAll("Bearer ", "").trim(); const isApiKey = !token.startsWith(ACCESS_CODE_PREFIX); return { accessCode: isApiKey ? "" : token.slice(ACCESS_CODE_PREFIX.length), apiKey: isApiKey ? token : "", }; } export function auth(req: NextRequest, modelProvider: ModelProvider) { const authToken = req.headers.get("Authorization") ?? ""; // check if it is openai api key or user token const { accessCode, apiKey } = parseApiKey(authToken); const hashedCode = md5.hash(accessCode ?? "").trim(); const serverConfig = getServerSideConfig(); console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]); console.log("[Auth] got access code:", accessCode); console.log("[Auth] hashed access code:", hashedCode); console.log("[User IP] ", getIP(req)); console.log("[Time] ", new Date().toLocaleString()); if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !apiKey) { return { error: true, msg: !accessCode ? "empty access code" : "wrong access code", }; } if (serverConfig.hideUserApiKey && !!apiKey) { return { error: true, msg: "you are not allowed to access with your own api key", }; } // if user does not provide an api key, inject system api key if (!apiKey) { const serverConfig = getServerSideConfig(); // const systemApiKey = // modelProvider === ModelProvider.GeminiPro // ? serverConfig.googleApiKey // : serverConfig.isAzure // ? serverConfig.azureApiKey // : serverConfig.apiKey; let systemApiKey: string | undefined; switch (modelProvider) { case ModelProvider.Stability: systemApiKey = serverConfig.stabilityApiKey; break; case ModelProvider.GeminiPro: systemApiKey = serverConfig.googleApiKey; break; case ModelProvider.Claude: systemApiKey = serverConfig.anthropicApiKey; break; case ModelProvider.Doubao: systemApiKey = serverConfig.bytedanceApiKey; break; case ModelProvider.Ernie: systemApiKey = serverConfig.baiduApiKey; break; case ModelProvider.Qwen: systemApiKey = serverConfig.alibabaApiKey; break; case ModelProvider.Moonshot: systemApiKey = serverConfig.moonshotApiKey; break; case ModelProvider.Iflytek: systemApiKey = serverConfig.iflytekApiKey + ":" + serverConfig.iflytekApiSecret; break; case ModelProvider.DeepSeek: systemApiKey = serverConfig.deepseekApiKey; break; case ModelProvider.XAI: systemApiKey = serverConfig.xaiApiKey; break; case ModelProvider.ChatGLM: systemApiKey = serverConfig.chatglmApiKey; break; case ModelProvider.SiliconFlow: systemApiKey = serverConfig.siliconFlowApiKey; break; case ModelProvider.GPT: default: if (req.nextUrl.pathname.includes("azure/deployments")) { systemApiKey = serverConfig.azureApiKey; } else { systemApiKey = serverConfig.apiKey; } } if (systemApiKey) { console.log("[Auth] use system api key"); req.headers.set("Authorization", `Bearer ${systemApiKey}`); } else { console.log("[Auth] admin did not provide an api key"); } } else { console.log("[Auth] use user api key"); } return { error: false, }; }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/azure.ts
app/api/azure.ts
import { ModelProvider } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "./auth"; import { requestOpenai } from "./common"; export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Azure Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const subpath = params.path.join("/"); const authResult = auth(req, ModelProvider.GPT); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { return await requestOpenai(req); } catch (e) { console.error("[Azure] ", e); return NextResponse.json(prettyObject(e)); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/proxy.ts
app/api/proxy.ts
import { NextRequest, NextResponse } from "next/server"; import { getServerSideConfig } from "@/app/config/server"; export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Proxy Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const serverConfig = getServerSideConfig(); // remove path params from searchParams req.nextUrl.searchParams.delete("path"); req.nextUrl.searchParams.delete("provider"); const subpath = params.path.join("/"); const fetchUrl = `${req.headers.get( "x-base-url", )}/${subpath}?${req.nextUrl.searchParams.toString()}`; const skipHeaders = ["connection", "host", "origin", "referer", "cookie"]; const headers = new Headers( Array.from(req.headers.entries()).filter((item) => { if ( item[0].indexOf("x-") > -1 || item[0].indexOf("sec-") > -1 || skipHeaders.includes(item[0]) ) { return false; } return true; }), ); // if dalle3 use openai api key const baseUrl = req.headers.get("x-base-url"); if (baseUrl?.includes("api.openai.com")) { if (!serverConfig.apiKey) { return NextResponse.json( { error: "OpenAI API key not configured" }, { status: 500 }, ); } headers.set("Authorization", `Bearer ${serverConfig.apiKey}`); } const controller = new AbortController(); const fetchOptions: RequestInit = { headers, method: req.method, body: req.body, // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); // The latest version of the OpenAI API forced the content-encoding to be "br" in json response // So if the streaming is disabled, we need to remove the content-encoding header // Because Vercel uses gzip to compress the response, if we don't remove the content-encoding header // The browser will try to decode the response with brotli and fail newHeaders.delete("content-encoding"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/moonshot.ts
app/api/moonshot.ts
import { getServerSideConfig } from "@/app/config/server"; import { MOONSHOT_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Moonshot Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.Moonshot); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[Moonshot] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); // alibaba use base url or just remove the path let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Moonshot, ""); let baseUrl = serverConfig.moonshotUrl || MOONSHOT_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.Moonshot as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[Moonshot] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/siliconflow.ts
app/api/siliconflow.ts
import { getServerSideConfig } from "@/app/config/server"; import { SILICONFLOW_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[SiliconFlow Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.SiliconFlow); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[SiliconFlow] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); // alibaba use base url or just remove the path let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.SiliconFlow, ""); let baseUrl = serverConfig.siliconFlowUrl || SILICONFLOW_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.SiliconFlow as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[SiliconFlow] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/xai.ts
app/api/xai.ts
import { getServerSideConfig } from "@/app/config/server"; import { XAI_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[XAI Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.XAI); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[XAI] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); // alibaba use base url or just remove the path let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.XAI, ""); let baseUrl = serverConfig.xaiUrl || XAI_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.XAI as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[XAI] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/baidu.ts
app/api/baidu.ts
import { getServerSideConfig } from "@/app/config/server"; import { BAIDU_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; import { getAccessToken } from "@/app/utils/baidu"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Baidu Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.Ernie); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } if (!serverConfig.baiduApiKey || !serverConfig.baiduSecretKey) { return NextResponse.json( { error: true, message: `missing BAIDU_API_KEY or BAIDU_SECRET_KEY in server env vars`, }, { status: 401, }, ); } try { const response = await request(req); return response; } catch (e) { console.error("[Baidu] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Baidu, ""); let baseUrl = serverConfig.baiduUrl || BAIDU_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const { access_token } = await getAccessToken( serverConfig.baiduApiKey as string, serverConfig.baiduSecretKey as string, ); const fetchUrl = `${baseUrl}${path}?access_token=${access_token}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.Baidu as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[Baidu] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/stability.ts
app/api/stability.ts
import { NextRequest, NextResponse } from "next/server"; import { getServerSideConfig } from "@/app/config/server"; import { ModelProvider, STABILITY_BASE_URL } from "@/app/constant"; import { auth } from "@/app/api/auth"; export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Stability] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const controller = new AbortController(); const serverConfig = getServerSideConfig(); let baseUrl = serverConfig.stabilityUrl || STABILITY_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } let path = `${req.nextUrl.pathname}`.replaceAll("/api/stability/", ""); console.log("[Stability Proxy] ", path); console.log("[Stability Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const authResult = auth(req, ModelProvider.Stability); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } const bearToken = req.headers.get("Authorization") ?? ""; const token = bearToken.trim().replaceAll("Bearer ", "").trim(); const key = token ? token : serverConfig.stabilityApiKey; if (!key) { return NextResponse.json( { error: true, message: `missing STABILITY_API_KEY in server env vars`, }, { status: 401, }, ); } const fetchUrl = `${baseUrl}/${path}`; console.log("[Stability Url] ", fetchUrl); const fetchOptions: RequestInit = { headers: { "Content-Type": req.headers.get("Content-Type") || "multipart/form-data", Accept: req.headers.get("Accept") || "application/json", Authorization: `Bearer ${key}`, }, method: req.method, body: req.body, // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/iflytek.ts
app/api/iflytek.ts
import { getServerSideConfig } from "@/app/config/server"; import { IFLYTEK_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; // iflytek const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Iflytek Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.Iflytek); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[Iflytek] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); // iflytek use base url or just remove the path let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Iflytek, ""); let baseUrl = serverConfig.iflytekUrl || IFLYTEK_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.Iflytek as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[Iflytek] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/alibaba.ts
app/api/alibaba.ts
import { getServerSideConfig } from "@/app/config/server"; import { ALIBABA_BASE_URL, ApiPath, ModelProvider, ServiceProvider, } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { isModelNotavailableInServer } from "@/app/utils/model"; const serverConfig = getServerSideConfig(); export async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Alibaba Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.Qwen); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[Alibaba] ", e); return NextResponse.json(prettyObject(e)); } } async function request(req: NextRequest) { const controller = new AbortController(); // alibaba use base url or just remove the path let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Alibaba, ""); let baseUrl = serverConfig.alibabaUrl || ALIBABA_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Proxy] ", path); console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = `${baseUrl}${path}`; const fetchOptions: RequestInit = { headers: { "Content-Type": "application/json", Authorization: req.headers.get("Authorization") ?? "", "X-DashScope-SSE": req.headers.get("X-DashScope-SSE") ?? "disable", }, method: req.method, body: req.body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; // #1815 try to refuse some request to some models if (serverConfig.customModels && req.body) { try { const clonedBody = await req.text(); fetchOptions.body = clonedBody; const jsonBody = JSON.parse(clonedBody) as { model?: string }; // not undefined and is false if ( isModelNotavailableInServer( serverConfig.customModels, jsonBody?.model as string, ServiceProvider.Alibaba as string, ) ) { return NextResponse.json( { error: true, message: `you are not allowed to use ${jsonBody?.model} model`, }, { status: 403, }, ); } } catch (e) { console.error(`[Alibaba] filter`, e); } } try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/webdav/[...path]/route.ts
app/api/webdav/[...path]/route.ts
import { NextRequest, NextResponse } from "next/server"; import { STORAGE_KEY, internalAllowedWebDavEndpoints } from "../../../constant"; import { getServerSideConfig } from "@/app/config/server"; const config = getServerSideConfig(); const mergedAllowedWebDavEndpoints = [ ...internalAllowedWebDavEndpoints, ...config.allowedWebDavEndpoints, ].filter((domain) => Boolean(domain.trim())); const normalizeUrl = (url: string) => { try { return new URL(url); } catch (err) { return null; } }; async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const folder = STORAGE_KEY; const fileName = `${folder}/backup.json`; const requestUrl = new URL(req.url); let endpoint = requestUrl.searchParams.get("endpoint"); let proxy_method = requestUrl.searchParams.get("proxy_method") || req.method; // Validate the endpoint to prevent potential SSRF attacks if ( !endpoint || !mergedAllowedWebDavEndpoints.some((allowedEndpoint) => { const normalizedAllowedEndpoint = normalizeUrl(allowedEndpoint); const normalizedEndpoint = normalizeUrl(endpoint as string); return ( normalizedEndpoint && normalizedEndpoint.hostname === normalizedAllowedEndpoint?.hostname && normalizedEndpoint.pathname.startsWith( normalizedAllowedEndpoint.pathname, ) ); }) ) { return NextResponse.json( { error: true, msg: "Invalid endpoint", }, { status: 400, }, ); } if (!endpoint?.endsWith("/")) { endpoint += "/"; } const endpointPath = params.path.join("/"); const targetPath = `${endpoint}${endpointPath}`; // only allow MKCOL, GET, PUT if ( proxy_method !== "MKCOL" && proxy_method !== "GET" && proxy_method !== "PUT" ) { return NextResponse.json( { error: true, msg: "you are not allowed to request " + targetPath, }, { status: 403, }, ); } // for MKCOL request, only allow request ${folder} if (proxy_method === "MKCOL" && !targetPath.endsWith(folder)) { return NextResponse.json( { error: true, msg: "you are not allowed to request " + targetPath, }, { status: 403, }, ); } // for GET request, only allow request ending with fileName if (proxy_method === "GET" && !targetPath.endsWith(fileName)) { return NextResponse.json( { error: true, msg: "you are not allowed to request " + targetPath, }, { status: 403, }, ); } // for PUT request, only allow request ending with fileName if (proxy_method === "PUT" && !targetPath.endsWith(fileName)) { return NextResponse.json( { error: true, msg: "you are not allowed to request " + targetPath, }, { status: 403, }, ); } const targetUrl = targetPath; const method = proxy_method || req.method; const shouldNotHaveBody = ["get", "head"].includes( method?.toLowerCase() ?? "", ); const fetchOptions: RequestInit = { headers: { authorization: req.headers.get("authorization") ?? "", }, body: shouldNotHaveBody ? null : req.body, redirect: "manual", method, // @ts-ignore duplex: "half", }; let fetchResult; try { fetchResult = await fetch(targetUrl, fetchOptions); } finally { console.log( "[Any Proxy]", targetUrl, { method: method, }, { status: fetchResult?.status, statusText: fetchResult?.statusText, }, ); } return fetchResult; } export const PUT = handle; export const GET = handle; export const OPTIONS = handle; export const runtime = "edge";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/artifacts/route.ts
app/api/artifacts/route.ts
import md5 from "spark-md5"; import { NextRequest, NextResponse } from "next/server"; import { getServerSideConfig } from "@/app/config/server"; async function handle(req: NextRequest, res: NextResponse) { const serverConfig = getServerSideConfig(); const storeUrl = () => `https://api.cloudflare.com/client/v4/accounts/${serverConfig.cloudflareAccountId}/storage/kv/namespaces/${serverConfig.cloudflareKVNamespaceId}`; const storeHeaders = () => ({ Authorization: `Bearer ${serverConfig.cloudflareKVApiKey}`, }); if (req.method === "POST") { const clonedBody = await req.text(); const hashedCode = md5.hash(clonedBody).trim(); const body: { key: string; value: string; expiration_ttl?: number; } = { key: hashedCode, value: clonedBody, }; try { const ttl = parseInt(serverConfig.cloudflareKVTTL as string); if (ttl > 60) { body["expiration_ttl"] = ttl; } } catch (e) { console.error(e); } const res = await fetch(`${storeUrl()}/bulk`, { headers: { ...storeHeaders(), "Content-Type": "application/json", }, method: "PUT", body: JSON.stringify([body]), }); const result = await res.json(); console.log("save data", result); if (result?.success) { return NextResponse.json( { code: 0, id: hashedCode, result }, { status: res.status }, ); } return NextResponse.json( { error: true, msg: "Save data error" }, { status: 400 }, ); } if (req.method === "GET") { const id = req?.nextUrl?.searchParams?.get("id"); const res = await fetch(`${storeUrl()}/values/${id}`, { headers: storeHeaders(), method: "GET", }); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: res.headers, }); } return NextResponse.json( { error: true, msg: "Invalid request" }, { status: 400 }, ); } export const POST = handle; export const GET = handle; export const runtime = "edge";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/tencent/route.ts
app/api/tencent/route.ts
import { getServerSideConfig } from "@/app/config/server"; import { TENCENT_BASE_URL, ModelProvider } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/api/auth"; import { getHeader } from "@/app/utils/tencent"; const serverConfig = getServerSideConfig(); async function handle( req: NextRequest, { params }: { params: { path: string[] } }, ) { console.log("[Tencent Route] params ", params); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const authResult = auth(req, ModelProvider.Hunyuan); if (authResult.error) { return NextResponse.json(authResult, { status: 401, }); } try { const response = await request(req); return response; } catch (e) { console.error("[Tencent] ", e); return NextResponse.json(prettyObject(e)); } } export const GET = handle; export const POST = handle; export const runtime = "edge"; export const preferredRegion = [ "arn1", "bom1", "cdg1", "cle1", "cpt1", "dub1", "fra1", "gru1", "hnd1", "iad1", "icn1", "kix1", "lhr1", "pdx1", "sfo1", "sin1", "syd1", ]; async function request(req: NextRequest) { const controller = new AbortController(); let baseUrl = serverConfig.tencentUrl || TENCENT_BASE_URL; if (!baseUrl.startsWith("http")) { baseUrl = `https://${baseUrl}`; } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.slice(0, -1); } console.log("[Base Url]", baseUrl); const timeoutId = setTimeout( () => { controller.abort(); }, 10 * 60 * 1000, ); const fetchUrl = baseUrl; const body = await req.text(); const headers = await getHeader( body, serverConfig.tencentSecretId as string, serverConfig.tencentSecretKey as string, ); const fetchOptions: RequestInit = { headers, method: req.method, body, redirect: "manual", // @ts-ignore duplex: "half", signal: controller.signal, }; try { const res = await fetch(fetchUrl, fetchOptions); // to prevent browser prompt for credentials const newHeaders = new Headers(res.headers); newHeaders.delete("www-authenticate"); // to disable nginx buffering newHeaders.set("X-Accel-Buffering", "no"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders, }); } finally { clearTimeout(timeoutId); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/[provider]/[...path]/route.ts
app/api/[provider]/[...path]/route.ts
import { ApiPath } from "@/app/constant"; import { NextRequest } from "next/server"; import { handle as openaiHandler } from "../../openai"; import { handle as azureHandler } from "../../azure"; import { handle as googleHandler } from "../../google"; import { handle as anthropicHandler } from "../../anthropic"; import { handle as baiduHandler } from "../../baidu"; import { handle as bytedanceHandler } from "../../bytedance"; import { handle as alibabaHandler } from "../../alibaba"; import { handle as moonshotHandler } from "../../moonshot"; import { handle as stabilityHandler } from "../../stability"; import { handle as iflytekHandler } from "../../iflytek"; import { handle as deepseekHandler } from "../../deepseek"; import { handle as siliconflowHandler } from "../../siliconflow"; import { handle as xaiHandler } from "../../xai"; import { handle as chatglmHandler } from "../../glm"; import { handle as proxyHandler } from "../../proxy"; import { handle as ai302Handler } from "../../302ai"; async function handle( req: NextRequest, { params }: { params: { provider: string; path: string[] } }, ) { const apiPath = `/api/${params.provider}`; console.log(`[${params.provider} Route] params `, params); switch (apiPath) { case ApiPath.Azure: return azureHandler(req, { params }); case ApiPath.Google: return googleHandler(req, { params }); case ApiPath.Anthropic: return anthropicHandler(req, { params }); case ApiPath.Baidu: return baiduHandler(req, { params }); case ApiPath.ByteDance: return bytedanceHandler(req, { params }); case ApiPath.Alibaba: return alibabaHandler(req, { params }); // case ApiPath.Tencent: using "/api/tencent" case ApiPath.Moonshot: return moonshotHandler(req, { params }); case ApiPath.Stability: return stabilityHandler(req, { params }); case ApiPath.Iflytek: return iflytekHandler(req, { params }); case ApiPath.DeepSeek: return deepseekHandler(req, { params }); case ApiPath.XAI: return xaiHandler(req, { params }); case ApiPath.ChatGLM: return chatglmHandler(req, { params }); case ApiPath.SiliconFlow: return siliconflowHandler(req, { params }); case ApiPath.OpenAI: return openaiHandler(req, { params }); case ApiPath["302.AI"]: return ai302Handler(req, { params }); default: return proxyHandler(req, { params }); } } export const GET = handle; export const POST = handle; export const runtime = "edge"; export const preferredRegion = [ "arn1", "bom1", "cdg1", "cle1", "cpt1", "dub1", "fra1", "gru1", "hnd1", "iad1", "icn1", "kix1", "lhr1", "pdx1", "sfo1", "sin1", "syd1", ];
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/upstash/[action]/[...key]/route.ts
app/api/upstash/[action]/[...key]/route.ts
import { NextRequest, NextResponse } from "next/server"; async function handle( req: NextRequest, { params }: { params: { action: string; key: string[] } }, ) { const requestUrl = new URL(req.url); const endpoint = requestUrl.searchParams.get("endpoint"); if (req.method === "OPTIONS") { return NextResponse.json({ body: "OK" }, { status: 200 }); } const [...key] = params.key; // only allow to request to *.upstash.io if (!endpoint || !new URL(endpoint).hostname.endsWith(".upstash.io")) { return NextResponse.json( { error: true, msg: "you are not allowed to request " + params.key.join("/"), }, { status: 403, }, ); } // only allow upstash get and set method if (params.action !== "get" && params.action !== "set") { console.log("[Upstash Route] forbidden action ", params.action); return NextResponse.json( { error: true, msg: "you are not allowed to request " + params.action, }, { status: 403, }, ); } const targetUrl = `${endpoint}/${params.action}/${params.key.join("/")}`; const method = req.method; const shouldNotHaveBody = ["get", "head"].includes( method?.toLowerCase() ?? "", ); const fetchOptions: RequestInit = { headers: { authorization: req.headers.get("authorization") ?? "", }, body: shouldNotHaveBody ? null : req.body, method, // @ts-ignore duplex: "half", }; console.log("[Upstash Proxy]", targetUrl, fetchOptions); const fetchResult = await fetch(targetUrl, fetchOptions); console.log("[Any Proxy]", targetUrl, { status: fetchResult.status, statusText: fetchResult.statusText, }); return fetchResult; } export const POST = handle; export const GET = handle; export const OPTIONS = handle; export const runtime = "edge";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/api/config/route.ts
app/api/config/route.ts
import { NextResponse } from "next/server"; import { getServerSideConfig } from "../../config/server"; const serverConfig = getServerSideConfig(); // Danger! Do not hard code any secret value here! // 警告!不要在这里写入任何敏感信息! const DANGER_CONFIG = { needCode: serverConfig.needCode, hideUserApiKey: serverConfig.hideUserApiKey, disableGPT4: serverConfig.disableGPT4, hideBalanceQuery: serverConfig.hideBalanceQuery, disableFastLink: serverConfig.disableFastLink, customModels: serverConfig.customModels, defaultModel: serverConfig.defaultModel, visionModels: serverConfig.visionModels, }; declare global { type DangerConfig = typeof DANGER_CONFIG; } async function handle() { return NextResponse.json(DANGER_CONFIG); } export const GET = handle; export const POST = handle; export const runtime = "edge";
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/lib/audio.ts
app/lib/audio.ts
export class AudioHandler { private context: AudioContext; private mergeNode: ChannelMergerNode; private analyserData: Uint8Array; public analyser: AnalyserNode; private workletNode: AudioWorkletNode | null = null; private stream: MediaStream | null = null; private source: MediaStreamAudioSourceNode | null = null; private recordBuffer: Int16Array[] = []; private readonly sampleRate = 24000; private nextPlayTime: number = 0; private isPlaying: boolean = false; private playbackQueue: AudioBufferSourceNode[] = []; private playBuffer: Int16Array[] = []; constructor() { this.context = new AudioContext({ sampleRate: this.sampleRate }); // using ChannelMergerNode to get merged audio data, and then get analyser data. this.mergeNode = new ChannelMergerNode(this.context, { numberOfInputs: 2 }); this.analyser = new AnalyserNode(this.context, { fftSize: 256 }); this.analyserData = new Uint8Array(this.analyser.frequencyBinCount); this.mergeNode.connect(this.analyser); } getByteFrequencyData() { this.analyser.getByteFrequencyData(this.analyserData); return this.analyserData; } async initialize() { await this.context.audioWorklet.addModule("/audio-processor.js"); } async startRecording(onChunk: (chunk: Uint8Array) => void) { try { if (!this.workletNode) { await this.initialize(); } this.stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, sampleRate: this.sampleRate, echoCancellation: true, noiseSuppression: true, }, }); await this.context.resume(); this.source = this.context.createMediaStreamSource(this.stream); this.workletNode = new AudioWorkletNode( this.context, "audio-recorder-processor", ); this.workletNode.port.onmessage = (event) => { if (event.data.eventType === "audio") { const float32Data = event.data.audioData; const int16Data = new Int16Array(float32Data.length); for (let i = 0; i < float32Data.length; i++) { const s = Math.max(-1, Math.min(1, float32Data[i])); int16Data[i] = s < 0 ? s * 0x8000 : s * 0x7fff; } const uint8Data = new Uint8Array(int16Data.buffer); onChunk(uint8Data); // save recordBuffer // @ts-ignore this.recordBuffer.push.apply(this.recordBuffer, int16Data); } }; this.source.connect(this.workletNode); this.source.connect(this.mergeNode, 0, 0); this.workletNode.connect(this.context.destination); this.workletNode.port.postMessage({ command: "START_RECORDING" }); } catch (error) { console.error("Error starting recording:", error); throw error; } } stopRecording() { if (!this.workletNode || !this.source || !this.stream) { throw new Error("Recording not started"); } this.workletNode.port.postMessage({ command: "STOP_RECORDING" }); this.workletNode.disconnect(); this.source.disconnect(); this.stream.getTracks().forEach((track) => track.stop()); } startStreamingPlayback() { this.isPlaying = true; this.nextPlayTime = this.context.currentTime; } stopStreamingPlayback() { this.isPlaying = false; this.playbackQueue.forEach((source) => source.stop()); this.playbackQueue = []; this.playBuffer = []; } playChunk(chunk: Uint8Array) { if (!this.isPlaying) return; const int16Data = new Int16Array(chunk.buffer); // @ts-ignore this.playBuffer.push.apply(this.playBuffer, int16Data); // save playBuffer const float32Data = new Float32Array(int16Data.length); for (let i = 0; i < int16Data.length; i++) { float32Data[i] = int16Data[i] / (int16Data[i] < 0 ? 0x8000 : 0x7fff); } const audioBuffer = this.context.createBuffer( 1, float32Data.length, this.sampleRate, ); audioBuffer.getChannelData(0).set(float32Data); const source = this.context.createBufferSource(); source.buffer = audioBuffer; source.connect(this.context.destination); source.connect(this.mergeNode, 0, 1); const chunkDuration = audioBuffer.length / this.sampleRate; source.start(this.nextPlayTime); this.playbackQueue.push(source); source.onended = () => { const index = this.playbackQueue.indexOf(source); if (index > -1) { this.playbackQueue.splice(index, 1); } }; this.nextPlayTime += chunkDuration; if (this.nextPlayTime < this.context.currentTime) { this.nextPlayTime = this.context.currentTime; } } _saveData(data: Int16Array, bytesPerSample = 16): Blob { const headerLength = 44; const numberOfChannels = 1; const byteLength = data.buffer.byteLength; const header = new Uint8Array(headerLength); const view = new DataView(header.buffer); view.setUint32(0, 1380533830, false); // RIFF identifier 'RIFF' view.setUint32(4, 36 + byteLength, true); // file length minus RIFF identifier length and file description length view.setUint32(8, 1463899717, false); // RIFF type 'WAVE' view.setUint32(12, 1718449184, false); // format chunk identifier 'fmt ' view.setUint32(16, 16, true); // format chunk length view.setUint16(20, 1, true); // sample format (raw) view.setUint16(22, numberOfChannels, true); // channel count view.setUint32(24, this.sampleRate, true); // sample rate view.setUint32(28, this.sampleRate * 4, true); // byte rate (sample rate * block align) view.setUint16(32, numberOfChannels * 2, true); // block align (channel count * bytes per sample) view.setUint16(34, bytesPerSample, true); // bits per sample view.setUint32(36, 1684108385, false); // data chunk identifier 'data' view.setUint32(40, byteLength, true); // data chunk length // using data.buffer, so no need to setUint16 to view. return new Blob([view, data.buffer], { type: "audio/mpeg" }); } savePlayFile() { // @ts-ignore return this._saveData(new Int16Array(this.playBuffer)); } saveRecordFile( audioStartMillis: number | undefined, audioEndMillis: number | undefined, ) { const startIndex = audioStartMillis ? Math.floor((audioStartMillis * this.sampleRate) / 1000) : 0; const endIndex = audioEndMillis ? Math.floor((audioEndMillis * this.sampleRate) / 1000) : this.recordBuffer.length; return this._saveData( // @ts-ignore new Int16Array(this.recordBuffer.slice(startIndex, endIndex)), ); } async close() { this.recordBuffer = []; this.workletNode?.disconnect(); this.source?.disconnect(); this.stream?.getTracks().forEach((track) => track.stop()); await this.context.close(); } }
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/locales/jp.ts
app/locales/jp.ts
import { SubmitKey } from "../store/config"; import type { PartialLocaleType } from "./index"; import { getClientConfig } from "../config/client"; import { SAAS_CHAT_UTM_URL } from "@/app/constant"; const isApp = !!getClientConfig()?.isApp; const jp: PartialLocaleType = { WIP: "この機能は開発中です", Error: { Unauthorized: isApp ? `😆 会話中に問題が発生しましたが、心配しないでください: \\ 1️⃣ 設定なしで始めたい場合は、[ここをクリックしてすぐにチャットを開始 🚀](${SAAS_CHAT_UTM_URL}) \\ 2️⃣ 自分のOpenAIリソースを使用したい場合は、[ここをクリックして](/#/settings)設定を変更してください ⚙️` : `😆 会話中に問題が発生しましたが、心配しないでください: \ 1️⃣ 設定なしで始めたい場合は、[ここをクリックしてすぐにチャットを開始 🚀](${SAAS_CHAT_UTM_URL}) \ 2️⃣ プライベートデプロイ版を使用している場合は、[ここをクリックして](/#/auth)アクセストークンを入力してください 🔑 \ 3️⃣ 自分のOpenAIリソースを使用したい場合は、[ここをクリックして](/#/settings)設定を変更してください ⚙️ `, }, Auth: { Title: "パスワードが必要です", Tips: "管理者がパスワード認証を有効にしました。以下にアクセスコードを入力してください", SubTips: "または、OpenAIまたはGoogle APIキーを入力してください", Input: "ここにアクセスコードを入力", Confirm: "確認", Later: "後で", Return: "戻る", SaasTips: "設定が面倒すぎる、すぐに使いたい", TopTips: "🥳 NextChat AIの発売特典で、OpenAI o1、GPT-4o、Claude-3.5などの最新の大規模モデルを今すぐアンロック", }, ChatItem: { ChatItemCount: (count: number) => `${count}件の会話`, }, Chat: { SubTitle: (count: number) => `合計${count}件の会話`, EditMessage: { Title: "メッセージ履歴を編集", Topic: { Title: "チャットテーマ", SubTitle: "現在のチャットテーマを変更", }, }, Actions: { ChatList: "メッセージリストを見る", CompressedHistory: "圧縮された履歴プロンプトを見る", Export: "チャット履歴をエクスポート", Copy: "コピー", Stop: "停止", Retry: "再試行", Pin: "固定", PinToastContent: "1件の会話をプリセットプロンプトに固定しました", PinToastAction: "見る", Delete: "削除", Edit: "編集", RefreshTitle: "タイトルを更新", RefreshToast: "タイトル更新リクエストが送信されました", }, Commands: { new: "新しいチャット", newm: "マスクから新しいチャット", next: "次のチャット", prev: "前のチャット", clear: "コンテキストをクリア", del: "チャットを削除", }, InputActions: { Stop: "応答を停止", ToBottom: "最新へスクロール", Theme: { auto: "自動テーマ", light: "ライトモード", dark: "ダークモード", }, Prompt: "クイックコマンド", Masks: "すべてのマスク", Clear: "チャットをクリア", Settings: "チャット設定", UploadImage: "画像をアップロード", }, Rename: "チャットの名前を変更", Typing: "入力中…", Input: (submitKey: string) => { var inputHints = `${submitKey}で送信`; if (submitKey === String(SubmitKey.Enter)) { inputHints += "、Shift + Enterで改行"; } return inputHints + "、/で補完をトリガー、:でコマンドをトリガー"; }, Send: "送信", Config: { Reset: "メモリをクリア", SaveAs: "マスクとして保存", }, IsContext: "プリセットプロンプト", }, Export: { Title: "チャット履歴を共有", Copy: "すべてコピー", Download: "ファイルをダウンロード", Share: "ShareGPTに共有", MessageFromYou: "ユーザー", MessageFromChatGPT: "ChatGPT", Format: { Title: "エクスポート形式", SubTitle: "MarkdownテキストまたはPNG画像としてエクスポートできます", }, IncludeContext: { Title: "マスクコンテキストを含む", SubTitle: "メッセージにマスクコンテキストを表示するかどうか", }, Steps: { Select: "選択", Preview: "プレビュー", }, Image: { Toast: "スクリーンショットを生成中", Modal: "長押しまたは右クリックして画像を保存", }, }, Select: { Search: "メッセージを検索", All: "すべて選択", Latest: "最新の数件", Clear: "選択をクリア", }, Memory: { Title: "履歴の要約", EmptyContent: "対話内容が短いため、要約は不要です", Send: "チャット履歴を自動的に圧縮し、コンテキストとして送信", Copy: "要約をコピー", Reset: "[unused]", ResetConfirm: "履歴の要約をリセットしてもよろしいですか?", }, Home: { NewChat: "新しいチャット", DeleteChat: "選択した会話を削除してもよろしいですか?", DeleteToast: "会話を削除しました", Revert: "元に戻す", }, Settings: { Title: "設定", SubTitle: "すべての設定オプション", Danger: { Reset: { Title: "すべての設定をリセット", SubTitle: "すべての設定項目をデフォルト値にリセット", Action: "今すぐリセット", Confirm: "すべての設定をリセットしてもよろしいですか?", }, Clear: { Title: "すべてのデータをクリア", SubTitle: "すべてのチャット、設定データをクリア", Action: "今すぐクリア", Confirm: "すべてのチャット、設定データをクリアしてもよろしいですか?", }, }, Lang: { Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language` All: "すべての言語", }, Avatar: "アバター", FontSize: { Title: "フォントサイズ", SubTitle: "チャット内容のフォントサイズ", }, FontFamily: { Title: "チャットフォント", SubTitle: "チャットコンテンツのフォント、空白の場合はグローバルデフォルトフォントを適用します", Placeholder: "フォント名", }, InjectSystemPrompts: { Title: "システムプロンプトの注入", SubTitle: "すべてのリクエストメッセージリストの先頭にChatGPTのシステムプロンプトを強制的に追加", }, InputTemplate: { Title: "ユーザー入力のプリプロセス", SubTitle: "最新のメッセージをこのテンプレートに埋め込む", }, Update: { Version: (x: string) => `現在のバージョン:${x}`, IsLatest: "最新バージョンです", CheckUpdate: "更新を確認", IsChecking: "更新を確認中...", FoundUpdate: (x: string) => `新しいバージョンを発見:${x}`, GoToUpdate: "更新へ進む", }, SendKey: "送信キー", Theme: "テーマ", TightBorder: "ボーダーレスモード", SendPreviewBubble: { Title: "プレビューバブル", SubTitle: "プレビューバブルでMarkdownコンテンツをプレビュー", }, AutoGenerateTitle: { Title: "自動タイトル生成", SubTitle: "チャット内容に基づいて適切なタイトルを生成", }, Sync: { CloudState: "クラウドデータ", NotSyncYet: "まだ同期されていません", Success: "同期に成功しました", Fail: "同期に失敗しました", Config: { Modal: { Title: "クラウド同期の設定", Check: "可用性を確認", }, SyncType: { Title: "同期タイプ", SubTitle: "好きな同期サーバーを選択", }, Proxy: { Title: "プロキシを有効化", SubTitle: "ブラウザで同期する場合、クロスオリジン制限を避けるためにプロキシを有効にする必要があります", }, ProxyUrl: { Title: "プロキシURL", SubTitle: "このプロジェクトに組み込まれたクロスオリジンプロキシ専用", }, WebDav: { Endpoint: "WebDAV エンドポイント", UserName: "ユーザー名", Password: "パスワード", }, UpStash: { Endpoint: "UpStash Redis REST URL", UserName: "バックアップ名", Password: "UpStash Redis REST トークン", }, }, LocalState: "ローカルデータ", Overview: (overview: any) => { return `${overview.chat} 回の対話、${overview.message} 件のメッセージ、${overview.prompt} 件のプロンプト、${overview.mask} 件のマスク`; }, ImportFailed: "インポートに失敗しました", }, Mask: { Splash: { Title: "マスク起動画面", SubTitle: "新しいチャットを作成する際にマスク起動画面を表示", }, Builtin: { Title: "内蔵マスクを非表示", SubTitle: "すべてのマスクリストで内蔵マスクを非表示", }, }, Prompt: { Disable: { Title: "プロンプトの自動補完を無効化", SubTitle: "入力フィールドの先頭に / を入力して自動補完をトリガー", }, List: "カスタムプロンプトリスト", ListCount: (builtin: number, custom: number) => `内蔵 ${builtin} 件、ユーザー定義 ${custom} 件`, Edit: "編集", Modal: { Title: "プロンプトリスト", Add: "新規作成", Search: "プロンプトを検索", }, EditModal: { Title: "プロンプトを編集", }, }, HistoryCount: { Title: "履歴メッセージ数", SubTitle: "各リクエストに含まれる履歴メッセージの数", }, CompressThreshold: { Title: "履歴メッセージの圧縮閾値", SubTitle: "未圧縮の履歴メッセージがこの値を超えた場合、圧縮が行われます", }, Usage: { Title: "残高確認", SubTitle(used: any, total: any) { return `今月の使用量 $${used}、サブスクリプション合計 $${total}`; }, IsChecking: "確認中…", Check: "再確認", NoAccess: "APIキーまたはアクセスパスワードを入力して残高を確認", }, Access: { SaasStart: { Title: "NextChat AIを使用する", Label: "(コストパフォーマンスの最も高いソリューション)", SubTitle: "NextChatによって公式に管理されており、設定なしですぐに使用でき、OpenAI o1、GPT-4o、Claude-3.5などの最新の大規模モデルをサポートしています", ChatNow: "今すぐチャット", }, AccessCode: { Title: "アクセスパスワード", SubTitle: "管理者が暗号化アクセスを有効にしました", Placeholder: "アクセスパスワードを入力してください", }, CustomEndpoint: { Title: "カスタムエンドポイント", SubTitle: "カスタムAzureまたはOpenAIサービスを使用するかどうか", }, Provider: { Title: "モデルプロバイダー", SubTitle: "異なるプロバイダーに切り替える", }, OpenAI: { ApiKey: { Title: "APIキー", SubTitle: "カスタムOpenAIキーを使用してパスワードアクセス制限を回避", Placeholder: "OpenAI APIキー", }, Endpoint: { Title: "エンドポイント", SubTitle: "デフォルト以外のアドレスにはhttp(s)://を含める必要があります", }, }, Azure: { ApiKey: { Title: "APIキー", SubTitle: "カスタムAzureキーを使用してパスワードアクセス制限を回避", Placeholder: "Azure APIキー", }, Endpoint: { Title: "エンドポイント", SubTitle: "例:", }, ApiVerion: { Title: "APIバージョン (azure api version)", SubTitle: "特定のバージョンを選択", }, }, Anthropic: { ApiKey: { Title: "APIキー", SubTitle: "カスタムAnthropicキーを使用してパスワードアクセス制限を回避", Placeholder: "Anthropic APIキー", }, Endpoint: { Title: "エンドポイント", SubTitle: "例:", }, ApiVerion: { Title: "APIバージョン (claude api version)", SubTitle: "特定のAPIバージョンを選択", }, }, Google: { ApiKey: { Title: "APIキー", SubTitle: "Google AIからAPIキーを取得", Placeholder: "Google AI Studio APIキーを入力", }, Endpoint: { Title: "エンドポイント", SubTitle: "例:", }, ApiVersion: { Title: "APIバージョン(gemini-pro専用)", SubTitle: "特定のAPIバージョンを選択", }, GoogleSafetySettings: { Title: "Google セーフティ設定", SubTitle: "コンテンツフィルタリングレベルを設定", }, }, Baidu: { ApiKey: { Title: "APIキー", SubTitle: "カスタムBaidu APIキーを使用", Placeholder: "Baidu APIキー", }, SecretKey: { Title: "シークレットキー", SubTitle: "カスタムBaiduシークレットキーを使用", Placeholder: "Baiduシークレットキー", }, Endpoint: { Title: "エンドポイント", SubTitle: "カスタムはサポートしていません、.env設定に進んでください", }, }, ByteDance: { ApiKey: { Title: "APIキー", SubTitle: "カスタムByteDance APIキーを使用", Placeholder: "ByteDance APIキー", }, Endpoint: { Title: "エンドポイント", SubTitle: "例:", }, }, Alibaba: { ApiKey: { Title: "APIキー", SubTitle: "カスタムAlibaba Cloud APIキーを使用", Placeholder: "Alibaba Cloud APIキー", }, Endpoint: { Title: "エンドポイント", SubTitle: "例:", }, }, AI302: { ApiKey: { Title: "APIキー", SubTitle: "カスタム302.AI APIキーを使用", Placeholder: "302.AI APIキー", }, Endpoint: { Title: "エンドポイント", SubTitle: "例:", }, }, CustomModel: { Title: "カスタムモデル名", SubTitle: "カスタムモデルの選択肢を追加、英語のカンマで区切る", }, }, Model: "モデル (model)", CompressModel: { Title: "圧縮モデル", SubTitle: "履歴を圧縮するために使用されるモデル", }, Temperature: { Title: "ランダム性 (temperature)", SubTitle: "値が大きいほど応答がランダムになります", }, TopP: { Title: "トップP (top_p)", SubTitle: "ランダム性に似ていますが、ランダム性と一緒に変更しないでください", }, MaxTokens: { Title: "1回の応答制限 (max_tokens)", SubTitle: "1回の対話で使用される最大トークン数", }, PresencePenalty: { Title: "新鮮度 (presence_penalty)", SubTitle: "値が大きいほど新しいトピックに移行する可能性が高くなります", }, FrequencyPenalty: { Title: "頻度ペナルティ (frequency_penalty)", SubTitle: "値が大きいほど繰り返しの単語が減少します", }, }, Store: { DefaultTopic: "新しいチャット", BotHello: "何かお手伝いできますか?", Error: "エラーが発生しました。後でもう一度試してください", Prompt: { History: (content: string) => "これは前提としての履歴チャットの要約です:" + content, Topic: "この文の簡潔なテーマを四から五文字で返してください。説明、句読点、感嘆詞、余計なテキストは不要です。太字も不要です。テーマがない場合は「雑談」と返してください", Summarize: "対話の内容を簡潔に要約し、後続のコンテキストプロンプトとして使用します。200文字以内に抑えてください", }, }, Copy: { Success: "クリップボードに書き込みました", Failed: "コピーに失敗しました。クリップボードの権限を付与してください", }, Download: { Success: "内容がダウンロードされました", Failed: "ダウンロードに失敗しました", }, Context: { Toast: (x: any) => `${x} 件のプリセットプロンプトが含まれています`, Edit: "現在の対話設定", Add: "対話を追加", Clear: "コンテキストがクリアされました", Revert: "コンテキストを元に戻す", }, Plugin: { Name: "プラグイン", }, Discovery: { Name: "発見", }, FineTuned: { Sysmessage: "あなたはアシスタントです", }, SearchChat: { Name: "検索", Page: { Title: "チャット履歴を検索", Search: "検索キーワードを入力", NoResult: "結果が見つかりませんでした", NoData: "データがありません", Loading: "読み込み中", SubTitle: (count: number) => `${count} 件の結果が見つかりました`, }, Item: { View: "表示", }, }, Mask: { Name: "マスク", Page: { Title: "プリセットキャラクターマスク", SubTitle: (count: number) => `${count} 件のプリセットキャラクター定義`, Search: "キャラクターマスクを検索", Create: "新規作成", }, Item: { Info: (count: number) => `${count} 件のプリセット対話が含まれています`, Chat: "対話", View: "表示", Edit: "編集", Delete: "削除", DeleteConfirm: "削除してもよろしいですか?", }, EditModal: { Title: (readonly: boolean) => `プリセットマスクの編集 ${readonly ? "(読み取り専用)" : ""}`, Download: "プリセットをダウンロード", Clone: "プリセットをクローン", }, Config: { Avatar: "キャラクターアバター", Name: "キャラクター名", Sync: { Title: "グローバル設定を使用", SubTitle: "現在の対話でグローバルモデル設定を使用するかどうか", Confirm: "現在の対話のカスタム設定が自動的に上書きされます。グローバル設定を有効にしてもよろしいですか?", }, HideContext: { Title: "プリセット対話を非表示", SubTitle: "非表示にすると、プリセット対話はチャット画面に表示されません", }, Share: { Title: "このマスクを共有", SubTitle: "このマスクの直リンクを生成", Action: "リンクをコピー", }, }, }, NewChat: { Return: "戻る", Skip: "直接開始", NotShow: "今後表示しない", ConfirmNoShow: "無効にしてもよろしいですか?無効にした後、設定でいつでも再度有効にできます。", Title: "マスクを選択", SubTitle: "今すぐ始めよう、マスクの背後にある魂と思考の衝突", More: "すべて表示", }, URLCommand: { Code: "リンクにアクセスコードが含まれています。自動入力しますか?", Settings: "リンクにプリセット設定が含まれています。自動入力しますか?", }, UI: { Confirm: "確認", Cancel: "キャンセル", Close: "閉じる", Create: "新規作成", Edit: "編集", Export: "エクスポート", Import: "インポート", Sync: "同期", Config: "設定", }, Exporter: { Description: { Title: "コンテキストをクリアした後のメッセージのみが表示されます", }, Model: "モデル", Messages: "メッセージ", Topic: "テーマ", Time: "時間", }, }; export default jp;
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false
ChatGPTNextWeb/NextChat
https://github.com/ChatGPTNextWeb/NextChat/blob/c3b8c1587c04fff05f7b42276a43016e87771527/app/locales/cn.ts
app/locales/cn.ts
import { getClientConfig } from "../config/client"; import { SubmitKey } from "../store/config"; import { SAAS_CHAT_UTM_URL } from "@/app/constant"; const isApp = !!getClientConfig()?.isApp; const cn = { WIP: "该功能仍在开发中……", Error: { Unauthorized: isApp ? `😆 对话遇到了一些问题,不用慌: \\ 1️⃣ 想要零配置开箱即用,[点击这里立刻开启对话 🚀](${SAAS_CHAT_UTM_URL}) \\ 2️⃣ 如果你想消耗自己的 OpenAI 资源,点击[这里](/#/settings)修改设置 ⚙️` : `😆 对话遇到了一些问题,不用慌: \ 1️⃣ 想要零配置开箱即用,[点击这里立刻开启对话 🚀](${SAAS_CHAT_UTM_URL}) \ 2️⃣ 如果你正在使用私有部署版本,点击[这里](/#/auth)输入访问秘钥 🔑 \ 3️⃣ 如果你想消耗自己的 OpenAI 资源,点击[这里](/#/settings)修改设置 ⚙️ `, }, Auth: { Return: "返回", Title: "需要密码", Tips: "管理员开启了密码验证,请在下方填入访问码", SubTips: "或者输入你的 OpenAI 或 Google AI 密钥", Input: "在此处填写访问码", Confirm: "确认", Later: "稍后再说", SaasTips: "配置太麻烦,想要立即使用", TopTips: "🥳 NextChat AI 首发优惠,立刻解锁 OpenAI o1, GPT-4o, Claude-3.5 等最新大模型", }, ChatItem: { ChatItemCount: (count: number) => `${count} 条对话`, }, Chat: { SubTitle: (count: number) => `共 ${count} 条对话`, EditMessage: { Title: "编辑消息记录", Topic: { Title: "聊天主题", SubTitle: "更改当前聊天主题", }, }, Actions: { ChatList: "查看消息列表", CompressedHistory: "查看压缩后的历史 Prompt", Export: "导出聊天记录", Copy: "复制", Stop: "停止", Retry: "重试", Pin: "固定", PinToastContent: "已将 1 条对话固定至预设提示词", PinToastAction: "查看", Delete: "删除", Edit: "编辑", FullScreen: "全屏", RefreshTitle: "刷新标题", RefreshToast: "已发送刷新标题请求", Speech: "朗读", StopSpeech: "停止", }, Commands: { new: "新建聊天", newm: "从面具新建聊天", next: "下一个聊天", prev: "上一个聊天", clear: "清除上下文", fork: "复制聊天", del: "删除聊天", }, InputActions: { Stop: "停止响应", ToBottom: "滚到最新", Theme: { auto: "自动主题", light: "亮色模式", dark: "深色模式", }, Prompt: "快捷指令", Masks: "所有面具", Clear: "清除聊天", Settings: "对话设置", UploadImage: "上传图片", }, Rename: "重命名对话", Typing: "正在输入…", Input: (submitKey: string) => { var inputHints = `${submitKey} 发送`; if (submitKey === String(SubmitKey.Enter)) { inputHints += ",Shift + Enter 换行"; } return inputHints + ",/ 触发补全,: 触发命令"; }, Send: "发送", StartSpeak: "说话", StopSpeak: "停止", Config: { Reset: "清除记忆", SaveAs: "存为面具", }, IsContext: "预设提示词", ShortcutKey: { Title: "键盘快捷方式", newChat: "打开新聊天", focusInput: "聚焦输入框", copyLastMessage: "复制最后一个回复", copyLastCode: "复制最后一个代码块", showShortcutKey: "显示快捷方式", clearContext: "清除上下文", }, }, Export: { Title: "分享聊天记录", Copy: "全部复制", Download: "下载文件", Share: "分享到 ShareGPT", MessageFromYou: "用户", MessageFromChatGPT: "ChatGPT", Format: { Title: "导出格式", SubTitle: "可以导出 Markdown 文本或者 PNG 图片", }, IncludeContext: { Title: "包含面具上下文", SubTitle: "是否在消息中展示面具上下文", }, Steps: { Select: "选取", Preview: "预览", }, Image: { Toast: "正在生成截图", Modal: "长按或右键保存图片", }, Artifacts: { Title: "分享页面", Error: "分享失败", }, }, Select: { Search: "搜索消息", All: "选取全部", Latest: "最近几条", Clear: "清除选中", }, Memory: { Title: "历史摘要", EmptyContent: "对话内容过短,无需总结", Send: "自动压缩聊天记录并作为上下文发送", Copy: "复制摘要", Reset: "[unused]", ResetConfirm: "确认清空历史摘要?", }, Home: { NewChat: "新的聊天", DeleteChat: "确认删除选中的对话?", DeleteToast: "已删除会话", Revert: "撤销", }, Settings: { Title: "设置", SubTitle: "所有设置选项", ShowPassword: "显示密码", Danger: { Reset: { Title: "重置所有设置", SubTitle: "重置所有设置项回默认值", Action: "立即重置", Confirm: "确认重置所有设置?", }, Clear: { Title: "清除所有数据", SubTitle: "清除所有聊天、设置数据", Action: "立即清除", Confirm: "确认清除所有聊天、设置数据?", }, }, Lang: { Name: "Language", // 注意:如果要添加新的翻译,请不要翻译此值,将它保留为 `Language` All: "所有语言", }, Avatar: "头像", FontSize: { Title: "字体大小", SubTitle: "聊天内容的字体大小", }, FontFamily: { Title: "聊天字体", SubTitle: "聊天内容的字体,若置空则应用全局默认字体", Placeholder: "字体名称", }, InjectSystemPrompts: { Title: "注入系统级提示信息", SubTitle: "强制给每次请求的消息列表开头添加一个模拟 ChatGPT 的系统提示", }, InputTemplate: { Title: "用户输入预处理", SubTitle: "用户最新的一条消息会填充到此模板", }, Update: { Version: (x: string) => `当前版本:${x}`, IsLatest: "已是最新版本", CheckUpdate: "检查更新", IsChecking: "正在检查更新...", FoundUpdate: (x: string) => `发现新版本:${x}`, GoToUpdate: "前往更新", Success: "更新成功!", Failed: "更新失败", }, SendKey: "发送键", Theme: "主题", TightBorder: "无边框模式", SendPreviewBubble: { Title: "预览气泡", SubTitle: "在预览气泡中预览 Markdown 内容", }, AutoGenerateTitle: { Title: "自动生成标题", SubTitle: "根据对话内容生成合适的标题", }, Sync: { CloudState: "云端数据", NotSyncYet: "还没有进行过同步", Success: "同步成功", Fail: "同步失败", Config: { Modal: { Title: "配置云同步", Check: "检查可用性", }, SyncType: { Title: "同步类型", SubTitle: "选择喜爱的同步服务器", }, Proxy: { Title: "启用代理", SubTitle: "在浏览器中同步时,必须启用代理以避免跨域限制", }, ProxyUrl: { Title: "代理地址", SubTitle: "仅适用于本项目自带的跨域代理", }, WebDav: { Endpoint: "WebDAV 地址", UserName: "用户名", Password: "密码", }, UpStash: { Endpoint: "UpStash Redis REST Url", UserName: "备份名称", Password: "UpStash Redis REST Token", }, }, LocalState: "本地数据", Overview: (overview: any) => { return `${overview.chat} 次对话,${overview.message} 条消息,${overview.prompt} 条提示词,${overview.mask} 个面具`; }, ImportFailed: "导入失败", }, Mask: { Splash: { Title: "面具启动页", SubTitle: "新建聊天时,展示面具启动页", }, Builtin: { Title: "隐藏内置面具", SubTitle: "在所有面具列表中隐藏内置面具", }, }, Prompt: { Disable: { Title: "禁用提示词自动补全", SubTitle: "在输入框开头输入 / 即可触发自动补全", }, List: "自定义提示词列表", ListCount: (builtin: number, custom: number) => `内置 ${builtin} 条,用户定义 ${custom} 条`, Edit: "编辑", Modal: { Title: "提示词列表", Add: "新建", Search: "搜索提示词", }, EditModal: { Title: "编辑提示词", }, }, HistoryCount: { Title: "附带历史消息数", SubTitle: "每次请求携带的历史消息数", }, CompressThreshold: { Title: "历史消息长度压缩阈值", SubTitle: "当未压缩的历史消息超过该值时,将进行压缩", }, Usage: { Title: "余额查询", SubTitle(used: any, total: any) { return `本月已使用 $${used},订阅总额 $${total}`; }, IsChecking: "正在检查…", Check: "重新检查", NoAccess: "输入 API Key 或访问密码查看余额", }, Access: { SaasStart: { Title: "使用 NextChat AI", Label: "(性价比最高的方案)", SubTitle: "由 NextChat 官方维护, 零配置开箱即用,支持 OpenAI o1, GPT-4o, Claude-3.5 等最新大模型", ChatNow: "立刻对话", }, AccessCode: { Title: "访问密码", SubTitle: "管理员已开启加密访问", Placeholder: "请输入访问密码", }, CustomEndpoint: { Title: "自定义接口", SubTitle: "是否使用自定义 Azure 或 OpenAI 服务", }, Provider: { Title: "模型服务商", SubTitle: "切换不同的服务商", }, OpenAI: { ApiKey: { Title: "API Key", SubTitle: "使用自定义 OpenAI Key 绕过密码访问限制", Placeholder: "OpenAI API Key", }, Endpoint: { Title: "接口地址", SubTitle: "除默认地址外,必须包含 http(s)://", }, }, Azure: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义 Azure Key 绕过密码访问限制", Placeholder: "Azure API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, ApiVerion: { Title: "接口版本 (azure api version)", SubTitle: "选择指定的部分版本", }, }, Anthropic: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义 Anthropic Key 绕过密码访问限制", Placeholder: "Anthropic API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, ApiVerion: { Title: "接口版本 (claude api version)", SubTitle: "选择一个特定的 API 版本输入", }, }, Google: { ApiKey: { Title: "API 密钥", SubTitle: "从 Google AI 获取您的 API 密钥", Placeholder: "Google AI API KEY", }, Endpoint: { Title: "终端地址", SubTitle: "示例:", }, ApiVersion: { Title: "API 版本(仅适用于 gemini-pro)", SubTitle: "选择一个特定的 API 版本", }, GoogleSafetySettings: { Title: "Google 安全过滤级别", SubTitle: "设置内容过滤级别", }, }, Baidu: { ApiKey: { Title: "API Key", SubTitle: "使用自定义 Baidu API Key", Placeholder: "Baidu API Key", }, SecretKey: { Title: "Secret Key", SubTitle: "使用自定义 Baidu Secret Key", Placeholder: "Baidu Secret Key", }, Endpoint: { Title: "接口地址", SubTitle: "不支持自定义前往.env配置", }, }, Tencent: { ApiKey: { Title: "API Key", SubTitle: "使用自定义腾讯云API Key", Placeholder: "Tencent API Key", }, SecretKey: { Title: "Secret Key", SubTitle: "使用自定义腾讯云Secret Key", Placeholder: "Tencent Secret Key", }, Endpoint: { Title: "接口地址", SubTitle: "不支持自定义前往.env配置", }, }, ByteDance: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义 ByteDance API Key", Placeholder: "ByteDance API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, Alibaba: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义阿里云API Key", Placeholder: "Alibaba Cloud API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, Moonshot: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义月之暗面API Key", Placeholder: "Moonshot API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, DeepSeek: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义DeepSeek API Key", Placeholder: "DeepSeek API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, XAI: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义XAI API Key", Placeholder: "XAI API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, ChatGLM: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义 ChatGLM API Key", Placeholder: "ChatGLM API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, SiliconFlow: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义硅基流动 API Key", Placeholder: "硅基流动 API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, Stability: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义 Stability API Key", Placeholder: "Stability API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, Iflytek: { ApiKey: { Title: "ApiKey", SubTitle: "从讯飞星火控制台获取的 APIKey", Placeholder: "APIKey", }, ApiSecret: { Title: "ApiSecret", SubTitle: "从讯飞星火控制台获取的 APISecret", Placeholder: "APISecret", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, CustomModel: { Title: "自定义模型名", SubTitle: "增加自定义模型可选项,使用英文逗号隔开", }, AI302: { ApiKey: { Title: "接口密钥", SubTitle: "使用自定义302.AI API Key", Placeholder: "302.AI API Key", }, Endpoint: { Title: "接口地址", SubTitle: "样例:", }, }, }, Model: "模型 (model)", CompressModel: { Title: "对话摘要模型", SubTitle: "用于压缩历史记录、生成对话标题的模型", }, Temperature: { Title: "随机性 (temperature)", SubTitle: "值越大,回复越随机", }, TopP: { Title: "核采样 (top_p)", SubTitle: "与随机性类似,但不要和随机性一起更改", }, MaxTokens: { Title: "单次回复限制 (max_tokens)", SubTitle: "单次交互所用的最大 Token 数", }, PresencePenalty: { Title: "话题新鲜度 (presence_penalty)", SubTitle: "值越大,越有可能扩展到新话题", }, FrequencyPenalty: { Title: "频率惩罚度 (frequency_penalty)", SubTitle: "值越大,越有可能降低重复字词", }, TTS: { Enable: { Title: "启用文本转语音", SubTitle: "启用文本生成语音服务", }, Autoplay: { Title: "启用自动朗读", SubTitle: "自动生成语音并播放,需先开启文本转语音开关", }, Model: "模型", Engine: "转换引擎", Voice: { Title: "声音", SubTitle: "生成语音时使用的声音", }, Speed: { Title: "速度", SubTitle: "生成语音的速度", }, }, Realtime: { Enable: { Title: "实时聊天", SubTitle: "开启实时聊天功能", }, Provider: { Title: "模型服务商", SubTitle: "切换不同的服务商", }, Model: { Title: "模型", SubTitle: "选择一个模型", }, ApiKey: { Title: "API Key", SubTitle: "API Key", Placeholder: "API Key", }, Azure: { Endpoint: { Title: "接口地址", SubTitle: "接口地址", }, Deployment: { Title: "部署名称", SubTitle: "部署名称", }, }, Temperature: { Title: "随机性 (temperature)", SubTitle: "值越大,回复越随机", }, }, }, Store: { DefaultTopic: "新的聊天", BotHello: "有什么可以帮你的吗", Error: "出错了,稍后重试吧", Prompt: { History: (content: string) => "这是历史聊天总结作为前情提要:" + content, Topic: "使用四到五个字直接返回这句话的简要主题,不要解释、不要标点、不要语气词、不要多余文本,不要加粗,如果没有主题,请直接返回“闲聊”", Summarize: "简要总结一下对话内容,用作后续的上下文提示 prompt,控制在 200 字以内", }, }, Copy: { Success: "已写入剪贴板", Failed: "复制失败,请赋予剪贴板权限", }, Download: { Success: "内容已下载到您的目录。", Failed: "下载失败。", }, Context: { Toast: (x: any) => `包含 ${x} 条预设提示词`, Edit: "当前对话设置", Add: "新增一条对话", Clear: "上下文已清除", Revert: "恢复上下文", }, Discovery: { Name: "发现", }, Mcp: { Name: "MCP", }, FineTuned: { Sysmessage: "你是一个助手", }, SearchChat: { Name: "搜索聊天记录", Page: { Title: "搜索聊天记录", Search: "输入搜索关键词", NoResult: "没有找到结果", NoData: "没有数据", Loading: "加载中", SubTitle: (count: number) => `搜索到 ${count} 条结果`, }, Item: { View: "查看", }, }, Plugin: { Name: "插件", Page: { Title: "插件", SubTitle: (count: number) => `${count} 个插件`, Search: "搜索插件", Create: "新建", Find: "您可以在Github上找到优秀的插件:", }, Item: { Info: (count: number) => `${count} 方法`, View: "查看", Edit: "编辑", Delete: "删除", DeleteConfirm: "确认删除?", }, Auth: { None: "不需要授权", Basic: "Basic", Bearer: "Bearer", Custom: "自定义", CustomHeader: "自定义参数名称", Token: "Token", Proxy: "使用代理", ProxyDescription: "使用代理解决 CORS 错误", Location: "位置", LocationHeader: "Header", LocationQuery: "Query", LocationBody: "Body", }, EditModal: { Title: (readonly: boolean) => `编辑插件 ${readonly ? "(只读)" : ""}`, Download: "下载", Auth: "授权方式", Content: "OpenAPI Schema", Load: "从网页加载", Method: "方法", Error: "格式错误", }, }, Mask: { Name: "面具", Page: { Title: "预设角色面具", SubTitle: (count: number) => `${count} 个预设角色定义`, Search: "搜索角色面具", Create: "新建", }, Item: { Info: (count: number) => `包含 ${count} 条预设对话`, Chat: "对话", View: "查看", Edit: "编辑", Delete: "删除", DeleteConfirm: "确认删除?", }, EditModal: { Title: (readonly: boolean) => `编辑预设面具 ${readonly ? "(只读)" : ""}`, Download: "下载预设", Clone: "克隆预设", }, Config: { Avatar: "角色头像", Name: "角色名称", Sync: { Title: "使用全局设置", SubTitle: "当前对话是否使用全局模型设置", Confirm: "当前对话的自定义设置将会被自动覆盖,确认启用全局设置?", }, HideContext: { Title: "隐藏预设对话", SubTitle: "隐藏后预设对话不会出现在聊天界面", }, Artifacts: { Title: "启用Artifacts", SubTitle: "启用之后可以直接渲染HTML页面", }, CodeFold: { Title: "启用代码折叠", SubTitle: "启用之后可以自动折叠/展开过长的代码块", }, Share: { Title: "分享此面具", SubTitle: "生成此面具的直达链接", Action: "复制链接", }, }, }, NewChat: { Return: "返回", Skip: "直接开始", NotShow: "不再展示", ConfirmNoShow: "确认禁用?禁用后可以随时在设置中重新启用。", Title: "挑选一个面具", SubTitle: "现在开始,与面具背后的灵魂思维碰撞", More: "查看全部", }, URLCommand: { Code: "检测到链接中已经包含访问码,是否自动填入?", Settings: "检测到链接中包含了预制设置,是否自动填入?", }, UI: { Confirm: "确认", Cancel: "取消", Close: "关闭", Create: "新建", Edit: "编辑", Export: "导出", Import: "导入", Sync: "同步", Config: "配置", }, Exporter: { Description: { Title: "只有清除上下文之后的消息会被展示", }, Model: "模型", Messages: "消息", Topic: "主题", Time: "时间", }, SdPanel: { Prompt: "画面提示", NegativePrompt: "否定提示", PleaseInput: (name: string) => `请输入${name}`, AspectRatio: "横纵比", ImageStyle: "图像风格", OutFormat: "输出格式", AIModel: "AI模型", ModelVersion: "模型版本", Submit: "提交生成", ParamIsRequired: (name: string) => `${name}不能为空`, Styles: { D3Model: "3D模型", AnalogFilm: "模拟电影", Anime: "动漫", Cinematic: "电影风格", ComicBook: "漫画书", DigitalArt: "数字艺术", Enhance: "增强", FantasyArt: "幻想艺术", Isometric: "等角", LineArt: "线描", LowPoly: "低多边形", ModelingCompound: "建模材料", NeonPunk: "霓虹朋克", Origami: "折纸", Photographic: "摄影", PixelArt: "像素艺术", TileTexture: "贴图", }, }, Sd: { SubTitle: (count: number) => `共 ${count} 条绘画`, Actions: { Params: "查看参数", Copy: "复制提示词", Delete: "删除", Retry: "重试", ReturnHome: "返回首页", History: "查看历史", }, EmptyRecord: "暂无绘画记录", Status: { Name: "状态", Success: "成功", Error: "失败", Wait: "等待中", Running: "运行中", }, Danger: { Delete: "确认删除?", }, GenerateParams: "生成参数", Detail: "详情", }, }; type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T; export type LocaleType = typeof cn; export type PartialLocaleType = DeepPartial<typeof cn>; export default cn;
typescript
MIT
c3b8c1587c04fff05f7b42276a43016e87771527
2026-01-04T15:25:31.858944Z
false