Compare commits

...

34 Commits

Author SHA1 Message Date
Mike Klimin
34307fd259 Merge 956ec96d51 into 3809375694 2025-04-20 22:00:37 +08:00
RiverRay
3809375694 Merge pull request #6457 from ACTOR-ALCHEMIST/main
Some checks failed
Run Tests / test (push) Has been cancelled
Support OpenAI o3 and o4-mini
2025-04-19 16:00:41 +08:00
RiverRay
1b0de25986 Update README.md 2025-04-19 15:59:31 +08:00
RiverRay
865c45dd29 Update README.md 2025-04-19 15:56:53 +08:00
RiverRay
1f5d8e6d9c Merge pull request #6458 from ChatGPTNextWeb/Leizhenpeng-patch-7
Update README.md
2025-04-19 15:50:48 +08:00
RiverRay
c9ef6d58ed Update README.md 2025-04-19 15:50:17 +08:00
Jasper Hu
2d7229d2b8 feat: 支持 OpenAI 新模型 o3 与 o4-mini,并适配新参数 2025-04-18 20:36:07 +01:00
RiverRay
11b37c15bd Merge pull request #6450 from stephen-zeng/main
Some checks failed
Run Tests / test (push) Has been cancelled
Add gpt-4.1 family & gpt-4.5-preview support
2025-04-17 08:29:19 +08:00
QwQwQ
1d0038f17d add gpt-4.5-preview support 2025-04-16 22:10:47 +08:00
QwQwQ
619fa519c0 add gpt-4.1 family support 2025-04-16 22:02:35 +08:00
RiverRay
48469bd8ca Merge pull request #6392 from ChatGPTNextWeb/Leizhenpeng-patch-6
Some checks failed
Run Tests / test (push) Has been cancelled
Update README.md
2025-03-20 17:52:02 +08:00
RiverRay
5a5e887f2b Update README.md 2025-03-20 17:51:47 +08:00
Mihail Klimin
956ec96d51 fix(types): improve typings in stream.ts
- Replace generic Function type with specific () => void for unlisten
- Enhance typing for setRequestId from Function to ((value: number) => void)
- Address code review feedback from Biome linter
2025-03-16 12:03:49 +03:00
Mihail Klimin
8fa7c14f18 feat(tauri): Migrate from Tauri v1 to v2
# Summary
This commit completes the migration from Tauri v1 to v2, resolves configuration issues, upgrades Next.js, and adds test coverage for critical components to ensure stability during the transition.

# Details
## Tauri v2 Migration
- Updated Tauri dependencies to v2.3.0 series in package.json
- Restructured build configuration in `/app/config/build.ts` to align with Tauri v2 requirements
- Fixed imports and API usage patterns across the codebase
- Added compatibility layer for window.__TAURI__ references to maintain backward compatibility

## Next.js Issues
- Upgraded Next.js from 14.1.1 to 14.2.24
- Resolved caching problems with Server Actions
- Updated eslint-config-next to match the new version
- Cleared Next.js cache and temporary files to address build issues

## Testing & Stability
- Added comprehensive tests for `stream.ts` to verify streaming functionality
- Created mocks for Tauri API to support test environment
- Verified that critical functionality continues to work correctly
- Translated all comments to English for consistency

## Infrastructure
- Fixed peer dependency warnings during installation
- Ensured proper integration with Tauri v2 plugins (clipboard-manager, dialog, fs, http, notification, shell, updater, window-state)

# Approach
Prioritized stability by:
1. Making minimal necessary changes to configuration files
2. Preserving most `window.__TAURI__` calls as they still function in v2
3. Planning gradual migration to new APIs with test coverage for critical components
4. Documenting areas that will require future attention

# Testing
- Created unit tests for critical streaming functionality
- Performed manual testing of key application features
- Verified successful build and launch with Tauri v2

# Future Work
- Future PRs will gradually replace deprecated Tauri v1 API calls with v2 equivalents
- Additional test coverage will be added for other critical components
2025-03-16 02:14:47 +03:00
RiverRay
b6f5d75656 Merge pull request #6344 from vangie/fix/jest-setup-esm
Some checks failed
Run Tests / test (push) Has been cancelled
test: fix unit test failures
2025-03-14 20:04:56 +08:00
Vangie Du
0d41a17ef6 test: fix unit test failures 2025-03-07 14:49:17 +08:00
RiverRay
f7cde17919 Merge pull request #6292 from Little-LittleProgrammer/feature/alibaba-omni-support
Some checks failed
Run Tests / test (push) Has been cancelled
feat(alibaba): Added alibaba vision model and omni model support
2025-03-01 10:25:16 +08:00
RiverRay
570cbb34b6 Merge pull request #6310 from agi-dude/patch-1
Remove duplicate links
2025-03-01 10:24:38 +08:00
RiverRay
7aa9ae0a3e Merge pull request #6311 from ChatGPTNextWeb/6305-bugthe-first-message-except-the-system-message-of-deepseek-reasoner-must-be-a-user-message-but-an-assistant-message-detected
Some checks are pending
Run Tests / test (push) Waiting to run
fix: enforce that the first message (excluding system messages) is a …
2025-02-28 19:48:09 +08:00
Kadxy
2d4180f5be fix: update request payload to use filtered messages in Deepseek API 2025-02-28 13:59:30 +08:00
Kadxy
9f0182b55e fix: enforce that the first message (excluding system messages) is a user message in the Deepseek API 2025-02-28 13:54:58 +08:00
Mr. AGI
ad6666eeaf Update README.md 2025-02-28 10:47:52 +05:00
EvanWu
a2c4e468a0 fix(app/utils/chat.ts): fix type error 2025-02-26 19:58:32 +08:00
RiverRay
2167076652 Merge pull request #6293 from hyiip/main
Some checks failed
Run Tests / test (push) Has been cancelled
claude 3.7 support
2025-02-26 18:41:28 +08:00
RiverRay
e123076250 Merge pull request #6295 from rexkyng/patch-1
Fix: Improve Mistral icon detection and remove redundant code.
2025-02-26 18:39:59 +08:00
Rex Ng
ebcb4db245 Fix: Improve Mistral icon detection and remove redundant code.
- Added "codestral" to the list of acceptable names for the Mistral icon, ensuring proper detection.
- Removed duplicate `toLowerCase()` calls.
2025-02-25 14:30:18 +08:00
EvanWu
0a25a1a8cb refacto(app/utils/chat.ts)r: optimize function preProcessImageContentBase 2025-02-25 09:22:47 +08:00
hyiip
f3154b20a5 claude 3.7 support 2025-02-25 03:55:24 +08:00
EvanWu
b709ee3983 feat(alibaba): Added alibaba vision model and omni model support 2025-02-24 20:18:07 +08:00
RiverRay
f5f3ce94f6 Update README.md
Some checks failed
Run Tests / test (push) Has been cancelled
2025-02-21 08:56:43 +08:00
RiverRay
2b5f600308 Update README.md 2025-02-21 08:55:40 +08:00
RiverRay
b966107117 Merge pull request #6235 from DBCDK/danish-locale
Some checks failed
Run Tests / test (push) Has been cancelled
Translation to danish
2025-02-17 22:58:01 +08:00
Rasmus Erik Voel Jensen
90827fc593 danish rewording / improved button label 2025-02-15 13:08:58 +01:00
Rasmus Erik Voel Jensen
008e339b6d danish locale 2025-02-15 12:52:44 +01:00
33 changed files with 16947 additions and 1942 deletions

View File

@@ -7,7 +7,7 @@
<h1 align="center">NextChat (ChatGPT Next Web)</h1>
<h1 align="center">NextChat</h1>
English / [简体中文](./README_CN.md)
@@ -22,8 +22,7 @@ English / [简体中文](./README_CN.md)
[![MacOS][MacOS-image]][download-url]
[![Linux][Linux-image]][download-url]
[NextChatAI](https://nextchat.dev/chat?utm_source=readme) / [Web App Demo](https://app.nextchat.dev) / [Desktop App](https://github.com/Yidadaa/ChatGPT-Next-Web/releases)
[NextChatAI](https://nextchat.club?utm_source=readme) / [Web App Demo](https://app.nextchat.dev) / [Desktop App](https://github.com/Yidadaa/ChatGPT-Next-Web/releases) / [Discord](https://discord.gg/YCkeafCafC) / [Enterprise Edition](#enterprise-edition) / [Twitter](https://twitter.com/NextChatDev)
[NextChatAI](https://nextchat.club?utm_source=readme) / [iOS APP](https://apps.apple.com/us/app/nextchat-ai/id6743085599) / [Web App Demo](https://app.nextchat.dev) / [Desktop App](https://github.com/Yidadaa/ChatGPT-Next-Web/releases) / [Enterprise Edition](#enterprise-edition)
[saas-url]: https://nextchat.club?utm_source=readme
@@ -41,13 +40,14 @@ English / [简体中文](./README_CN.md)
</div>
## 🥳 Cheer for DeepSeek, China's AI star!
> Purpose-Built UI for DeepSeek Reasoner Model
## 🥳 Cheer for NextChat iOS Version Online!
> [👉 Click Here to Install Now](https://apps.apple.com/us/app/nextchat-ai/id6743085599)
> [❤️ Source Code Coming Soon](https://github.com/ChatGPTNextWeb/NextChat-iOS)
![Github iOS Image](https://github.com/user-attachments/assets/e0aa334f-4c13-4dc9-8310-e3b09fa4b9f3)
<img src="https://github.com/user-attachments/assets/f3952210-3af1-4dc0-9b81-40eaa4847d9a"/>
## 🫣 NextChat Support MCP !
> Before build, please set env ENABLE_MCP=true

View File

@@ -40,6 +40,11 @@ export interface MultimodalContent {
};
}
export interface MultimodalContentForAlibaba {
text?: string;
image?: string;
}
export interface RequestMessage {
role: MessageRole;
content: string | MultimodalContent[];

View File

@@ -7,7 +7,10 @@ import {
ChatMessageTool,
usePluginStore,
} from "@/app/store";
import { streamWithThink } from "@/app/utils/chat";
import {
preProcessImageContentForAlibabaDashScope,
streamWithThink,
} from "@/app/utils/chat";
import {
ChatOptions,
getHeaders,
@@ -15,12 +18,14 @@ import {
LLMModel,
SpeechOptions,
MultimodalContent,
MultimodalContentForAlibaba,
} from "../api";
import { getClientConfig } from "@/app/config/client";
import {
getMessageTextContent,
getMessageTextContentWithoutThinking,
getTimeoutMSByModel,
isVisionModel,
} from "@/app/utils";
import { fetch } from "@/app/utils/stream";
@@ -89,14 +94,6 @@ export class QwenApi implements LLMApi {
}
async chat(options: ChatOptions) {
const messages = options.messages.map((v) => ({
role: v.role,
content:
v.role === "assistant"
? getMessageTextContentWithoutThinking(v)
: getMessageTextContent(v),
}));
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
@@ -105,6 +102,21 @@ export class QwenApi implements LLMApi {
},
};
const visionModel = isVisionModel(options.config.model);
const messages: ChatOptions["messages"] = [];
for (const v of options.messages) {
const content = (
visionModel
? await preProcessImageContentForAlibabaDashScope(v.content)
: v.role === "assistant"
? getMessageTextContentWithoutThinking(v)
: getMessageTextContent(v)
) as any;
messages.push({ role: v.role, content });
}
const shouldStream = !!options.config.stream;
const requestPayload: RequestPayload = {
model: modelConfig.model,
@@ -129,7 +141,7 @@ export class QwenApi implements LLMApi {
"X-DashScope-SSE": shouldStream ? "enable" : "disable",
};
const chatPath = this.path(Alibaba.ChatPath);
const chatPath = this.path(Alibaba.ChatPath(modelConfig.model));
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
@@ -162,7 +174,7 @@ export class QwenApi implements LLMApi {
const json = JSON.parse(text);
const choices = json.output.choices as Array<{
message: {
content: string | null;
content: string | null | MultimodalContentForAlibaba[];
tool_calls: ChatMessageTool[];
reasoning_content: string | null;
};
@@ -212,7 +224,9 @@ export class QwenApi implements LLMApi {
} else if (content && content.length > 0) {
return {
isThinking: false,
content: content,
content: Array.isArray(content)
? content.map((item) => item.text).join(",")
: content,
};
}

View File

@@ -75,6 +75,25 @@ export class DeepSeekApi implements LLMApi {
}
}
// 检测并修复消息顺序确保除system外的第一个消息是user
const filteredMessages: ChatOptions["messages"] = [];
let hasFoundFirstUser = false;
for (const msg of messages) {
if (msg.role === "system") {
// Keep all system messages
filteredMessages.push(msg);
} else if (msg.role === "user") {
// User message directly added
filteredMessages.push(msg);
hasFoundFirstUser = true;
} else if (hasFoundFirstUser) {
// After finding the first user message, all subsequent non-system messages are retained.
filteredMessages.push(msg);
}
// If hasFoundFirstUser is false and it is not a system message, it will be skipped.
}
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
@@ -85,7 +104,7 @@ export class DeepSeekApi implements LLMApi {
};
const requestPayload: RequestPayload = {
messages,
messages: filteredMessages,
stream: options.config.stream,
model: modelConfig.model,
temperature: modelConfig.temperature,

View File

@@ -198,7 +198,8 @@ export class ChatGPTApi implements LLMApi {
const isDalle3 = _isDalle3(options.config.model);
const isO1OrO3 =
options.config.model.startsWith("o1") ||
options.config.model.startsWith("o3");
options.config.model.startsWith("o3") ||
options.config.model.startsWith("o4-mini");
if (isDalle3) {
const prompt = getMessageTextContent(
options.messages.slice(-1)?.pop() as any,
@@ -243,7 +244,7 @@ export class ChatGPTApi implements LLMApi {
}
// add max_tokens to vision model
if (visionModel) {
if (visionModel && !isO1OrO3) {
requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
}
}

View File

@@ -66,11 +66,11 @@ export function Avatar(props: { model?: ModelType; avatar?: string }) {
LlmIcon = BotIconGemma;
} else if (modelName.startsWith("claude")) {
LlmIcon = BotIconClaude;
} else if (modelName.toLowerCase().includes("llama")) {
} else if (modelName.includes("llama")) {
LlmIcon = BotIconMeta;
} else if (modelName.startsWith("mixtral")) {
} else if (modelName.startsWith("mixtral") || modelName.startsWith("codestral")) {
LlmIcon = BotIconMistral;
} else if (modelName.toLowerCase().includes("deepseek")) {
} else if (modelName.includes("deepseek")) {
LlmIcon = BotIconDeepseek;
} else if (modelName.startsWith("moonshot")) {
LlmIcon = BotIconMoonshot;
@@ -85,7 +85,7 @@ export function Avatar(props: { model?: ModelType; avatar?: string }) {
} else if (modelName.startsWith("doubao") || modelName.startsWith("ep-")) {
LlmIcon = BotIconDoubao;
} else if (
modelName.toLowerCase().includes("glm") ||
modelName.includes("glm") ||
modelName.startsWith("cogview-") ||
modelName.startsWith("cogvideox-")
) {

View File

@@ -40,6 +40,8 @@ import { type ClientApi, getClientApi } from "../client/api";
import { getMessageTextContent } from "../utils";
import { MaskAvatar } from "./mask";
import clsx from "clsx";
import { save } from "@tauri-apps/plugin-dialog";
import { writeFile } from "@tauri-apps/plugin-fs";
const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
loading: () => <LoadingIcon />,
@@ -456,7 +458,7 @@ export function ImagePreviewer(props: {
if (isMobile || (isApp && window.__TAURI__)) {
if (isApp && window.__TAURI__) {
const result = await window.__TAURI__.dialog.save({
const result = await save({
defaultPath: `${props.topic}.png`,
filters: [
{
@@ -474,7 +476,7 @@ export function ImagePreviewer(props: {
const response = await fetch(blob);
const buffer = await response.arrayBuffer();
const uint8Array = new Uint8Array(buffer);
await window.__TAURI__.fs.writeBinaryFile(result, uint8Array);
await writeFile(result, uint8Array);
showToast(Locale.Download.Success);
} else {
showToast(Locale.Download.Failed);

View File

@@ -10,7 +10,7 @@ export const getBuildConfig = () => {
const buildMode = process.env.BUILD_MODE ?? "standalone";
const isApp = !!process.env.BUILD_APP;
const version = "v" + tauriConfig.package.version;
const version = "v" + tauriConfig.version;
const commitInfo = (() => {
try {

View File

@@ -221,7 +221,12 @@ export const ByteDance = {
export const Alibaba = {
ExampleEndpoint: ALIBABA_BASE_URL,
ChatPath: "v1/services/aigc/text-generation/generation",
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 = {
@@ -412,6 +417,14 @@ export const KnowledgeCutOffDate: Record<string, string> = {
"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",
@@ -453,6 +466,7 @@ export const DEFAULT_TTS_VOICES = [
export const VISION_MODEL_REGEXES = [
/vision/,
/gpt-4o/,
/gpt-4\.1/,
/claude-3/,
/gemini-1\.5/,
/gemini-exp/,
@@ -464,6 +478,8 @@ export const VISION_MODEL_REGEXES = [
/^dall-e-3$/, // Matches exactly "dall-e-3"
/glm-4v/,
/vl/i,
/o3/,
/o4-mini/,
];
export const EXCLUDE_VISION_MODEL_REGEXES = [/claude-3-5-haiku-20241022/];
@@ -480,6 +496,14 @@ const openaiModels = [
"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-4o",
"gpt-4o-2024-05-13",
"gpt-4o-2024-08-06",
@@ -494,6 +518,8 @@ const openaiModels = [
"o1-mini",
"o1-preview",
"o3-mini",
"o3",
"o4-mini",
];
const googleModels = [
@@ -535,6 +561,8 @@ const anthropicModels = [
"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",
];
const baiduModels = [
@@ -568,6 +596,9 @@ const alibabaModes = [
"qwen-max-0403",
"qwen-max-0107",
"qwen-max-longcontext",
"qwen-omni-turbo",
"qwen-vl-plus",
"qwen-vl-max",
];
const tencentModels = [

832
app/locales/da.ts Normal file
View File

@@ -0,0 +1,832 @@
import { getClientConfig } from "../config/client";
import { SubmitKey } from "../store/config";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
import { PartialLocaleType } from "./index";
const isApp = !!getClientConfig()?.isApp;
const da: PartialLocaleType = {
WIP: "Der kommer snart mere...",
Error: {
Unauthorized: isApp
? `Hov, der skete en fejl. Sådan kan du komme videre:
\\ 1⃣ Er du ny her? [Tryk for at starte nu 🚀](${SAAS_CHAT_UTM_URL})
\\ 2⃣ Vil du bruge dine egne OpenAI-nøgler? [Tryk her](/#/settings) for at ændre indstillinger ⚙️`
: `Hov, der skete en fejl. Lad os løse det:
\\ 1⃣ Er du ny her? [Tryk for at starte nu 🚀](${SAAS_CHAT_UTM_URL})
\\ 2⃣ Bruger du en privat opsætning? [Tryk her](/#/auth) for at taste din nøgle 🔑
\\ 3⃣ Vil du bruge dine egne OpenAI-nøgler? [Tryk her](/#/settings) for at ændre indstillinger ⚙️
`,
},
Auth: {
Return: "Tilbage",
Title: "Adgangskode",
Tips: "Skriv venligst koden herunder",
SubTips: "Eller brug din egen OpenAI- eller Google-nøgle",
Input: "Adgangskode",
Confirm: "OK",
Later: "Senere",
SaasTips: "Hvis det er for svært, kan du starte nu",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} beskeder`,
},
Chat: {
SubTitle: (count: number) => `${count} beskeder`,
EditMessage: {
Title: "Rediger beskeder",
Topic: {
Title: "Emne",
SubTitle: "Skift emne for denne chat",
},
},
Actions: {
ChatList: "Gå til chatliste",
CompressedHistory: "Komprimeret historie",
Export: "Eksporter alle beskeder som Markdown",
Copy: "Kopiér",
Stop: "Stop",
Retry: "Prøv igen",
Pin: "Fastgør",
PinToastContent: "1 besked er nu fastgjort",
PinToastAction: "Se",
Delete: "Slet",
Edit: "Rediger",
FullScreen: "Fuld skærm",
RefreshTitle: "Opdatér titel",
RefreshToast: "Anmodning om ny titel sendt",
Speech: "Afspil",
StopSpeech: "Stop",
},
Commands: {
new: "Ny chat",
newm: "Ny chat med persona",
next: "Næste chat",
prev: "Forrige chat",
clear: "Ryd alt før",
fork: "Kopiér chat",
del: "Slet chat",
},
InputActions: {
Stop: "Stop",
ToBottom: "Ned til nyeste",
Theme: {
auto: "Automatisk",
light: "Lyst tema",
dark: "Mørkt tema",
},
Prompt: "Prompts",
Masks: "Personaer",
Clear: "Ryd kontekst",
Settings: "Indstillinger",
UploadImage: "Upload billeder",
},
Rename: "Omdøb chat",
Typing: "Skriver…",
Input: (submitKey: string) => {
let inputHints = `${submitKey} for at sende`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += ", Shift + Enter for ny linje";
}
return (
inputHints + ", / for at søge i prompts, : for at bruge kommandoer"
);
},
Send: "Send",
StartSpeak: "Start oplæsning",
StopSpeak: "Stop oplæsning",
Config: {
Reset: "Nulstil til standard",
SaveAs: "Gem som persona",
},
IsContext: "Ekstra prompt til baggrund",
ShortcutKey: {
Title: "Hurtigtaster",
newChat: "Åbn ny chat",
focusInput: "Fokus på tekstfeltet",
copyLastMessage: "Kopiér sidste svar",
copyLastCode: "Kopiér sidste kodeblok",
showShortcutKey: "Vis hurtigtaster",
clearContext: "Ryd kontekst",
},
},
Export: {
Title: "Eksportér beskeder",
Copy: "Kopiér alt",
Download: "Download",
MessageFromYou: "Fra dig",
MessageFromChatGPT: "Fra ChatGPT",
Share: "Del til ShareGPT",
Format: {
Title: "Filformat",
SubTitle: "Vælg enten Markdown eller PNG-billede",
},
IncludeContext: {
Title: "Tag baggrund med",
SubTitle: "Skal ekstra baggrund (persona) med i eksporten?",
},
Steps: {
Select: "Vælg",
Preview: "Forhåndsvis",
},
Image: {
Toast: "Laver billede...",
Modal: "Tryk længe eller højreklik for at gemme",
},
Artifacts: {
Title: "Del side",
Error: "Fejl ved deling",
},
},
Select: {
Search: "Søg",
All: "Vælg alle",
Latest: "Vælg nyeste",
Clear: "Ryd alt",
},
Memory: {
Title: "Huskesætning",
EmptyContent: "Ingenting lige nu.",
Send: "Send huskesætning",
Copy: "Kopiér huskesætning",
Reset: "Nulstil chat",
ResetConfirm:
"Dette sletter nuværende samtale og hukommelse. Er du sikker?",
},
Home: {
NewChat: "Ny Chat",
DeleteChat: "Vil du slette den valgte chat?",
DeleteToast: "Chat slettet",
Revert: "Fortryd",
},
Settings: {
Title: "Indstillinger",
SubTitle: "Alle indstillinger",
ShowPassword: "Vis kodeord",
Danger: {
Reset: {
Title: "Nulstil alle indstillinger",
SubTitle: "Gendan alt til standard",
Action: "Nulstil",
Confirm: "Vil du virkelig nulstille alt?",
},
Clear: {
Title: "Slet alle data",
SubTitle: "Sletter alt om beskeder og indstillinger",
Action: "Slet",
Confirm: "Er du sikker på, at du vil slette alt?",
},
},
Lang: {
Name: "Language",
All: "Alle sprog",
},
Avatar: "Avatar",
FontSize: {
Title: "Skriftstørrelse",
SubTitle: "Vælg, hvor stor teksten skal være",
},
FontFamily: {
Title: "Skrifttype",
SubTitle: "Hvis tom, bruger den standard skrifttype",
Placeholder: "Skrifttype-navn",
},
InjectSystemPrompts: {
Title: "Tilføj system-prompt",
SubTitle: "Læg altid en ekstra prompt først i anmodninger",
},
InputTemplate: {
Title: "Tekstskabelon",
SubTitle: "Den seneste besked placeres i denne skabelon",
},
Update: {
Version: (x: string) => `Version: ${x}`,
IsLatest: "Du har nyeste version",
CheckUpdate: "Tjek efter opdatering",
IsChecking: "Tjekker...",
FoundUpdate: (x: string) => `Ny version fundet: ${x}`,
GoToUpdate: "Opdatér",
Success: "Opdatering lykkedes.",
Failed: "Opdatering mislykkedes.",
},
SendKey: "Tast for send",
Theme: "Tema",
TightBorder: "Stram kant",
SendPreviewBubble: {
Title: "Forhåndsvisnings-boble",
SubTitle: "Vis tekst, før den sendes",
},
AutoGenerateTitle: {
Title: "Lav titel automatisk",
SubTitle: "Foreslå en titel ud fra chatten",
},
Sync: {
CloudState: "Seneste opdatering",
NotSyncYet: "Endnu ikke synkroniseret",
Success: "Synkronisering lykkedes",
Fail: "Synkronisering mislykkedes",
Config: {
Modal: {
Title: "Indstil synk",
Check: "Tjek forbindelse",
},
SyncType: {
Title: "Synk-type",
SubTitle: "Vælg en synk-tjeneste",
},
Proxy: {
Title: "Aktivér proxy",
SubTitle: "Brug proxy for at undgå netværksproblemer",
},
ProxyUrl: {
Title: "Proxy-adresse",
SubTitle: "Bruges kun til projektets egen proxy",
},
WebDav: {
Endpoint: "WebDAV-adresse",
UserName: "Brugernavn",
Password: "Kodeord",
},
UpStash: {
Endpoint: "UpStash Redis REST URL",
UserName: "Backup-navn",
Password: "UpStash Redis REST Token",
},
},
LocalState: "Lokale data",
Overview: (overview: any) =>
`${overview.chat} chats, ${overview.message} beskeder, ${overview.prompt} prompts, ${overview.mask} personaer`,
ImportFailed: "Import mislykkedes",
},
Mask: {
Splash: {
Title: "Persona-forside",
SubTitle: "Vis denne side, når du opretter ny chat",
},
Builtin: {
Title: "Skjul indbyggede personaer",
SubTitle: "Vis ikke de indbyggede personaer i listen",
},
},
Prompt: {
Disable: {
Title: "Slå auto-forslag fra",
SubTitle: "Tast / for at få forslag",
},
List: "Prompt-liste",
ListCount: (builtin: number, custom: number) =>
`${builtin} indbygget, ${custom} brugerdefineret`,
Edit: "Rediger",
Modal: {
Title: "Prompt-liste",
Add: "Tilføj",
Search: "Søg prompts",
},
EditModal: {
Title: "Rediger prompt",
},
},
HistoryCount: {
Title: "Antal beskeder, der følger med",
SubTitle: "Hvor mange af de tidligere beskeder, der sendes hver gang",
},
CompressThreshold: {
Title: "Komprimeringsgrænse",
SubTitle:
"Hvis chatten bliver for lang, vil den komprimeres efter dette antal tegn",
},
Usage: {
Title: "Brug og saldo",
SubTitle(used: any, total: any) {
return `Du har brugt $${used} i denne måned, og din grænse er $${total}.`;
},
IsChecking: "Tjekker...",
Check: "Tjek igen",
NoAccess: "Indtast API-nøgle for at se forbrug",
},
Access: {
AccessCode: {
Title: "Adgangskode",
SubTitle: "Adgangskontrol er slået til",
Placeholder: "Skriv kode her",
},
CustomEndpoint: {
Title: "Brugerdefineret adresse",
SubTitle: "Brug Azure eller OpenAI fra egen server",
},
Provider: {
Title: "Model-udbyder",
SubTitle: "Vælg Azure eller OpenAI",
},
OpenAI: {
ApiKey: {
Title: "OpenAI API-nøgle",
SubTitle: "Brug din egen nøgle",
Placeholder: "sk-xxx",
},
Endpoint: {
Title: "OpenAI Endpoint",
SubTitle: "Skal starte med http(s):// eller /api/openai som standard",
},
},
Azure: {
ApiKey: {
Title: "Azure Api Key",
SubTitle: "Hent din nøgle fra Azure-portalen",
Placeholder: "Azure Api Key",
},
Endpoint: {
Title: "Azure Endpoint",
SubTitle: "F.eks.: ",
},
ApiVerion: {
Title: "Azure Api Version",
SubTitle: "Hentet fra Azure-portalen",
},
},
Anthropic: {
ApiKey: {
Title: "Anthropic API-nøgle",
SubTitle: "Brug din egen Anthropic-nøgle",
Placeholder: "Anthropic API Key",
},
Endpoint: {
Title: "Endpoint-adresse",
SubTitle: "F.eks.: ",
},
ApiVerion: {
Title: "API-version (Claude)",
SubTitle: "Vælg den ønskede version",
},
},
Baidu: {
ApiKey: {
Title: "Baidu-nøgle",
SubTitle: "Din egen Baidu-nøgle",
Placeholder: "Baidu API Key",
},
SecretKey: {
Title: "Baidu hemmelig nøgle",
SubTitle: "Din egen hemmelige nøgle fra Baidu",
Placeholder: "Baidu Secret Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "Kan ikke ændres, se .env",
},
},
Tencent: {
ApiKey: {
Title: "Tencent-nøgle",
SubTitle: "Din egen nøgle fra Tencent",
Placeholder: "Tencent API Key",
},
SecretKey: {
Title: "Tencent hemmelig nøgle",
SubTitle: "Din egen hemmelige nøgle fra Tencent",
Placeholder: "Tencent Secret Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "Kan ikke ændres, se .env",
},
},
ByteDance: {
ApiKey: {
Title: "ByteDance-nøgle",
SubTitle: "Din egen nøgle til ByteDance",
Placeholder: "ByteDance API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
Alibaba: {
ApiKey: {
Title: "Alibaba-nøgle",
SubTitle: "Din egen Alibaba Cloud-nøgle",
Placeholder: "Alibaba Cloud API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
Moonshot: {
ApiKey: {
Title: "Moonshot-nøgle",
SubTitle: "Din egen Moonshot-nøgle",
Placeholder: "Moonshot API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
DeepSeek: {
ApiKey: {
Title: "DeepSeek-nøgle",
SubTitle: "Din egen DeepSeek-nøgle",
Placeholder: "DeepSeek API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
XAI: {
ApiKey: {
Title: "XAI-nøgle",
SubTitle: "Din egen XAI-nøgle",
Placeholder: "XAI API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
ChatGLM: {
ApiKey: {
Title: "ChatGLM-nøgle",
SubTitle: "Din egen ChatGLM-nøgle",
Placeholder: "ChatGLM API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
SiliconFlow: {
ApiKey: {
Title: "SiliconFlow-nøgle",
SubTitle: "Din egen SiliconFlow-nøgle",
Placeholder: "SiliconFlow API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
Stability: {
ApiKey: {
Title: "Stability-nøgle",
SubTitle: "Din egen Stability-nøgle",
Placeholder: "Stability API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
Iflytek: {
ApiKey: {
Title: "Iflytek API Key",
SubTitle: "Nøgle fra Iflytek",
Placeholder: "Iflytek API Key",
},
ApiSecret: {
Title: "Iflytek hemmelig nøgle",
SubTitle: "Hentet fra Iflytek",
Placeholder: "Iflytek API Secret",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
},
CustomModel: {
Title: "Egne modelnavne",
SubTitle: "Skriv komma-adskilte navne",
},
Google: {
ApiKey: {
Title: "Google-nøgle",
SubTitle: "Få din nøgle hos Google AI",
Placeholder: "Google AI API Key",
},
Endpoint: {
Title: "Adresse",
SubTitle: "F.eks.: ",
},
ApiVersion: {
Title: "API-version (til gemini-pro)",
SubTitle: "Vælg en bestemt version",
},
GoogleSafetySettings: {
Title: "Google sikkerhedsindstillinger",
SubTitle: "Vælg et niveau for indholdskontrol",
},
},
},
Model: "Model",
CompressModel: {
Title: "Opsummeringsmodel",
SubTitle: "Bruges til at korte historik ned og lave titel",
},
Temperature: {
Title: "Temperatur",
SubTitle: "Jo højere tal, jo mere kreativt svar",
},
TopP: {
Title: "Top P",
SubTitle: "Skal ikke ændres sammen med temperatur",
},
MaxTokens: {
Title: "Maks. længde",
SubTitle: "Hvor mange tokens (ord/stykker tekst) der kan bruges",
},
PresencePenalty: {
Title: "Nye emner",
SubTitle: "Jo højere tal, jo mere nyt indhold",
},
FrequencyPenalty: {
Title: "Gentagelsesstraf",
SubTitle: "Jo højere tal, jo mindre gentagelse",
},
TTS: {
Enable: {
Title: "Tænd for oplæsning (TTS)",
SubTitle: "Slå tekst-til-tale til",
},
Autoplay: {
Title: "Automatisk oplæsning",
SubTitle: "Laver lyd automatisk, hvis TTS er slået til",
},
Model: "Model",
Voice: {
Title: "Stemme",
SubTitle: "Hvilken stemme der bruges til lyd",
},
Speed: {
Title: "Hastighed",
SubTitle: "Hvor hurtigt der oplæses",
},
Engine: "TTS-motor",
},
Realtime: {
Enable: {
Title: "Live-chat",
SubTitle: "Slå live-svar til",
},
Provider: {
Title: "Modeludbyder",
SubTitle: "Vælg forskellig udbyder",
},
Model: {
Title: "Model",
SubTitle: "Vælg en model",
},
ApiKey: {
Title: "API-nøgle",
SubTitle: "Din nøgle",
Placeholder: "API-nøgle",
},
Azure: {
Endpoint: {
Title: "Adresse",
SubTitle: "Endpoint til Azure",
},
Deployment: {
Title: "Udrulningsnavn",
SubTitle: "Navn for dit Azure-setup",
},
},
Temperature: {
Title: "Temperatur",
SubTitle: "Højere tal = mere varierede svar",
},
},
},
Store: {
DefaultTopic: "Ny samtale",
BotHello: "Hej! Hvordan kan jeg hjælpe dig i dag?",
Error: "Noget gik galt. Prøv igen senere.",
Prompt: {
History: (content: string) =>
"Her er et kort resume af, hvad vi har snakket om: " + content,
Topic:
"Find en kort overskrift med 4-5 ord om emnet. Ingen tegnsætning eller anførselstegn.",
Summarize:
"Skriv et kort resumé (under 200 ord) af vores samtale til senere brug.",
},
},
Copy: {
Success: "Kopieret",
Failed: "Kunne ikke kopiere. Giv adgang til udklipsholder.",
},
Download: {
Success: "Filen er downloadet.",
Failed: "Download fejlede.",
},
Context: {
Toast: (x: any) => `Inkluderer ${x} ekstra prompts`,
Edit: "Chatindstillinger",
Add: "Tilføj prompt",
Clear: "Kontekst ryddet",
Revert: "Fortryd",
},
Discovery: {
Name: "Søgning og plugins",
},
Mcp: {
Name: "MCP",
},
FineTuned: {
Sysmessage: "Du er en hjælper, der skal...",
},
SearchChat: {
Name: "Søg",
Page: {
Title: "Søg i tidligere chats",
Search: "Skriv her for at søge",
NoResult: "Ingen resultater",
NoData: "Ingen data",
Loading: "Henter...",
SubTitle: (count: number) => `Fandt ${count} resultater`,
},
Item: {
View: "Vis",
},
},
Plugin: {
Name: "Plugin",
Page: {
Title: "Plugins",
SubTitle: (count: number) => `${count} plugins`,
Search: "Søg plugin",
Create: "Opret nyt",
Find: "Du kan finde flere plugins på GitHub: ",
},
Item: {
Info: (count: number) => `${count} metode`,
View: "Vis",
Edit: "Rediger",
Delete: "Slet",
DeleteConfirm: "Vil du slette?",
},
Auth: {
None: "Ingen",
Basic: "Basic",
Bearer: "Bearer",
Custom: "Tilpasset",
CustomHeader: "Parameternavn",
Token: "Token",
Proxy: "Brug Proxy",
ProxyDescription: "Løs CORS-problemer med Proxy",
Location: "Sted",
LocationHeader: "Header",
LocationQuery: "Query",
LocationBody: "Body",
},
EditModal: {
Title: (readonly: boolean) =>
`Rediger Plugin ${readonly ? "(skrivebeskyttet)" : ""}`,
Download: "Download",
Auth: "Godkendelsestype",
Content: "OpenAPI Schema",
Load: "Hent fra URL",
Method: "Metode",
Error: "Fejl i OpenAPI Schema",
},
},
Mask: {
Name: "Persona",
Page: {
Title: "Prompts som personaer",
SubTitle: (count: number) => `${count} skabeloner`,
Search: "Søg skabeloner",
Create: "Opret ny",
},
Item: {
Info: (count: number) => `${count} prompts`,
Chat: "Chat",
View: "Vis",
Edit: "Rediger",
Delete: "Slet",
DeleteConfirm: "Vil du slette?",
},
EditModal: {
Title: (readonly: boolean) =>
`Rediger skabelon ${readonly ? "(skrivebeskyttet)" : ""}`,
Download: "Download",
Clone: "Klon",
},
Config: {
Avatar: "Chat-avatar",
Name: "Chat-navn",
Sync: {
Title: "Brug globale indstillinger",
SubTitle: "Gældende for denne chat",
Confirm: "Erstat nuværende indstillinger med globale?",
},
HideContext: {
Title: "Skjul ekstra prompts",
SubTitle: "Vis dem ikke på chat-skærmen",
},
Artifacts: {
Title: "Brug Artefakter",
SubTitle: "Gør det muligt at vise HTML-sider",
},
CodeFold: {
Title: "Fold kode sammen",
SubTitle: "Luk/åbn lange kodestykker automatisk",
},
Share: {
Title: "Del denne persona",
SubTitle: "Få et link til denne skabelon",
Action: "Kopiér link",
},
},
},
NewChat: {
Return: "Tilbage",
Skip: "Start straks",
Title: "Vælg en persona",
SubTitle: "Chat med den persona, du vælger",
More: "Se flere",
NotShow: "Vis ikke igen",
ConfirmNoShow:
"Er du sikker på, at du ikke vil se det igen? Du kan altid slå det til under indstillinger.",
},
UI: {
Confirm: "OK",
Cancel: "Fortryd",
Close: "Luk",
Create: "Opret",
Edit: "Rediger",
Export: "Eksporter",
Import: "Importér",
Sync: "Synk",
Config: "Konfigurer",
},
Exporter: {
Description: {
Title: "Kun beskeder efter sidste rydning vises",
},
Model: "Model",
Messages: "Beskeder",
Topic: "Emne",
Time: "Tid",
},
URLCommand: {
Code: "Så ud til, at der var en kode i linket. Vil du bruge den?",
Settings: "Så ud til, at der var indstillinger i linket. Vil du bruge dem?",
},
SdPanel: {
Prompt: "Prompt",
NegativePrompt: "Negativ prompt",
PleaseInput: (name: string) => `Indtast: ${name}`,
AspectRatio: "Billedformat",
ImageStyle: "Stil",
OutFormat: "Uddataformat",
AIModel: "AI-model",
ModelVersion: "Version",
Submit: "Send",
ParamIsRequired: (name: string) => `${name} er krævet`,
Styles: {
D3Model: "3d-model",
AnalogFilm: "analog-film",
Anime: "anime",
Cinematic: "cinematisk",
ComicBook: "tegneserie",
DigitalArt: "digital-art",
Enhance: "enhance",
FantasyArt: "fantasy-art",
Isometric: "isometric",
LineArt: "line-art",
LowPoly: "low-poly",
ModelingCompound: "modeling-compound",
NeonPunk: "neon-punk",
Origami: "origami",
Photographic: "fotografisk",
PixelArt: "pixel-art",
TileTexture: "tile-texture",
},
},
Sd: {
SubTitle: (count: number) => `${count} billeder`,
Actions: {
Params: "Se indstillinger",
Copy: "Kopiér prompt",
Delete: "Slet",
Retry: "Prøv igen",
ReturnHome: "Til forsiden",
History: "Historik",
},
EmptyRecord: "Ingen billeder endnu",
Status: {
Name: "Status",
Success: "Ok",
Error: "Fejl",
Wait: "Venter",
Running: "I gang",
},
Danger: {
Delete: "Vil du slette?",
},
GenerateParams: "Genereringsvalg",
Detail: "Detaljer",
},
};
export default da;

View File

@@ -2,6 +2,7 @@ import cn from "./cn";
import en from "./en";
import pt from "./pt";
import tw from "./tw";
import da from "./da";
import id from "./id";
import fr from "./fr";
import es from "./es";
@@ -30,6 +31,7 @@ const ALL_LANGS = {
en,
tw,
pt,
da,
jp,
ko,
id,
@@ -56,6 +58,7 @@ export const ALL_LANG_OPTIONS: Record<Lang, string> = {
en: "English",
pt: "Português",
tw: "繁體中文",
da: "Dansk",
jp: "日本語",
ko: "한국어",
id: "Indonesia",
@@ -141,6 +144,7 @@ export const STT_LANG_MAP: Record<Lang, string> = {
en: "en-US",
pt: "pt-BR",
tw: "zh-TW",
da: "da-DK",
jp: "ja-JP",
ko: "ko-KR",
id: "id-ID",

View File

@@ -10,6 +10,11 @@ import { clientUpdate } from "../utils";
import ChatGptIcon from "../icons/chatgpt.png";
import Locale from "../locales";
import { ClientApi } from "../client/api";
import {
isPermissionGranted,
requestPermission,
sendNotification,
} from "@tauri-apps/plugin-notification";
const ONE_MINUTE = 60 * 1000;
const isApp = !!getClientConfig()?.isApp;
@@ -90,42 +95,39 @@ export const useUpdateStore = createPersistStore(
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();
}
}
});
}
});
try {
// Check if notification permission is granted
const granted = await isPermissionGranted();
if (!granted) {
// Request permission to show notifications
const permission = await requestPermission();
if (permission !== "granted") return;
}
if (version === remoteId) {
// Show a notification using Tauri
await 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
await sendNotification({
title: "NextChat",
body: updateMessage,
icon: `${ChatGptIcon.src}`,
sound: "Default",
});
clientUpdate();
}
} catch (error) {
console.error("[Notification Error]", error);
}
}
console.log("[Got Upstream] ", remoteId);
} catch (error) {

View File

@@ -12,6 +12,9 @@ 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";
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
import { save } from "@tauri-apps/plugin-dialog";
import { writeTextFile } from "@tauri-apps/plugin-fs";
export function trimTopic(topic: string) {
// Fix an issue where double quotes still show in the Indonesian language
@@ -20,15 +23,15 @@ export function trimTopic(topic: string) {
return (
topic
// fix for gemini
.replace(/^["“”*]+|["“”*]+$/g, "")
.replace(/[,。!?”“"、,.!?*]*$/, "")
.replace(/^["""*]+|["""*]+$/g, "")
.replace(/[,。!?""""、,.!?*]*$/, "")
);
}
export async function copyToClipboard(text: string) {
try {
if (window.__TAURI__) {
window.__TAURI__.writeText(text);
await writeText(text);
} else {
await navigator.clipboard.writeText(text);
}
@@ -52,7 +55,7 @@ export async function copyToClipboard(text: string) {
export async function downloadAs(text: string, filename: string) {
if (window.__TAURI__) {
const result = await window.__TAURI__.dialog.save({
const result = await save({
defaultPath: `${filename}`,
filters: [
{
@@ -68,7 +71,7 @@ export async function downloadAs(text: string, filename: string) {
if (result !== null) {
try {
await window.__TAURI__.fs.writeTextFile(result, text);
await writeTextFile(result, text);
showToast(Locale.Download.Success);
} catch (error) {
showToast(Locale.Download.Failed);
@@ -448,24 +451,29 @@ export function getOperationId(operation: {
export function clientUpdate() {
// this a wild for updating client app
return window.__TAURI__?.updater
const tauriApp = window.__TAURI__;
if (!tauriApp || !tauriApp.updater) return Promise.resolve();
return tauriApp.updater
.checkUpdate()
.then((updateResult) => {
.then((updateResult: any) => {
if (updateResult.shouldUpdate) {
window.__TAURI__?.updater
return tauriApp.updater
.installUpdate()
.then((result) => {
.then((result: any) => {
showToast(Locale.Settings.Update.Success);
})
.catch((e) => {
.catch((e: any) => {
console.error("[Install Update Error]", e);
showToast(Locale.Settings.Update.Failed);
});
}
return updateResult;
})
.catch((e) => {
.catch((e: any) => {
console.error("[Check Update Error]", e);
showToast(Locale.Settings.Update.Failed);
return e;
});
}

View File

@@ -3,7 +3,7 @@ import {
UPLOAD_URL,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
import { RequestMessage } from "@/app/client/api";
import { MultimodalContent, RequestMessage } from "@/app/client/api";
import Locale from "@/app/locales";
import {
EventStreamContentType,
@@ -70,8 +70,9 @@ export function compressImage(file: Blob, maxSize: number): Promise<string> {
});
}
export async function preProcessImageContent(
export async function preProcessImageContentBase(
content: RequestMessage["content"],
transformImageUrl: (url: string) => Promise<{ [key: string]: any }>,
) {
if (typeof content === "string") {
return content;
@@ -81,7 +82,7 @@ export async function preProcessImageContent(
if (part?.type == "image_url" && part?.image_url?.url) {
try {
const url = await cacheImageToBase64Image(part?.image_url?.url);
result.push({ type: part.type, image_url: { url } });
result.push(await transformImageUrl(url));
} catch (error) {
console.error("Error processing image URL:", error);
}
@@ -92,6 +93,23 @@ export async function preProcessImageContent(
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)) {

View File

@@ -3,6 +3,9 @@
// 1. invoke('stream_fetch', {url, method, headers, body}), get response with headers.
// 2. listen event: `stream-response` multi times to get body
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
type ResponseEvent = {
id: number;
payload: {
@@ -27,8 +30,8 @@ export function fetch(url: string, options?: RequestInit): Promise<Response> {
headers: _headers = {},
body = [],
} = options || {};
let unlisten: Function | undefined;
let setRequestId: Function | undefined;
let unlisten: (() => void) | undefined;
let setRequestId: ((value: number) => void) | undefined;
const requestIdPromise = new Promise((resolve) => (setRequestId = resolve));
const ts = new TransformStream();
const writer = ts.writable.getWriter();
@@ -46,25 +49,24 @@ export function fetch(url: string, options?: RequestInit): Promise<Response> {
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));
// Listen for stream response events
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: () => void) => (unlisten = u));
const headers: Record<string, string> = {
Accept: "application/json, text/plain, */*",
@@ -74,17 +76,16 @@ export function fetch(url: string, options?: RequestInit): Promise<Response> {
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))
: [],
})
return invoke<StreamResponse>("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);

View File

@@ -15,6 +15,8 @@ const config: Config = {
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

View File

@@ -1,24 +1,22 @@
// 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({}),
json: () => Promise.resolve([]),
headers: new Headers(),
redirected: false,
statusText: "OK",
type: "basic",
url: "",
clone: function () {
return this;
},
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),
);

View File

@@ -17,8 +17,8 @@
"prompts": "node ./scripts/fetch-prompts.mjs",
"prepare": "husky install",
"proxy-dev": "sh ./scripts/init-proxy.sh && proxychains -f ./scripts/proxychains.conf yarn dev",
"test": "jest --watch",
"test:ci": "jest --ci"
"test": "node --no-warnings --experimental-vm-modules $(yarn bin jest) --watch",
"test:ci": "node --no-warnings --experimental-vm-modules $(yarn bin jest) --ci"
},
"dependencies": {
"@fortaine/fetch-event-source": "^3.0.6",
@@ -26,6 +26,14 @@
"@modelcontextprotocol/sdk": "^1.0.4",
"@next/third-parties": "^14.1.0",
"@svgr/webpack": "^6.5.1",
"@tauri-apps/plugin-clipboard-manager": "~2",
"@tauri-apps/plugin-dialog": "~2",
"@tauri-apps/plugin-fs": "~2",
"@tauri-apps/plugin-http": "~2",
"@tauri-apps/plugin-notification": "~2",
"@tauri-apps/plugin-shell": "~2",
"@tauri-apps/plugin-updater": "~2",
"@tauri-apps/plugin-window-state": "^2.2.1",
"@vercel/analytics": "^0.1.11",
"@vercel/speed-insights": "^1.0.2",
"axios": "^1.7.5",
@@ -39,7 +47,7 @@
"markdown-to-txt": "^2.0.1",
"mermaid": "^10.6.1",
"nanoid": "^5.0.3",
"next": "^14.1.1",
"next": "14.2.24",
"node-fetch": "^3.3.1",
"openapi-client-axios": "^7.5.5",
"react": "^18.2.0",
@@ -59,8 +67,8 @@
"zustand": "^4.3.8"
},
"devDependencies": {
"@tauri-apps/api": "^2.1.1",
"@tauri-apps/cli": "1.5.11",
"@tauri-apps/api": "^2.3.0",
"@tauri-apps/cli": "^2.3.1",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
@@ -75,7 +83,7 @@
"concurrently": "^8.2.2",
"cross-env": "^7.0.3",
"eslint": "^8.49.0",
"eslint-config-next": "13.4.19",
"eslint-config-next": "14.2.24",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-unused-imports": "^3.2.0",

3887
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,38 +12,31 @@ rust-version = "1.60"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.5.1", features = [] }
tauri-build = { version = "2", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.5.4", features = [ "http-all",
"notification-all",
"fs-all",
"clipboard-all",
"dialog-all",
"shell-open",
"updater",
"window-close",
"window-hide",
"window-maximize",
"window-minimize",
"window-set-icon",
"window-set-ignore-cursor-events",
"window-set-resizable",
"window-show",
"window-start-dragging",
"window-unmaximize",
"window-unminimize",
tauri = { version = "2", features = [
] }
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
tauri-plugin-window-state = { version = "2" }
percent-encoding = "2.3.1"
reqwest = "0.11.18"
futures-util = "0.3.30"
bytes = "1.7.2"
log = "0.4.21"
tauri-plugin-dialog = "2"
tauri-plugin-shell = "2"
tauri-plugin-notification = "2"
tauri-plugin-fs = "2"
tauri-plugin-http = "2"
tauri-plugin-clipboard-manager = "2"
[features]
# this feature is used for production builds or when `devPath` points to the filesystem and the built-in dev server is disabled.
# If you use cargo directly instead of tauri's cli you can use this feature flag to switch between tauri's `dev` and `build` modes.
# DO NOT REMOVE!!
custom-protocol = ["tauri/custom-protocol"]
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-updater = "2"

View File

@@ -1,3 +1,3 @@
fn main() {
tauri_build::build()
tauri_build::build()
}

View File

@@ -0,0 +1,14 @@
{
"identifier": "desktop-capability",
"platforms": [
"macOS",
"windows",
"linux"
],
"windows": [
"main"
],
"permissions": [
"updater:default"
]
}

View File

@@ -0,0 +1,57 @@
{
"identifier": "migrated",
"description": "permissions that were migrated from v1",
"local": true,
"windows": [
"main"
],
"permissions": [
"core:default",
"fs:allow-read-file",
"fs:allow-write-file",
"fs:allow-read-dir",
"fs:allow-copy-file",
"fs:allow-mkdir",
"fs:allow-remove",
"fs:allow-remove",
"fs:allow-rename",
"fs:allow-exists",
"core:window:allow-set-resizable",
"core:window:allow-maximize",
"core:window:allow-unmaximize",
"core:window:allow-minimize",
"core:window:allow-unminimize",
"core:window:allow-show",
"core:window:allow-hide",
"core:window:allow-close",
"core:window:allow-set-icon",
"core:window:allow-set-ignore-cursor-events",
"core:window:allow-start-dragging",
"shell:allow-open",
"dialog:allow-open",
"dialog:allow-save",
"dialog:allow-message",
"dialog:allow-ask",
"dialog:allow-confirm",
{
"identifier": "http:default",
"allow": [
{
"url": "https://*/"
},
{
"url": "http://*/"
}
]
},
"notification:default",
"clipboard-manager:allow-read-text",
"clipboard-manager:allow-write-text",
"dialog:default",
"shell:default",
"notification:default",
"fs:default",
"http:default",
"clipboard-manager:default"
]
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"desktop-capability":{"identifier":"desktop-capability","description":"","local":true,"windows":["main"],"permissions":["updater:default"],"platforms":["macOS","windows","linux"]},"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main"],"permissions":["core:default","fs:allow-read-file","fs:allow-write-file","fs:allow-read-dir","fs:allow-copy-file","fs:allow-mkdir","fs:allow-remove","fs:allow-remove","fs:allow-rename","fs:allow-exists","core:window:allow-set-resizable","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-minimize","core:window:allow-unminimize","core:window:allow-show","core:window:allow-hide","core:window:allow-close","core:window:allow-set-icon","core:window:allow-set-ignore-cursor-events","core:window:allow-start-dragging","shell:allow-open","dialog:allow-open","dialog:allow-save","dialog:allow-message","dialog:allow-ask","dialog:allow-confirm",{"identifier":"http:default","allow":[{"url":"https://*/"},{"url":"http://*/"}]},"notification:default","clipboard-manager:allow-read-text","clipboard-manager:allow-write-text","dialog:default","shell:default","notification:default","fs:default","http:default","clipboard-manager:default"]}}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -4,9 +4,16 @@
mod stream;
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![stream::stream_fetch])
.plugin(tauri_plugin_window_state::Builder::default().build())
.run(tauri::generate_context!())
.expect("error while running tauri application");
tauri::Builder::default()
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_dialog::init())
.invoke_handler(tauri::generate_handler![stream::stream_fetch])
.plugin(tauri_plugin_window_state::Builder::default().build())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View File

@@ -1,145 +1,176 @@
//
//
use std::time::Duration;
use futures_util::StreamExt;
use std::collections::HashMap;
use std::error::Error;
use std::sync::atomic::{AtomicU32, Ordering};
use std::collections::HashMap;
use futures_util::{StreamExt};
use reqwest::Client;
use reqwest::header::{HeaderName, HeaderMap};
use std::time::Duration;
use tauri::Emitter;
use tauri_plugin_http::reqwest;
use tauri_plugin_http::reqwest::header::{HeaderMap, HeaderName};
use tauri_plugin_http::reqwest::Client;
static REQUEST_COUNTER: AtomicU32 = AtomicU32::new(0);
#[derive(Debug, Clone, serde::Serialize)]
pub struct StreamResponse {
request_id: u32,
status: u16,
status_text: String,
headers: HashMap<String, String>
request_id: u32,
status: u16,
status_text: String,
headers: HashMap<String, String>,
}
#[derive(Clone, serde::Serialize)]
pub struct EndPayload {
request_id: u32,
status: u16,
request_id: u32,
status: u16,
}
#[derive(Clone, serde::Serialize)]
pub struct ChunkPayload {
request_id: u32,
chunk: bytes::Bytes,
request_id: u32,
chunk: Vec<u8>,
}
#[tauri::command]
pub async fn stream_fetch(
window: tauri::Window,
method: String,
url: String,
headers: HashMap<String, String>,
body: Vec<u8>,
window: tauri::WebviewWindow,
method: String,
url: String,
headers: HashMap<String, String>,
body: Vec<u8>,
) -> Result<StreamResponse, String> {
let event_name = "stream-response";
let request_id = REQUEST_COUNTER.fetch_add(1, Ordering::SeqCst);
let event_name = "stream-response";
let request_id = REQUEST_COUNTER.fetch_add(1, Ordering::SeqCst);
let mut _headers = HeaderMap::new();
for (key, value) in &headers {
_headers.insert(key.parse::<HeaderName>().unwrap(), value.parse().unwrap());
}
// println!("method: {:?}", method);
// println!("url: {:?}", url);
// println!("headers: {:?}", headers);
// println!("headers: {:?}", _headers);
let method = method.parse::<reqwest::Method>().map_err(|err| format!("failed to parse method: {}", err))?;
let client = Client::builder()
.default_headers(_headers)
.redirect(reqwest::redirect::Policy::limited(3))
.connect_timeout(Duration::new(3, 0))
.build()
.map_err(|err| format!("failed to generate client: {}", err))?;
let mut request = client.request(
method.clone(),
url.parse::<reqwest::Url>().map_err(|err| format!("failed to parse url: {}", err))?
);
if method == reqwest::Method::POST || method == reqwest::Method::PUT || method == reqwest::Method::PATCH {
let body = bytes::Bytes::from(body);
// println!("body: {:?}", body);
request = request.body(body);
}
// println!("client: {:?}", client);
// println!("request: {:?}", request);
let response_future = request.send();
let res = response_future.await;
let response = match res {
Ok(res) => {
// get response and emit to client
let mut headers = HashMap::new();
for (name, value) in res.headers() {
headers.insert(
name.as_str().to_string(),
std::str::from_utf8(value.as_bytes()).unwrap().to_string()
);
}
let status = res.status().as_u16();
tauri::async_runtime::spawn(async move {
let mut stream = res.bytes_stream();
while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => {
// println!("chunk: {:?}", bytes);
if let Err(e) = window.emit(event_name, ChunkPayload{ request_id, chunk: bytes }) {
println!("Failed to emit chunk payload: {:?}", e);
}
}
Err(err) => {
println!("Error chunk: {:?}", err);
}
}
}
if let Err(e) = window.emit(event_name, EndPayload{ request_id, status: 0 }) {
println!("Failed to emit end payload: {:?}", e);
}
});
StreamResponse {
request_id,
status,
status_text: "OK".to_string(),
headers,
}
let mut _headers = HeaderMap::new();
for (key, value) in &headers {
_headers.insert(key.parse::<HeaderName>().unwrap(), value.parse().unwrap());
}
Err(err) => {
let error: String = err.source()
.map(|e| e.to_string())
.unwrap_or_else(|| "Unknown error occurred".to_string());
println!("Error response: {:?}", error);
tauri::async_runtime::spawn( async move {
if let Err(e) = window.emit(event_name, ChunkPayload{ request_id, chunk: error.into() }) {
println!("Failed to emit chunk payload: {:?}", e);
}
if let Err(e) = window.emit(event_name, EndPayload{ request_id, status: 0 }) {
println!("Failed to emit end payload: {:?}", e);
}
});
StreamResponse {
request_id,
status: 599,
status_text: "Error".to_string(),
headers: HashMap::new(),
}
// println!("method: {:?}", method);
// println!("url: {:?}", url);
// println!("headers: {:?}", headers);
// println!("headers: {:?}", _headers);
let method = method
.parse::<reqwest::Method>()
.map_err(|err| format!("failed to parse method: {}", err))?;
let client = Client::builder()
.default_headers(_headers)
.redirect(reqwest::redirect::Policy::limited(3))
.connect_timeout(Duration::new(3, 0))
.build()
.map_err(|err| format!("failed to generate client: {}", err))?;
let mut request = client.request(
method.clone(),
url.parse::<reqwest::Url>()
.map_err(|err| format!("failed to parse url: {}", err))?,
);
if method == reqwest::Method::POST
|| method == reqwest::Method::PUT
|| method == reqwest::Method::PATCH
{
let body = bytes::Bytes::from(body);
// println!("body: {:?}", body);
request = request.body(body);
}
};
// println!("Response: {:?}", response);
Ok(response)
// println!("client: {:?}", client);
// println!("request: {:?}", request);
let response_future = request.send();
let res = response_future.await;
let response = match res {
Ok(res) => {
// get response and emit to client
let mut headers = HashMap::new();
for (name, value) in res.headers() {
headers.insert(
name.as_str().to_string(),
std::str::from_utf8(value.as_bytes()).unwrap().to_string(),
);
}
let status = res.status().as_u16();
tauri::async_runtime::spawn(async move {
let mut stream = res.bytes_stream();
while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => {
// println!("chunk: {:?}", bytes);
if let Err(e) = window.emit(
event_name,
ChunkPayload {
request_id,
chunk: bytes.to_vec(),
},
) {
println!("Failed to emit chunk payload: {:?}", e);
}
}
Err(err) => {
println!("Error chunk: {:?}", err);
}
}
}
if let Err(e) = window.emit(
event_name,
EndPayload {
request_id,
status: 0,
},
) {
println!("Failed to emit end payload: {:?}", e);
}
});
StreamResponse {
request_id,
status,
status_text: "OK".to_string(),
headers,
}
}
Err(err) => {
let error: String = err
.source()
.map(|e| e.to_string())
.unwrap_or_else(|| "Unknown error occurred".to_string());
println!("Error response: {:?}", error);
tauri::async_runtime::spawn(async move {
if let Err(e) = window.emit(
event_name,
ChunkPayload {
request_id,
chunk: error.into_bytes(),
},
) {
println!("Failed to emit chunk payload: {:?}", e);
}
if let Err(e) = window.emit(
event_name,
EndPayload {
request_id,
status: 0,
},
) {
println!("Failed to emit end payload: {:?}", e);
}
});
StreamResponse {
request_id,
status: 599,
status_text: "Error".to_string(),
headers: HashMap::new(),
}
}
};
// println!("Response: {:?}", response);
Ok(response)
}

View File

@@ -3,108 +3,61 @@
"build": {
"beforeBuildCommand": "yarn export",
"beforeDevCommand": "yarn export:dev",
"devPath": "http://localhost:3000",
"distDir": "../out",
"withGlobalTauri": true
"frontendDist": "../out",
"devUrl": "http://localhost:3000"
},
"package": {
"productName": "NextChat",
"version": "2.15.8"
},
"tauri": {
"allowlist": {
"all": false,
"shell": {
"all": false,
"open": true
},
"dialog": {
"all": true,
"ask": true,
"confirm": true,
"message": true,
"open": true,
"save": true
},
"clipboard": {
"all": true,
"writeText": true,
"readText": true
},
"window": {
"all": false,
"close": true,
"hide": true,
"maximize": true,
"minimize": true,
"setIcon": true,
"setIgnoreCursorEvents": true,
"setResizable": true,
"show": true,
"startDragging": true,
"unmaximize": true,
"unminimize": true
},
"fs": {
"all": true
},
"notification": {
"all": true
},
"http": {
"all": true,
"request": true,
"scope": ["https://*", "http://*"]
}
"bundle": {
"active": true,
"category": "DeveloperTool",
"copyright": "2023, Zhang Yifei All Rights Reserved.",
"targets": "all",
"externalBin": [],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
},
"bundle": {
"active": true,
"category": "DeveloperTool",
"copyright": "2023, Zhang Yifei All Rights Reserved.",
"longDescription": "NextChat is a cross-platform ChatGPT client, including Web/Win/Linux/OSX/PWA.",
"macOS": {
"entitlements": null,
"exceptionDomain": "",
"frameworks": [],
"providerShortName": null,
"signingIdentity": null
},
"resources": [],
"shortDescription": "NextChat App",
"linux": {
"deb": {
"depends": []
},
"externalBin": [],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "com.yida.chatgpt.next.web",
"longDescription": "NextChat is a cross-platform ChatGPT client, including Web/Win/Linux/OSX/PWA.",
"macOS": {
"entitlements": null,
"exceptionDomain": "",
"frameworks": [],
"providerShortName": null,
"signingIdentity": null
},
"resources": [],
"shortDescription": "NextChat App",
"targets": "all",
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
}
},
"security": {
"csp": null,
"dangerousUseHttpScheme": true
},
"createUpdaterArtifacts": "v1Compatible"
},
"productName": "NextChat",
"mainBinaryName": "NextChat",
"version": "2.15.8",
"identifier": "com.yida.chatgpt.next.web",
"plugins": {
"updater": {
"active": true,
"endpoints": [
"https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/releases/latest/download/latest.json"
],
"dialog": true,
"windows": {
"installMode": "passive"
},
"endpoints": [
"https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/releases/latest/download/latest.json"
],
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERFNDE4MENFM0Y1RTZBOTQKUldTVWFsNC96b0JCM3RqM2NmMnlFTmxIaStRaEJrTHNOU2VqRVlIV1hwVURoWUdVdEc1eDcxVEYK"
},
}
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"fullscreen": false,
@@ -113,8 +66,12 @@
"title": "NextChat",
"width": 960,
"hiddenTitle": true,
"titleBarStyle": "Overlay"
"titleBarStyle": "Overlay",
"useHttpsScheme": false
}
]
],
"security": {
"csp": null
}
}
}
}

167
test/stream-fetch.test.ts Normal file
View File

@@ -0,0 +1,167 @@
import { jest } from '@jest/globals';
// Create mocks
const mockInvoke = jest.fn();
const mockListen = jest.fn();
// Mock Tauri modules before import
jest.mock('@tauri-apps/api/core', () => ({
invoke: (...args: any[]) => mockInvoke(...args)
}));
jest.mock('@tauri-apps/api/event', () => ({
listen: (...args: any[]) => mockListen(...args)
}));
// Import function after mocking
import { fetch as streamFetch } from '../app/utils/stream';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
// Mock global objects
// @ts-ignore
global.TransformStream = class TransformStream {
writable = {
getWriter: () => ({
ready: Promise.resolve(),
// @ts-ignore
write: jest.fn().mockResolvedValue(undefined as any),
// @ts-ignore
close: jest.fn().mockResolvedValue(undefined as any)
})
};
readable = {} as any;
} as any;
// Add Response to global context
global.Response = class Response {
constructor(public body: any, public init: any) {
Object.assign(this, init);
}
status: number = 200;
statusText: string = 'OK';
headers: any = {};
} as any;
describe('stream-fetch', () => {
let originalFetch: any;
let originalWindow: any;
beforeAll(() => {
originalFetch = global.fetch;
originalWindow = global.window;
// Mock window object
Object.defineProperty(global, 'window', {
value: {
__TAURI__: true,
__TAURI_INTERNALS__: {
transformCallback: (callback: Function) => callback,
invoke: mockInvoke
},
fetch: jest.fn(),
Headers: class Headers {
constructor() {}
entries() { return []; }
},
TextEncoder: class TextEncoder {
encode(text: string) {
return new Uint8Array(Array.from(text).map(c => c.charCodeAt(0)));
}
},
navigator: {
userAgent: 'test-agent'
},
Response: class Response {
constructor(public body: any, public init: any) {}
status: number = 200;
statusText: string = 'OK';
headers: any = {};
}
},
writable: true,
});
});
afterAll(() => {
Object.defineProperty(global, 'window', {
value: originalWindow,
writable: true,
});
global.fetch = originalFetch;
});
beforeEach(() => {
jest.clearAllMocks();
// Set up default behavior for listen
mockListen.mockImplementation(() => Promise.resolve(() => {}));
});
test('should use native fetch when Tauri is unavailable', async () => {
// Temporarily remove __TAURI__
const tempWindow = { ...window };
delete (tempWindow as any).__TAURI__;
Object.defineProperty(global, 'window', {
value: tempWindow,
writable: true,
});
await streamFetch('https://example.com');
// Check that native fetch was called
expect(window.fetch).toHaveBeenCalledWith('https://example.com', undefined);
// Restore __TAURI__
Object.defineProperty(global, 'window', {
value: { ...tempWindow, __TAURI__: true },
writable: true,
});
});
test('should use Tauri API when Tauri is available', async () => {
// Mock successful response from Tauri
// @ts-ignore
mockInvoke.mockResolvedValue({
request_id: 123,
status: 200,
status_text: 'OK',
headers: {}
} as any);
// Call fetch function
await streamFetch('https://example.com');
// Check that Tauri invoke was called with correct parameters
expect(mockInvoke).toHaveBeenCalledWith(
'stream_fetch',
expect.objectContaining({
url: 'https://example.com'
}),
undefined
);
});
test('should add abort signal to request', async () => {
// Mock successful response from Tauri
// @ts-ignore
mockInvoke.mockResolvedValue({
request_id: 123,
status: 200,
status_text: 'OK',
headers: {}
} as any);
// Create AbortController
const controller = new AbortController();
const addEventListenerSpy = jest.spyOn(controller.signal, 'addEventListener');
// Call fetch with signal
await streamFetch('https://example.com', {
signal: controller.signal
});
// Check that signal was added
expect(addEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function));
});
});

View File

@@ -1,3 +1,4 @@
import { jest } from "@jest/globals";
import { isVisionModel } from "../app/utils";
describe("isVisionModel", () => {
@@ -50,7 +51,7 @@ describe("isVisionModel", () => {
test("should identify models from VISION_MODELS env var", () => {
process.env.VISION_MODELS = "custom-vision-model,another-vision-model";
expect(isVisionModel("custom-vision-model")).toBe(true);
expect(isVisionModel("another-vision-model")).toBe(true);
expect(isVisionModel("unrelated-model")).toBe(false);
@@ -64,4 +65,4 @@ describe("isVisionModel", () => {
expect(isVisionModel("unrelated-model")).toBe(false);
expect(isVisionModel("gpt-4-vision")).toBe(true);
});
});
});

1932
yarn.lock

File diff suppressed because it is too large Load Diff