Compare commits

...

16 Commits

Author SHA1 Message Date
renovate[bot]
3e053bc904 fix(deps): update dependency zod to v4 2026-01-01 05:46:19 +00:00
Dayuan Jiang
037f32973a fix: resolve biome lint errors blocking CI (#480)
- Update biome schema version from 2.3.8 to 2.3.10
- Add radix parameter to parseInt in mcp-server
- Remove unnecessary React fragment in model-config-dialog
- Fix unused variable errors (err -> _err)
- Auto-format code with biome
2026-01-01 14:45:46 +09:00
Dayuan Jiang
7bdc1fe612 fix(mcp-server): add graceful shutdown to prevent zombie processes (#477)
* fix(mcp-server): add graceful shutdown to prevent zombie processes

Add lifecycle handlers to properly exit the MCP server when the parent
application closes:

- Listen for stdin close/end events (primary method for all platforms)
- Handle SIGINT/SIGTERM signals
- Handle stdout broken pipe errors
- Export shutdown() function from http-server to clean up resources

* chore(mcp-server): bump version to 0.1.11
2025-12-31 18:38:20 +09:00
Dayuan Jiang
03ac9a79de fix: detect models that don't support image input and return clear error (#474)
Some models (Kimi K2, DeepSeek, Qwen text models) don't support image/vision
input. The AI SDK silently drops unsupported image parts, causing confusing
responses where the model acts as if no image was uploaded.

Added supportsImageInput() function to detect unsupported models by name,
and return a 400 error with clear guidance when users try to upload images
to these models.

Closes #469
2025-12-31 12:20:09 +09:00
E66Crisp
f97934d6e0 feat(i18n): sync Draw.io panel language with app locale (#473) 2025-12-31 11:48:02 +09:00
E66Crisp
73a36cf9de style(chat-panel): Improve aiChat label display in collapsed panel (#470)
* style(chat-panel): Improve aiChat label display in collapsed panel

* fix: update qs to fix high severity security vulnerability

---------

Co-authored-by: dayuan.jiang <jdy.toh@gmail.com>
2025-12-31 11:25:23 +09:00
Dayuan Jiang
69f9df1792 fix: improve image not supported error detection for DeepSeek (#468) 2025-12-31 00:12:19 +09:00
Dayuan Jiang
aaa2938dac docs: reorganize documentation into i18n folder structure (#466)
* docs: reorganize docs into en/cn/ja folders

- Move documentation files into language-specific folders (en, cn, ja)
- Add Chinese and Japanese translations for all docs
- Extract Docker section from README to separate doc file
- Update README to link to new doc locations

* docs: fix links to new docs folder structure

* docs: update README and provider docs

* docs: fix broken import statements in cloudflare deploy guides

* docs: sync CN/JA READMEs with EN structure and fix all paths
2025-12-31 00:04:32 +09:00
broBinChen
24afa0b58a feat: add copy button for tool call blocks (#463)
* feat: add copy button for tool call blocks

* refactor: simplify copy state updates with helper function

---------

Co-authored-by: binge_c-admin <totchinaa@gmail.com>
2025-12-30 23:45:50 +09:00
Dayuan Jiang
1d19127855 chore: remove About link from header and language switcher from about pages (#464)
- Remove About link and sponsor notice icon from chat panel header
- Remove language switcher (English | 中文 | 日本語) from all about pages
- Fix About link in settings dialog to use current language
- Remove unused sponsorTooltip translation key from all dictionaries
2025-12-30 23:45:31 +09:00
zhoujie0531
ca21a5bb27 feat: add EdgeOne Pages as AI provider (#456)
* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* feat: edit diagram

* feat: edit diagram

* feat: edit diagram

* feat: edit diagram

* feat: edit diagram

* feat: edit diagram

* feat: edit diagram

* feat: add edgeone provider

* feat: add edgeone provider

* feat: add edgeone provider

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: add cookie

* fix: add cookie

* fix: add cookie

* fix: add cookie

* fix: add cookie

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* fix: build error

* feat: validate

* feat: document link

---------

Co-authored-by: zoejiezhou <zoejiezhou@tencent.com>
2025-12-30 22:13:22 +09:00
broBinChen
ad80e9c6f5 i18n: add missing translations for chat UI components (#457)
* i18n: add missing translations for chat UI components

* i18n: add missing translations for chat components and toast messages
2025-12-30 20:52:57 +09:00
Biki Kalita
1ab8d260a2 fix: restore locale redirection using Next.js middleware (#462)
* fix: restore locale redirection using Next.js middleware

* fix: use proxy.ts instead of middleware.ts for Next.js 16

---------

Co-authored-by: Dayuan Jiang <jdy.toh@gmail.com>
2025-12-30 20:40:33 +09:00
Dayuan Jiang
2d62496f9f fix(edit_diagram): implement cascade delete for children and edges (#451)
* fix(edit_diagram): implement cascade delete for children and edges

- Add automatic cascade deletion when deleting a cell
- Recursively delete all child cells (parent attribute references)
- Delete all edges referencing deleted cells (source/target)
- Skip silently if cell already deleted (handles AI redundant ops)
- Update prompts to inform AI about cascade behavior

Fixes #450

* fix: add root cell protection and sync MCP server cascade delete

- Add protection for root cells '0' and '1' to prevent full diagram wipe
- Sync MCP server with main app's cascade delete logic
- Both lib/utils.ts and packages/mcp-server now have identical delete behavior

* chore(mcp): bump version to 0.1.9

* fix(cascade-delete): recursively collect edge children (labels)

- Change from cellsToDelete.add(edgeId) to collectDescendants(edgeId)
- Fixes orphaned edge labels causing draw.io to crash/clear canvas
- Edge labels (parent=edgeId) are now deleted with their parent edge
2025-12-30 00:03:30 +09:00
Dayuan Jiang
c2aa7f49be fix(mcp): rename display_diagram to create_new_diagram (#449)
Rename tool to be less ambiguous and help AI models correctly
provide the required xml parameter on subsequent calls.

Closes #445
2025-12-29 15:15:13 +09:00
Dayuan Jiang
30b30550d9 chore: clean up root folder by relocating config files (#448)
* chore: clean up root folder by moving config files

- Move renovate.json to .github/renovate.json
- Move electron-builder.yml to electron/electron-builder.yml
- Move electron.d.ts to electron/electron.d.ts
- Delete proxy.ts (unused dead code)
- Update package.json dist scripts with --config flag
- Use tsconfig.json files array for electron.d.ts (bypasses exclude)

Reduces git-tracked root files from 23 to 19.

* chore: regenerate package-lock.json to fix CI

* fix: regenerate package-lock.json with cross-platform deps
2025-12-29 14:30:25 +09:00
54 changed files with 24459 additions and 22747 deletions

View File

@@ -29,7 +29,7 @@ jobs:
cache: 'npm' cache: 'npm'
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm install
- name: Type check - name: Type check
run: npx tsc --noEmit run: npx tsc --noEmit

3
.gitignore vendored
View File

@@ -63,3 +63,6 @@ push-via-ec2.sh
CLAUDE.md CLAUDE.md
.spec-workflow .spec-workflow
# edgeone
.edgeone

View File

@@ -9,7 +9,7 @@ WORKDIR /app
COPY package.json package-lock.json* ./ COPY package.json package-lock.json* ./
# Install dependencies # Install dependencies
RUN npm ci RUN npm install
# Stage 2: Build application # Stage 2: Build application
FROM node:24-alpine AS builder FROM node:24-alpine AS builder

122
README.md
View File

@@ -4,7 +4,7 @@
**AI-Powered Diagram Creation Tool - Chat, Draw, Visualize** **AI-Powered Diagram Creation Tool - Chat, Draw, Visualize**
English | [中文](./docs/README_CN.md) | [日本語](./docs/README_JA.md) English | [中文](./docs/cn/README_CN.md) | [日本語](./docs/ja/README_JA.md)
[![TrendShift](https://trendshift.io/api/badge/repositories/15449)](https://next-ai-drawio.jiang.jp/) [![TrendShift](https://trendshift.io/api/badge/repositories/15449)](https://next-ai-drawio.jiang.jp/)
@@ -36,14 +36,14 @@ https://github.com/user-attachments/assets/9d60a3e8-4a1c-4b5e-acbb-26af2d3eabd1
- [Getting Started](#getting-started) - [Getting Started](#getting-started)
- [Try it Online](#try-it-online) - [Try it Online](#try-it-online)
- [Desktop Application](#desktop-application) - [Desktop Application](#desktop-application)
- [Run with Docker (Recommended)](#run-with-docker-recommended) - [Run with Docker](#run-with-docker)
- [Installation](#installation) - [Installation](#installation)
- [Deployment](#deployment) - [Deployment](#deployment)
- [Deploy to EdgeOne Pages](#deploy-to-edgeone-pages)
- [Deploy on Vercel (Recommended)](#deploy-on-vercel-recommended) - [Deploy on Vercel (Recommended)](#deploy-on-vercel-recommended)
- [Deploy on Cloudflare Workers](#deploy-on-cloudflare-workers) - [Deploy on Cloudflare Workers](#deploy-on-cloudflare-workers)
- [Multi-Provider Support](#multi-provider-support) - [Multi-Provider Support](#multi-provider-support)
- [How It Works](#how-it-works) - [How It Works](#how-it-works)
- [Project Structure](#project-structure)
- [Support \& Contact](#support--contact) - [Support \& Contact](#support--contact)
- [Star History](#star-history) - [Star History](#star-history)
@@ -100,7 +100,7 @@ Here are some example prompts and their generated diagrams:
## MCP Server (Preview) ## MCP Server (Preview)
> **Preview Feature**: This feature is experimental and may not stable. > **Preview Feature**: This feature is experimental and may not be stable.
Use Next AI Draw.io with AI agents like Claude Desktop, Cursor, and VS Code via MCP (Model Context Protocol). Use Next AI Draw.io with AI agents like Claude Desktop, Cursor, and VS Code via MCP (Model Context Protocol).
@@ -144,53 +144,11 @@ No installation needed! Try the app directly on our demo site:
Download the native desktop app for your platform from the [Releases page](https://github.com/DayuanJiang/next-ai-draw-io/releases): Download the native desktop app for your platform from the [Releases page](https://github.com/DayuanJiang/next-ai-draw-io/releases):
| Platform | Download | Supported platforms: Windows, macOS, Linux.
|----------|----------|
| macOS | `.dmg` (Intel & Apple Silicon) |
| Windows | `.exe` installer (x64 & ARM64) |
| Linux | `.AppImage` or `.deb` (x64 & ARM64) |
**Features:** ### Run with Docker
- **Secure API key storage**: Credentials encrypted using OS keychain
- **Configuration presets**: Save and switch between AI providers via menu
- **Native file dialogs**: Open/save `.drawio` files directly
- **Offline capable**: Works without internet after first launch
**Quick Setup:** [Go to Docker Guide](./docs/en/docker.md)
1. Download and install for your platform
2. Open the app → **Menu → Configuration → Manage Presets**
3. Add your AI provider credentials
4. Start creating diagrams!
### Run with Docker (Recommended)
If you just want to run it locally, the best way is to use Docker.
First, install Docker if you haven't already: [Get Docker](https://docs.docker.com/get-docker/)
Then run:
```bash
docker run -d -p 3000:3000 \
-e AI_PROVIDER=openai \
-e AI_MODEL=gpt-4o \
-e OPENAI_API_KEY=your_api_key \
ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
Or use an env file:
```bash
cp env.example .env
# Edit .env with your configuration
docker run -d -p 3000:3000 --env-file .env ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
Open [http://localhost:3000](http://localhost:3000) in your browser.
Replace the environment variables with your preferred AI provider configuration. See [Multi-Provider Support](#multi-provider-support) for available options.
> **Offline Deployment:** If `embed.diagrams.net` is blocked, see [Offline Deployment](./docs/offline-deployment.md) for configuration options.
### Installation ### Installation
@@ -199,44 +157,34 @@ Replace the environment variables with your preferred AI provider configuration.
```bash ```bash
git clone https://github.com/DayuanJiang/next-ai-draw-io git clone https://github.com/DayuanJiang/next-ai-draw-io
cd next-ai-draw-io cd next-ai-draw-io
```
2. Install dependencies:
```bash
npm install npm install
```
3. Configure your AI provider:
Create a `.env.local` file in the root directory:
```bash
cp env.example .env.local cp env.example .env.local
``` ```
Edit `.env.local` and configure your chosen provider: See the [Provider Configuration Guide](./docs/en/ai-providers.md) for detailed setup instructions for each provider.
- Set `AI_PROVIDER` to your chosen provider (doubao,bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow) 2. Run the development server:
- Set `AI_MODEL` to the specific model you want to use
- Add the required API keys for your provider
- `TEMPERATURE`: Optional temperature setting (e.g., `0` for deterministic output). Leave unset for models that don't support it (e.g., reasoning models).
- `ACCESS_CODE_LIST`: Optional access password(s), can be comma-separated for multiple passwords.
> Warning: If you do not set `ACCESS_CODE_LIST`, anyone can access your deployed site directly, which may lead to rapid depletion of your token. It is recommended to set this option.
See the [Provider Configuration Guide](./docs/ai-providers.md) for detailed setup instructions for each provider.
4. Run the development server:
```bash ```bash
npm run dev npm run dev
``` ```
5. Open [http://localhost:3000](http://localhost:3000) in your browser to see the application. 3. Open [http://localhost:6002](http://localhost:6002) in your browser to see the application.
## Deployment ## Deployment
### Deploy to EdgeOne Pages
You can deploy with one click using [Tencent EdgeOne Pages](https://pages.edgeone.ai/).
Deploy by this button:
[![Deploy to EdgeOne Pages](https://cdnstatic.tencentcs.com/edgeone/pages/deploy.svg)](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
Check out the [Tencent EdgeOne Pages documentation](https://pages.edgeone.ai/document/deployment-overview) for more details.
Additionally, deploying through Tencent EdgeOne Pages will also grant you a [daily free quota for DeepSeek models](https://pages.edgeone.ai/document/edge-ai).
### Deploy on Vercel (Recommended) ### Deploy on Vercel (Recommended)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io) [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
@@ -247,7 +195,7 @@ See the [Next.js deployment documentation](https://nextjs.org/docs/app/building-
### Deploy on Cloudflare Workers ### Deploy on Cloudflare Workers
[Go to Cloudflare Deploy Guide](./docs/Cloudflare_Deploy.md) [Go to Cloudflare Deploy Guide](./docs/en/cloudflare-deploy.md)
@@ -263,15 +211,17 @@ See the [Next.js deployment documentation](https://nextjs.org/docs/app/building-
- OpenRouter - OpenRouter
- DeepSeek - DeepSeek
- SiliconFlow - SiliconFlow
- SGLang
- Vercel AI Gateway
All providers except AWS Bedrock and OpenRouter support custom endpoints. All providers except AWS Bedrock and OpenRouter support custom endpoints.
📖 **[Detailed Provider Configuration Guide](./docs/ai-providers.md)** - See setup instructions for each provider. 📖 **[Detailed Provider Configuration Guide](./docs/en/ai-providers.md)** - See setup instructions for each provider.
**Model Requirements**: This task requires strong model capabilities for generating long-form text with strict formatting constraints (draw.io XML). Recommended models include Claude Sonnet 4.5, GPT-5.1, Gemini 3 Pro, and DeepSeek V3.2/R1. **Model Requirements**: This task requires strong model capabilities for generating long-form text with strict formatting constraints (draw.io XML). Recommended models include Claude Sonnet 4.5, GPT-5.1, Gemini 3 Pro, and DeepSeek V3.2/R1.
Note that `claude` series has trained on draw.io diagrams with cloud architecture logos like AWS, Azure, GCP. So if you want to create cloud architecture diagrams, this is the best choice. Note that the `claude` series has been trained on draw.io diagrams with cloud architecture logos like AWS, Azure, GCP. So if you want to create cloud architecture diagrams, this is the best choice.
## How It Works ## How It Works
@@ -284,24 +234,6 @@ The application uses the following technologies:
Diagrams are represented as XML that can be rendered in draw.io. The AI processes your commands and generates or modifies this XML accordingly. Diagrams are represented as XML that can be rendered in draw.io. The AI processes your commands and generates or modifies this XML accordingly.
## Project Structure
```
app/ # Next.js App Router
api/chat/ # Chat API endpoint with AI tools
page.tsx # Main page with DrawIO embed
components/ # React components
chat-panel.tsx # Chat interface with diagram control
chat-input.tsx # User input component with file upload
history-dialog.tsx # Diagram version history viewer
ui/ # UI components (buttons, cards, etc.)
contexts/ # React context providers
diagram-context.tsx # Global diagram state management
lib/ # Utility functions and helpers
ai-providers.ts # Multi-provider AI configuration
utils.ts # XML processing and conversion utilities
public/ # Static assets including example images
```
## Support & Contact ## Support & Contact

View File

@@ -72,28 +72,6 @@ export default function AboutCN() {
<p className="text-xl text-gray-600 font-medium"> <p className="text-xl text-gray-600 font-medium">
AI驱动的图表创建工具 - AI驱动的图表创建工具 -
</p> </p>
<div className="flex justify-center gap-4 mt-4 text-sm">
<Link
href="/about"
className="text-gray-600 hover:text-blue-600"
>
English
</Link>
<span className="text-gray-400">|</span>
<Link
href="/about/cn"
className="text-blue-600 font-semibold"
>
</Link>
<span className="text-gray-400">|</span>
<Link
href="/about/ja"
className="text-gray-600 hover:text-blue-600"
>
</Link>
</div>
</div> </div>
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg"> <div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">

View File

@@ -80,28 +80,6 @@ export default function AboutJA() {
AI搭載のダイアグラム作成ツール - AI搭載のダイアグラム作成ツール -
</p> </p>
<div className="flex justify-center gap-4 mt-4 text-sm">
<Link
href="/about"
className="text-gray-600 hover:text-blue-600"
>
English
</Link>
<span className="text-gray-400">|</span>
<Link
href="/about/cn"
className="text-gray-600 hover:text-blue-600"
>
</Link>
<span className="text-gray-400">|</span>
<Link
href="/about/ja"
className="text-blue-600 font-semibold"
>
</Link>
</div>
</div> </div>
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg"> <div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">

View File

@@ -80,28 +80,6 @@ export default function About() {
AI-Powered Diagram Creation Tool - Chat, Draw, AI-Powered Diagram Creation Tool - Chat, Draw,
Visualize Visualize
</p> </p>
<div className="flex justify-center gap-4 mt-4 text-sm">
<Link
href="/about"
className="text-blue-600 font-semibold"
>
English
</Link>
<span className="text-gray-400">|</span>
<Link
href="/about/cn"
className="text-gray-600 hover:text-blue-600"
>
</Link>
<span className="text-gray-400">|</span>
<Link
href="/about/ja"
className="text-gray-600 hover:text-blue-600"
>
</Link>
</div>
</div> </div>
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg"> <div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">

View File

@@ -28,6 +28,8 @@ export default function Home() {
} = useDiagram() } = useDiagram()
const router = useRouter() const router = useRouter()
const pathname = usePathname() const pathname = usePathname()
// Extract current language from pathname (e.g., "/zh/about" → "zh")
const currentLang = (pathname.split("/")[1] || i18n.defaultLocale) as Locale
const [isMobile, setIsMobile] = useState(false) const [isMobile, setIsMobile] = useState(false)
const [isChatVisible, setIsChatVisible] = useState(true) const [isChatVisible, setIsChatVisible] = useState(true)
const [drawioUi, setDrawioUi] = useState<"min" | "sketch">("min") const [drawioUi, setDrawioUi] = useState<"min" | "sketch">("min")
@@ -207,7 +209,7 @@ export default function Home() {
<div className="h-full rounded-xl overflow-hidden shadow-soft-lg border border-border/30"> <div className="h-full rounded-xl overflow-hidden shadow-soft-lg border border-border/30">
{isLoaded ? ( {isLoaded ? (
<DrawIoEmbed <DrawIoEmbed
key={`${drawioUi}-${darkMode}`} key={`${drawioUi}-${darkMode}-${currentLang}`}
ref={drawioRef} ref={drawioRef}
onExport={handleDiagramExport} onExport={handleDiagramExport}
onLoad={onDrawioLoad} onLoad={onDrawioLoad}
@@ -220,6 +222,7 @@ export default function Home() {
saveAndExit: false, saveAndExit: false,
noExitBtn: true, noExitBtn: true,
dark: darkMode, dark: darkMode,
lang: currentLang,
}} }}
/> />
) : ( ) : (

View File

@@ -12,7 +12,11 @@ import fs from "fs/promises"
import { jsonrepair } from "jsonrepair" import { jsonrepair } from "jsonrepair"
import path from "path" import path from "path"
import { z } from "zod" import { z } from "zod"
import { getAIModel, supportsPromptCaching } from "@/lib/ai-providers" import {
getAIModel,
supportsImageInput,
supportsPromptCaching,
} from "@/lib/ai-providers"
import { findCachedResponse } from "@/lib/cached-responses" import { findCachedResponse } from "@/lib/cached-responses"
import { import {
checkAndIncrementRequest, checkAndIncrementRequest,
@@ -244,9 +248,22 @@ async function handleChatRequest(req: Request): Promise<Response> {
// === CACHE CHECK END === // === CACHE CHECK END ===
// Read client AI provider overrides from headers // Read client AI provider overrides from headers
const provider = req.headers.get("x-ai-provider")
let baseUrl = req.headers.get("x-ai-base-url")
// For EdgeOne provider, construct full URL from request origin
// because createOpenAI needs absolute URL, not relative path
if (provider === "edgeone" && !baseUrl) {
const origin = req.headers.get("origin") || new URL(req.url).origin
baseUrl = `${origin}/api/edgeai`
}
// Get cookie header for EdgeOne authentication (eo_token, eo_time)
const cookieHeader = req.headers.get("cookie")
const clientOverrides = { const clientOverrides = {
provider: req.headers.get("x-ai-provider"), provider,
baseUrl: req.headers.get("x-ai-base-url"), baseUrl,
apiKey: req.headers.get("x-ai-api-key"), apiKey: req.headers.get("x-ai-api-key"),
modelId: req.headers.get("x-ai-model"), modelId: req.headers.get("x-ai-model"),
// AWS Bedrock credentials // AWS Bedrock credentials
@@ -254,6 +271,11 @@ async function handleChatRequest(req: Request): Promise<Response> {
awsSecretAccessKey: req.headers.get("x-aws-secret-access-key"), awsSecretAccessKey: req.headers.get("x-aws-secret-access-key"),
awsRegion: req.headers.get("x-aws-region"), awsRegion: req.headers.get("x-aws-region"),
awsSessionToken: req.headers.get("x-aws-session-token"), awsSessionToken: req.headers.get("x-aws-session-token"),
// Pass cookies for EdgeOne Pages authentication
...(provider === "edgeone" &&
cookieHeader && {
headers: { cookie: cookieHeader },
}),
} }
// Read minimal style preference from header // Read minimal style preference from header
@@ -277,6 +299,17 @@ async function handleChatRequest(req: Request): Promise<Response> {
lastUserMessage?.parts?.filter((part: any) => part.type === "file") || lastUserMessage?.parts?.filter((part: any) => part.type === "file") ||
[] []
// Check if user is sending images to a model that doesn't support them
// AI SDK silently drops unsupported parts, so we need to catch this early
if (fileParts.length > 0 && !supportsImageInput(modelId)) {
return Response.json(
{
error: `The model "${modelId}" does not support image input. Please use a vision-capable model (e.g., GPT-4o, Claude, Gemini) or remove the image.`,
},
{ status: 400 },
)
}
// User input only - XML is now in a separate cached system message // User input only - XML is now in a separate cached system message
const formattedUserInput = `User input: const formattedUserInput = `User input:
"""md """md
@@ -605,7 +638,7 @@ Notes:
Operations: Operations:
- update: Replace an existing cell by its id. Provide cell_id and complete new_xml. - update: Replace an existing cell by its id. Provide cell_id and complete new_xml.
- add: Add a new cell. Provide cell_id (new unique id) and new_xml. - add: Add a new cell. Provide cell_id (new unique id) and new_xml.
- delete: Remove a cell by its id. Only cell_id is needed. - delete: Remove a cell. Cascade is automatic: children AND edges (source/target) are auto-deleted. Only specify ONE cell_id.
For update/add, new_xml must be a complete mxCell element including mxGeometry. For update/add, new_xml must be a complete mxCell element including mxGeometry.
@@ -614,8 +647,8 @@ For update/add, new_xml must be a complete mxCell element including mxGeometry.
Example - Add a rectangle: Example - Add a rectangle:
{"operations": [{"operation": "add", "cell_id": "rect-1", "new_xml": "<mxCell id=\\"rect-1\\" value=\\"Hello\\" style=\\"rounded=0;\\" vertex=\\"1\\" parent=\\"1\\"><mxGeometry x=\\"100\\" y=\\"100\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/></mxCell>"}]} {"operations": [{"operation": "add", "cell_id": "rect-1", "new_xml": "<mxCell id=\\"rect-1\\" value=\\"Hello\\" style=\\"rounded=0;\\" vertex=\\"1\\" parent=\\"1\\"><mxGeometry x=\\"100\\" y=\\"100\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/></mxCell>"}]}
Example - Delete a cell: Example - Delete container (children & edges auto-deleted):
{"operations": [{"operation": "delete", "cell_id": "rect-1"}]}`, {"operations": [{"operation": "delete", "cell_id": "2"}]}`,
inputSchema: z.object({ inputSchema: z.object({
operations: z operations: z
.array( .array(

View File

@@ -121,7 +121,7 @@ export async function POST(req: Request) {
{ status: 400 }, { status: 400 },
) )
} }
} else if (provider !== "ollama" && !apiKey) { } else if (provider !== "ollama" && provider !== "edgeone" && !apiKey) {
return NextResponse.json( return NextResponse.json(
{ valid: false, error: "API key is required" }, { valid: false, error: "API key is required" },
{ status: 400 }, { status: 400 },
@@ -225,6 +225,21 @@ export async function POST(req: Request) {
break break
} }
case "edgeone": {
// EdgeOne uses OpenAI-compatible API via Edge Functions
// Need to pass cookies for EdgeOne Pages authentication
const cookieHeader = req.headers.get("cookie") || ""
const edgeone = createOpenAI({
apiKey: "edgeone", // EdgeOne doesn't require API key
baseURL: baseUrl || "/api/edgeai",
headers: {
cookie: cookieHeader,
},
})
model = edgeone.chat(modelId)
break
}
case "sglang": { case "sglang": {
// SGLang is OpenAI-compatible // SGLang is OpenAI-compatible
const sglang = createOpenAI({ const sglang = createOpenAI({

View File

@@ -1,5 +1,5 @@
{ {
"$schema": "https://biomejs.dev/schemas/2.3.8/schema.json", "$schema": "https://biomejs.dev/schemas/2.3.10/schema.json",
"vcs": { "vcs": {
"enabled": true, "enabled": true,
"clientKind": "git", "clientKind": "git",

View File

@@ -27,6 +27,7 @@ import {
ReasoningTrigger, ReasoningTrigger,
} from "@/components/ai-elements/reasoning" } from "@/components/ai-elements/reasoning"
import { ScrollArea } from "@/components/ui/scroll-area" import { ScrollArea } from "@/components/ui/scroll-area"
import { useDictionary } from "@/hooks/use-dictionary"
import { getApiEndpoint } from "@/lib/base-path" import { getApiEndpoint } from "@/lib/base-path"
import { import {
applyDiagramOperations, applyDiagramOperations,
@@ -205,6 +206,7 @@ export function ChatMessageDisplay({
onEditMessage, onEditMessage,
status = "idle", status = "idle",
}: ChatMessageDisplayProps) { }: ChatMessageDisplayProps) {
const dict = useDictionary()
const { chartXML, loadDiagram: onDisplayChart } = useDiagram() const { chartXML, loadDiagram: onDisplayChart } = useDiagram()
const messagesEndRef = useRef<HTMLDivElement>(null) const messagesEndRef = useRef<HTMLDivElement>(null)
const previousXML = useRef<string>("") const previousXML = useRef<string>("")
@@ -228,6 +230,12 @@ export function ChatMessageDisplay({
const [expandedTools, setExpandedTools] = useState<Record<string, boolean>>( const [expandedTools, setExpandedTools] = useState<Record<string, boolean>>(
{}, {},
) )
const [copiedToolCallId, setCopiedToolCallId] = useState<string | null>(
null,
)
const [copyFailedToolCallId, setCopyFailedToolCallId] = useState<
string | null
>(null)
const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null) const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null)
const [copyFailedMessageId, setCopyFailedMessageId] = useState< const [copyFailedMessageId, setCopyFailedMessageId] = useState<
string | null string | null
@@ -243,13 +251,39 @@ export function ChatMessageDisplay({
Record<string, boolean> Record<string, boolean>
>({}) >({})
const copyMessageToClipboard = async (messageId: string, text: string) => { const setCopyState = (
try { messageId: string,
await navigator.clipboard.writeText(text) isToolCall: boolean,
isSuccess: boolean,
) => {
if (isSuccess) {
if (isToolCall) {
setCopiedToolCallId(messageId)
setTimeout(() => setCopiedToolCallId(null), 2000)
} else {
setCopiedMessageId(messageId) setCopiedMessageId(messageId)
setTimeout(() => setCopiedMessageId(null), 2000) setTimeout(() => setCopiedMessageId(null), 2000)
} catch (err) { }
} else {
if (isToolCall) {
setCopyFailedToolCallId(messageId)
setTimeout(() => setCopyFailedToolCallId(null), 2000)
} else {
setCopyFailedMessageId(messageId)
setTimeout(() => setCopyFailedMessageId(null), 2000)
}
}
}
const copyMessageToClipboard = async (
messageId: string,
text: string,
isToolCall = false,
) => {
try {
await navigator.clipboard.writeText(text)
setCopyState(messageId, isToolCall, true)
} catch (_err) {
// Fallback for non-secure contexts (HTTP) or permission denied // Fallback for non-secure contexts (HTTP) or permission denied
const textarea = document.createElement("textarea") const textarea = document.createElement("textarea")
textarea.value = text textarea.value = text
@@ -264,15 +298,11 @@ export function ChatMessageDisplay({
if (!success) { if (!success) {
throw new Error("Copy command failed") throw new Error("Copy command failed")
} }
setCopiedMessageId(messageId) setCopyState(messageId, isToolCall, true)
setTimeout(() => setCopiedMessageId(null), 2000)
} catch (fallbackErr) { } catch (fallbackErr) {
console.error("Failed to copy message:", fallbackErr) console.error("Failed to copy message:", fallbackErr)
toast.error( toast.error(dict.chat.failedToCopyDetail)
"Failed to copy message. Please copy manually or check clipboard permissions.", setCopyState(messageId, isToolCall, false)
)
setCopyFailedMessageId(messageId)
setTimeout(() => setCopyFailedMessageId(null), 2000)
} finally { } finally {
document.body.removeChild(textarea) document.body.removeChild(textarea)
} }
@@ -304,7 +334,7 @@ export function ChatMessageDisplay({
}) })
} catch (error) { } catch (error) {
console.error("Failed to log feedback:", error) console.error("Failed to log feedback:", error)
toast.error("Failed to record your feedback. Please try again.") toast.error(dict.errors.failedToRecordFeedback)
// Revert optimistic UI update // Revert optimistic UI update
setFeedback((prev) => { setFeedback((prev) => {
const next = { ...prev } const next = { ...prev }
@@ -349,9 +379,7 @@ export function ChatMessageDisplay({
console.error( console.error(
"[ChatMessageDisplay] Malformed XML detected in final output", "[ChatMessageDisplay] Malformed XML detected in final output",
) )
toast.error( toast.error(dict.errors.malformedXml)
"AI generated invalid diagram XML. Please try regenerating.",
)
} }
return // Skip this update return // Skip this update
} }
@@ -402,9 +430,7 @@ export function ChatMessageDisplay({
"[ChatMessageDisplay] XML validation failed:", "[ChatMessageDisplay] XML validation failed:",
validation.error, validation.error,
) )
toast.error( toast.error(dict.errors.validationFailed)
"Diagram validation failed. Please try regenerating.",
)
} }
} catch (error) { } catch (error) {
console.error( console.error(
@@ -413,9 +439,7 @@ export function ChatMessageDisplay({
) )
// Only show toast if this is the final XML (not during streaming) // Only show toast if this is the final XML (not during streaming)
if (showToast) { if (showToast) {
toast.error( toast.error(dict.errors.failedToProcess)
"Failed to process diagram. Please try regenerating.",
)
} }
} }
} }
@@ -647,6 +671,7 @@ export function ChatMessageDisplay({
const { state, input, output } = part const { state, input, output } = part
const isExpanded = expandedTools[callId] ?? true const isExpanded = expandedTools[callId] ?? true
const toolName = part.type?.replace("tool-", "") const toolName = part.type?.replace("tool-", "")
const isCopied = copiedToolCallId === callId
const toggleExpanded = () => { const toggleExpanded = () => {
setExpandedTools((prev) => ({ setExpandedTools((prev) => ({
@@ -668,6 +693,35 @@ export function ChatMessageDisplay({
} }
} }
const handleCopy = () => {
let textToCopy = ""
if (input && typeof input === "object") {
if (input.xml) {
textToCopy = input.xml
} else if (
input.operations &&
Array.isArray(input.operations)
) {
textToCopy = JSON.stringify(input.operations, null, 2)
} else if (Object.keys(input).length > 0) {
textToCopy = JSON.stringify(input, null, 2)
}
}
if (
output &&
toolName === "get_shape_library" &&
typeof output === "string"
) {
textToCopy = output
}
if (textToCopy) {
copyMessageToClipboard(callId, textToCopy, true)
}
}
return ( return (
<div <div
key={callId} key={callId}
@@ -687,9 +741,32 @@ export function ChatMessageDisplay({
<div className="h-4 w-4 border-2 border-primary border-t-transparent rounded-full animate-spin" /> <div className="h-4 w-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
)} )}
{state === "output-available" && ( {state === "output-available" && (
<>
<span className="text-xs font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full"> <span className="text-xs font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
Complete {dict.tools.complete}
</span> </span>
{isExpanded && (
<button
type="button"
onClick={handleCopy}
className="p-1 rounded hover:bg-muted transition-colors"
title={
copiedToolCallId === callId
? dict.chat.copied
: copyFailedToolCallId ===
callId
? dict.chat.failedToCopy
: dict.chat.copyResponse
}
>
{isCopied ? (
<Check className="w-4 h-4 text-green-600" />
) : (
<Copy className="w-4 h-4 text-muted-foreground" />
)}
</button>
)}
</>
)} )}
{state === "output-error" && {state === "output-error" &&
(() => { (() => {
@@ -832,7 +909,10 @@ export function ChatMessageDisplay({
) )
}} }}
className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-muted-foreground hover:bg-muted transition-colors" className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-muted-foreground hover:bg-muted transition-colors"
title="Edit message" title={
dict.chat
.editMessage
}
> >
<Pencil className="h-3.5 w-3.5" /> <Pencil className="h-3.5 w-3.5" />
</button> </button>
@@ -849,11 +929,13 @@ export function ChatMessageDisplay({
title={ title={
copiedMessageId === copiedMessageId ===
message.id message.id
? "Copied!" ? dict.chat.copied
: copyFailedMessageId === : copyFailedMessageId ===
message.id message.id
? "Failed to copy" ? dict.chat
: "Copy message" .failedToCopy
: dict.chat
.copyResponse
} }
> >
{copiedMessageId === {copiedMessageId ===
@@ -968,7 +1050,7 @@ export function ChatMessageDisplay({
}} }}
className="px-3 py-1.5 text-xs rounded-lg bg-muted hover:bg-muted/80 transition-colors" className="px-3 py-1.5 text-xs rounded-lg bg-muted hover:bg-muted/80 transition-colors"
> >
Cancel {dict.common.cancel}
</button> </button>
<button <button
type="button" type="button"
@@ -990,7 +1072,7 @@ export function ChatMessageDisplay({
disabled={!editText.trim()} disabled={!editText.trim()}
className="px-3 py-1.5 text-xs rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors" className="px-3 py-1.5 text-xs rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
> >
Save & Submit {dict.chat.saveAndSubmit}
</button> </button>
</div> </div>
</div> </div>
@@ -1123,7 +1205,8 @@ export function ChatMessageDisplay({
"user" && "user" &&
isLastUserMessage && isLastUserMessage &&
onEditMessage onEditMessage
? "Click to edit" ? dict.chat
.clickToEdit
: undefined : undefined
} }
> >
@@ -1325,8 +1408,8 @@ export function ChatMessageDisplay({
title={ title={
copiedMessageId === copiedMessageId ===
message.id message.id
? "Copied!" ? dict.chat.copied
: "Copy response" : dict.chat.copyResponse
} }
> >
{copiedMessageId === {copiedMessageId ===
@@ -1352,7 +1435,9 @@ export function ChatMessageDisplay({
) )
} }
className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-foreground hover:bg-muted transition-colors" className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-foreground hover:bg-muted transition-colors"
title="Regenerate response" title={
dict.chat.regenerate
}
> >
<RotateCcw className="h-3.5 w-3.5" /> <RotateCcw className="h-3.5 w-3.5" />
</button> </button>
@@ -1374,7 +1459,7 @@ export function ChatMessageDisplay({
? "text-green-600 bg-green-100" ? "text-green-600 bg-green-100"
: "text-muted-foreground/60 hover:text-green-600 hover:bg-green-50" : "text-muted-foreground/60 hover:text-green-600 hover:bg-green-50"
}`} }`}
title="Good response" title={dict.chat.goodResponse}
> >
<ThumbsUp className="h-3.5 w-3.5" /> <ThumbsUp className="h-3.5 w-3.5" />
</button> </button>
@@ -1393,7 +1478,7 @@ export function ChatMessageDisplay({
? "text-red-600 bg-red-100" ? "text-red-600 bg-red-100"
: "text-muted-foreground/60 hover:text-red-600 hover:bg-red-50" : "text-muted-foreground/60 hover:text-red-600 hover:bg-red-50"
}`} }`}
title="Bad response" title={dict.chat.badResponse}
> >
<ThumbsDown className="h-3.5 w-3.5" /> <ThumbsDown className="h-3.5 w-3.5" />
</button> </button>

View File

@@ -3,14 +3,12 @@
import { useChat } from "@ai-sdk/react" import { useChat } from "@ai-sdk/react"
import { DefaultChatTransport } from "ai" import { DefaultChatTransport } from "ai"
import { import {
AlertTriangle,
MessageSquarePlus, MessageSquarePlus,
PanelRightClose, PanelRightClose,
PanelRightOpen, PanelRightOpen,
Settings, Settings,
} from "lucide-react" } from "lucide-react"
import Image from "next/image" import Image from "next/image"
import Link from "next/link"
import type React from "react" import type React from "react"
import { useCallback, useEffect, useRef, useState } from "react" import { useCallback, useEffect, useRef, useState } from "react"
import { flushSync } from "react-dom" import { flushSync } from "react-dom"
@@ -26,6 +24,7 @@ import { useDictionary } from "@/hooks/use-dictionary"
import { getSelectedAIConfig, useModelConfig } from "@/hooks/use-model-config" import { getSelectedAIConfig, useModelConfig } from "@/hooks/use-model-config"
import { getApiEndpoint } from "@/lib/base-path" import { getApiEndpoint } from "@/lib/base-path"
import { findCachedResponse } from "@/lib/cached-responses" import { findCachedResponse } from "@/lib/cached-responses"
import { formatMessage } from "@/lib/i18n/utils"
import { isPdfFile, isTextFile } from "@/lib/pdf-utils" import { isPdfFile, isTextFile } from "@/lib/pdf-utils"
import { type FileData, useFileProcessor } from "@/lib/use-file-processor" import { type FileData, useFileProcessor } from "@/lib/use-file-processor"
import { useQuotaManager } from "@/lib/use-quota-manager" import { useQuotaManager } from "@/lib/use-quota-manager"
@@ -336,7 +335,10 @@ export default function ChatPanel({
} }
// Translate image not supported error // Translate image not supported error
if (friendlyMessage.includes("image content block")) { if (
friendlyMessage.includes("image content block") ||
friendlyMessage.toLowerCase().includes("image_url")
) {
friendlyMessage = "This model doesn't support image input." friendlyMessage = "This model doesn't support image input."
} }
@@ -389,7 +391,9 @@ export default function ChatPanel({
MAX_CONTINUATION_RETRY_COUNT MAX_CONTINUATION_RETRY_COUNT
) { ) {
toast.error( toast.error(
`Continuation retry limit reached (${MAX_CONTINUATION_RETRY_COUNT}). The diagram may be too complex.`, formatMessage(dict.errors.continuationRetryLimit, {
max: MAX_CONTINUATION_RETRY_COUNT,
}),
) )
continuationRetryCountRef.current = 0 continuationRetryCountRef.current = 0
partialXmlRef.current = "" partialXmlRef.current = ""
@@ -400,7 +404,9 @@ export default function ChatPanel({
// Regular error: check retry count limit // Regular error: check retry count limit
if (autoRetryCountRef.current >= MAX_AUTO_RETRY_COUNT) { if (autoRetryCountRef.current >= MAX_AUTO_RETRY_COUNT) {
toast.error( toast.error(
`Auto-retry limit reached (${MAX_AUTO_RETRY_COUNT}). Please try again manually.`, formatMessage(dict.errors.retryLimit, {
max: MAX_AUTO_RETRY_COUNT,
}),
) )
autoRetryCountRef.current = 0 autoRetryCountRef.current = 0
partialXmlRef.current = "" partialXmlRef.current = ""
@@ -450,7 +456,7 @@ export default function ChatPanel({
// On complete failure, clear storage to allow recovery // On complete failure, clear storage to allow recovery
localStorage.removeItem(STORAGE_MESSAGES_KEY) localStorage.removeItem(STORAGE_MESSAGES_KEY)
localStorage.removeItem(STORAGE_XML_SNAPSHOTS_KEY) localStorage.removeItem(STORAGE_XML_SNAPSHOTS_KEY)
toast.error("Session data was corrupted. Starting fresh.") toast.error(dict.errors.sessionCorrupted)
} }
}, [setMessages]) }, [setMessages])
@@ -651,12 +657,10 @@ export default function ChatPanel({
localStorage.removeItem(STORAGE_DIAGRAM_XML_KEY) localStorage.removeItem(STORAGE_DIAGRAM_XML_KEY)
localStorage.setItem(STORAGE_SESSION_ID_KEY, newSessionId) localStorage.setItem(STORAGE_SESSION_ID_KEY, newSessionId)
sessionStorage.removeItem(SESSION_STORAGE_INPUT_KEY) sessionStorage.removeItem(SESSION_STORAGE_INPUT_KEY)
toast.success("Started a fresh chat") toast.success(dict.dialogs.clearSuccess)
} catch (error) { } catch (error) {
console.error("Failed to clear localStorage:", error) console.error("Failed to clear localStorage:", error)
toast.warning( toast.warning(dict.errors.storageUpdateFailed)
"Chat cleared but browser storage could not be updated",
)
} }
setShowNewChatDialog(false) setShowNewChatDialog(false)
@@ -889,7 +893,7 @@ export default function ChatPanel({
return ( return (
<div className="h-full flex flex-col items-center pt-4 bg-card border border-border/30 rounded-xl"> <div className="h-full flex flex-col items-center pt-4 bg-card border border-border/30 rounded-xl">
<ButtonWithTooltip <ButtonWithTooltip
tooltipContent="Show chat panel (Ctrl+B)" tooltipContent={dict.nav.showPanel}
variant="ghost" variant="ghost"
size="icon" size="icon"
onClick={onToggleVisibility} onClick={onToggleVisibility}
@@ -901,10 +905,9 @@ export default function ChatPanel({
className="text-sm font-medium text-muted-foreground mt-8 tracking-wide" className="text-sm font-medium text-muted-foreground mt-8 tracking-wide"
style={{ style={{
writingMode: "vertical-rl", writingMode: "vertical-rl",
transform: "rotate(180deg)",
}} }}
> >
AI Chat {dict.nav.aiChat}
</div> </div>
</div> </div>
) )
@@ -949,32 +952,6 @@ export default function ChatPanel({
Next AI Drawio Next AI Drawio
</h1> </h1>
</div> </div>
{!isMobile && (
<Link
href="/about"
target="_blank"
rel="noopener noreferrer"
className="text-sm text-muted-foreground hover:text-foreground transition-colors ml-2"
>
About
</Link>
)}
{!isMobile && (
<Link
href="/about"
target="_blank"
rel="noopener noreferrer"
>
<ButtonWithTooltip
tooltipContent="Sponsored by ByteDance Doubao K2-thinking. See About page for details."
variant="ghost"
size="icon"
className="h-6 w-6 text-amber-500 hover:text-amber-600"
>
<AlertTriangle className="h-4 w-4" />
</ButtonWithTooltip>
</Link>
)}
</div> </div>
<div className="flex items-center gap-1 justify-end overflow-visible"> <div className="flex items-center gap-1 justify-end overflow-visible">
<ButtonWithTooltip <ButtonWithTooltip

View File

@@ -1,6 +1,7 @@
"use client" "use client"
import { useEffect, useRef, useState } from "react" import { useEffect, useRef, useState } from "react"
import { useDictionary } from "@/hooks/use-dictionary"
import { wrapWithMxFile } from "@/lib/utils" import { wrapWithMxFile } from "@/lib/utils"
// Dev XML presets for streaming simulator // Dev XML presets for streaming simulator
@@ -142,6 +143,7 @@ export function DevXmlSimulator({
onDisplayChart, onDisplayChart,
onShowQuotaToast, onShowQuotaToast,
}: DevXmlSimulatorProps) { }: DevXmlSimulatorProps) {
const dict = useDictionary()
const [devXml, setDevXml] = useState("") const [devXml, setDevXml] = useState("")
const [isSimulating, setIsSimulating] = useState(false) const [isSimulating, setIsSimulating] = useState(false)
const [devIntervalMs, setDevIntervalMs] = useState(1) const [devIntervalMs, setDevIntervalMs] = useState(1)
@@ -178,7 +180,7 @@ export function DevXmlSimulator({
parts: [ parts: [
{ {
type: "text" as const, type: "text" as const,
text: "[Dev] Simulating XML streaming", text: dict.dev.simulatingMessage,
}, },
], ],
} }
@@ -228,7 +230,7 @@ export function DevXmlSimulator({
const lastMsg = updated[updated.length - 1] as any const lastMsg = updated[updated.length - 1] as any
if (lastMsg?.role === "assistant" && lastMsg.parts?.[0]) { if (lastMsg?.role === "assistant" && lastMsg.parts?.[0]) {
lastMsg.parts[0].state = "output-available" lastMsg.parts[0].state = "output-available"
lastMsg.parts[0].output = "Successfully displayed the diagram." lastMsg.parts[0].output = dict.dev.successMessage
lastMsg.parts[0].input = { xml } lastMsg.parts[0].input = { xml }
} }
return updated return updated
@@ -245,12 +247,12 @@ export function DevXmlSimulator({
<div className="border-t border-dashed border-orange-500/50 px-4 py-2 bg-orange-50/50 dark:bg-orange-950/30"> <div className="border-t border-dashed border-orange-500/50 px-4 py-2 bg-orange-50/50 dark:bg-orange-950/30">
<details> <details>
<summary className="text-xs text-orange-600 dark:text-orange-400 cursor-pointer font-medium"> <summary className="text-xs text-orange-600 dark:text-orange-400 cursor-pointer font-medium">
Dev: XML Streaming Simulator {dict.dev.title}
</summary> </summary>
<div className="mt-2 space-y-2"> <div className="mt-2 space-y-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<label className="text-xs text-muted-foreground whitespace-nowrap"> <label className="text-xs text-muted-foreground whitespace-nowrap">
Preset: {dict.dev.preset}
</label> </label>
<select <select
onChange={(e) => { onChange={(e) => {
@@ -262,7 +264,7 @@ export function DevXmlSimulator({
defaultValue="" defaultValue=""
> >
<option value="" disabled> <option value="" disabled>
Select a preset... {dict.dev.selectPreset}
</option> </option>
{Object.keys(DEV_XML_PRESETS).map((name) => ( {Object.keys(DEV_XML_PRESETS).map((name) => (
<option key={name} value={name}> <option key={name} value={name}>
@@ -275,19 +277,19 @@ export function DevXmlSimulator({
onClick={() => setDevXml("")} onClick={() => setDevXml("")}
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground border rounded" className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground border rounded"
> >
Clear {dict.dev.clear}
</button> </button>
</div> </div>
<textarea <textarea
value={devXml} value={devXml}
onChange={(e) => setDevXml(e.target.value)} onChange={(e) => setDevXml(e.target.value)}
placeholder="Paste mxCell XML here or select a preset..." placeholder={dict.dev.placeholder}
className="w-full h-24 text-xs font-mono p-2 border rounded bg-background" className="w-full h-24 text-xs font-mono p-2 border rounded bg-background"
/> />
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<div className="flex items-center gap-2 flex-1"> <div className="flex items-center gap-2 flex-1">
<label className="text-xs text-muted-foreground whitespace-nowrap"> <label className="text-xs text-muted-foreground whitespace-nowrap">
Interval: {dict.dev.interval}
</label> </label>
<input <input
type="range" type="range"
@@ -306,7 +308,7 @@ export function DevXmlSimulator({
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<label className="text-xs text-muted-foreground whitespace-nowrap"> <label className="text-xs text-muted-foreground whitespace-nowrap">
Chars: {dict.dev.chars}
</label> </label>
<input <input
type="number" type="number"
@@ -330,8 +332,8 @@ export function DevXmlSimulator({
className="px-3 py-1 text-xs bg-orange-500 text-white rounded hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed" className="px-3 py-1 text-xs bg-orange-500 text-white rounded hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed"
> >
{isSimulating {isSimulating
? "Streaming..." ? dict.dev.streaming
: `Simulate (${devChunkSize} chars/${devIntervalMs}ms)`} : `${dict.dev.simulate} (${devChunkSize} chars/${devIntervalMs}ms)`}
</button> </button>
{isSimulating && ( {isSimulating && (
<button <button
@@ -341,7 +343,7 @@ export function DevXmlSimulator({
}} }}
className="px-3 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600" className="px-3 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
> >
Stop {dict.dev.stop}
</button> </button>
)} )}
{onShowQuotaToast && ( {onShowQuotaToast && (
@@ -350,7 +352,7 @@ export function DevXmlSimulator({
onClick={onShowQuotaToast} onClick={onShowQuotaToast}
className="px-3 py-1 text-xs bg-purple-500 text-white rounded hover:bg-purple-600" className="px-3 py-1 text-xs bg-purple-500 text-white rounded hover:bg-purple-600"
> >
Test Quota Toast {dict.dev.testQuotaToast}
</button> </button>
)} )}
</div> </div>

View File

@@ -21,7 +21,6 @@ import {
Zap, Zap,
} from "lucide-react" } from "lucide-react"
import { useCallback, useEffect, useRef, useState } from "react" import { useCallback, useEffect, useRef, useState } from "react"
import { toast } from "sonner"
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -78,6 +77,7 @@ const PROVIDER_LOGO_MAP: Record<string, string> = {
siliconflow: "siliconflow", siliconflow: "siliconflow",
sglang: "openai", // SGLang is OpenAI-compatible sglang: "openai", // SGLang is OpenAI-compatible
gateway: "vercel", gateway: "vercel",
edgeone: "tencent-cloud",
doubao: "bytedance", doubao: "bytedance",
} }
@@ -277,6 +277,7 @@ export function ModelConfigDialog({
// Check credentials based on provider type // Check credentials based on provider type
const isBedrock = selectedProvider.provider === "bedrock" const isBedrock = selectedProvider.provider === "bedrock"
const isEdgeOne = selectedProvider.provider === "edgeone"
if (isBedrock) { if (isBedrock) {
if ( if (
!selectedProvider.awsAccessKeyId || !selectedProvider.awsAccessKeyId ||
@@ -285,7 +286,7 @@ export function ModelConfigDialog({
) { ) {
return return
} }
} else if (!selectedProvider.apiKey) { } else if (!isEdgeOne && !selectedProvider.apiKey) {
return return
} }
@@ -308,13 +309,18 @@ export function ModelConfigDialog({
setValidatingModelIndex(i) setValidatingModelIndex(i)
try { try {
// For EdgeOne, construct baseUrl from current origin
const baseUrl = isEdgeOne
? `${window.location.origin}/api/edgeai`
: selectedProvider.baseUrl
const response = await fetch("/api/validate-model", { const response = await fetch("/api/validate-model", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
provider: selectedProvider.provider, provider: selectedProvider.provider,
apiKey: selectedProvider.apiKey, apiKey: selectedProvider.apiKey,
baseUrl: selectedProvider.baseUrl, baseUrl,
modelId: model.modelId, modelId: model.modelId,
// AWS Bedrock credentials // AWS Bedrock credentials
awsAccessKeyId: selectedProvider.awsAccessKeyId, awsAccessKeyId: selectedProvider.awsAccessKeyId,
@@ -322,7 +328,6 @@ export function ModelConfigDialog({
awsRegion: selectedProvider.awsRegion, awsRegion: selectedProvider.awsRegion,
}), }),
}) })
const data = await response.json() const data = await response.json()
if (data.valid) { if (data.valid) {
@@ -511,7 +516,6 @@ export function ModelConfigDialog({
{/* Provider Details (Right Panel) */} {/* Provider Details (Right Panel) */}
<div className="flex-1 min-w-0 flex flex-col overflow-auto [&::-webkit-scrollbar]:hidden "> <div className="flex-1 min-w-0 flex flex-col overflow-auto [&::-webkit-scrollbar]:hidden ">
{selectedProvider ? ( {selectedProvider ? (
<>
<ScrollArea className="flex-1" ref={scrollRef}> <ScrollArea className="flex-1" ref={scrollRef}>
<div className="p-6 space-y-8"> <div className="p-6 space-y-8">
{/* Provider Header */} {/* Provider Header */}
@@ -553,10 +557,7 @@ export function ModelConfigDialog({
<div className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-success-muted text-success"> <div className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-success-muted text-success">
<Check className="h-3.5 w-3.5 animate-check-pop" /> <Check className="h-3.5 w-3.5 animate-check-pop" />
<span className="text-xs font-medium"> <span className="text-xs font-medium">
{ {dict.modelConfig.verified}
dict.modelConfig
.verified
}
</span> </span>
</div> </div>
)} )}
@@ -569,18 +570,13 @@ export function ModelConfigDialog({
className="text-destructive hover:text-destructive hover:bg-destructive/10" className="text-destructive hover:text-destructive hover:bg-destructive/10"
> >
<Trash2 className="h-4 w-4 mr-1.5" /> <Trash2 className="h-4 w-4 mr-1.5" />
{ {dict.modelConfig.deleteProvider}
dict.modelConfig
.deleteProvider
}
</Button> </Button>
</div> </div>
{/* Configuration Section */} {/* Configuration Section */}
<ConfigSection <ConfigSection
title={ title={dict.modelConfig.configuration}
dict.modelConfig.configuration
}
icon={Settings2} icon={Settings2}
> >
<ConfigCard> <ConfigCard>
@@ -630,8 +626,7 @@ export function ModelConfigDialog({
> >
<Key className="h-3.5 w-3.5 text-muted-foreground" /> <Key className="h-3.5 w-3.5 text-muted-foreground" />
{ {
dict dict.modelConfig
.modelConfig
.awsAccessKeyId .awsAccessKeyId
} }
</Label> </Label>
@@ -666,8 +661,7 @@ export function ModelConfigDialog({
> >
<Key className="h-3.5 w-3.5 text-muted-foreground" /> <Key className="h-3.5 w-3.5 text-muted-foreground" />
{ {
dict dict.modelConfig
.modelConfig
.awsSecretAccessKey .awsSecretAccessKey
} }
</Label> </Label>
@@ -683,13 +677,10 @@ export function ModelConfigDialog({
selectedProvider.awsSecretAccessKey || selectedProvider.awsSecretAccessKey ||
"" ""
} }
onChange={( onChange={(e) =>
e,
) =>
handleProviderUpdate( handleProviderUpdate(
"awsSecretAccessKey", "awsSecretAccessKey",
e e.target
.target
.value, .value,
) )
} }
@@ -731,8 +722,7 @@ export function ModelConfigDialog({
> >
<Link2 className="h-3.5 w-3.5 text-muted-foreground" /> <Link2 className="h-3.5 w-3.5 text-muted-foreground" />
{ {
dict dict.modelConfig
.modelConfig
.awsRegion .awsRegion
} }
</Label> </Label>
@@ -811,8 +801,7 @@ export function ModelConfigDialog({
</SelectItem> </SelectItem>
<SelectItem value="sa-east-1"> <SelectItem value="sa-east-1">
sa-east-1 sa-east-1
(São (São Paulo)
Paulo)
</SelectItem> </SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
@@ -859,8 +848,7 @@ export function ModelConfigDialog({
} }
</> </>
) : ( ) : (
dict dict.modelConfig
.modelConfig
.test .test
)} )}
</Button> </Button>
@@ -876,6 +864,62 @@ export function ModelConfigDialog({
)} )}
</div> </div>
</> </>
) : selectedProvider.provider ===
"edgeone" ? (
<div className="space-y-3">
<div className="flex items-center gap-2">
<Button
variant={
validationStatus ===
"success"
? "outline"
: "default"
}
size="sm"
onClick={
handleValidate
}
disabled={
validationStatus ===
"validating"
}
className={cn(
"h-9 px-4",
validationStatus ===
"success" &&
"text-success border-success/30 bg-success-muted hover:bg-success-muted",
)}
>
{validationStatus ===
"validating" ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : validationStatus ===
"success" ? (
<>
<Check className="h-4 w-4 mr-1.5" />
{
dict
.modelConfig
.verified
}
</>
) : (
dict.modelConfig
.test
)}
</Button>
{validationStatus ===
"error" &&
validationError && (
<p className="text-xs text-destructive flex items-center gap-1">
<X className="h-3 w-3" />
{
validationError
}
</p>
)}
</div>
</div>
) : ( ) : (
<> <>
{/* API Key */} {/* API Key */}
@@ -886,8 +930,7 @@ export function ModelConfigDialog({
> >
<Key className="h-3.5 w-3.5 text-muted-foreground" /> <Key className="h-3.5 w-3.5 text-muted-foreground" />
{ {
dict dict.modelConfig
.modelConfig
.apiKey .apiKey
} }
</Label> </Label>
@@ -1004,8 +1047,7 @@ export function ModelConfigDialog({
> >
<Link2 className="h-3.5 w-3.5 text-muted-foreground" /> <Link2 className="h-3.5 w-3.5 text-muted-foreground" />
{ {
dict dict.modelConfig
.modelConfig
.baseUrl .baseUrl
} }
<span className="text-muted-foreground font-normal"> <span className="text-muted-foreground font-normal">
@@ -1035,8 +1077,7 @@ export function ModelConfigDialog({
.provider .provider
] ]
.defaultBaseUrl || .defaultBaseUrl ||
dict dict.modelConfig
.modelConfig
.customEndpoint .customEndpoint
} }
className="h-9 rounded-xl font-mono text-xs" className="h-9 rounded-xl font-mono text-xs"
@@ -1059,13 +1100,10 @@ export function ModelConfigDialog({
dict.modelConfig dict.modelConfig
.customModelId .customModelId
} }
value={ value={customModelInput}
customModelInput
}
onChange={(e) => { onChange={(e) => {
setCustomModelInput( setCustomModelInput(
e.target e.target.value,
.value,
) )
if ( if (
duplicateError duplicateError
@@ -1085,9 +1123,7 @@ export function ModelConfigDialog({
handleAddModel( handleAddModel(
customModelInput.trim(), customModelInput.trim(),
) )
if ( if (success) {
success
) {
setCustomModelInput( setCustomModelInput(
"", "",
) )
@@ -1132,9 +1168,7 @@ export function ModelConfigDialog({
<Plus className="h-3.5 w-3.5" /> <Plus className="h-3.5 w-3.5" />
</Button> </Button>
<Select <Select
onValueChange={( onValueChange={(value) => {
value,
) => {
if (value) { if (value) {
handleAddModel( handleAddModel(
value, value,
@@ -1170,9 +1204,7 @@ export function ModelConfigDialog({
} }
className="font-mono text-xs" className="font-mono text-xs"
> >
{ {modelId}
modelId
}
</SelectItem> </SelectItem>
), ),
)} )}
@@ -1183,8 +1215,8 @@ export function ModelConfigDialog({
> >
{/* Model List */} {/* Model List */}
<div className="rounded-2xl border border-border-subtle bg-surface-2/30 overflow-hidden min-h-[120px]"> <div className="rounded-2xl border border-border-subtle bg-surface-2/30 overflow-hidden min-h-[120px]">
{selectedProvider.models {selectedProvider.models.length ===
.length === 0 ? ( 0 ? (
<div className="p-6 text-center h-full flex flex-col items-center justify-center"> <div className="p-6 text-center h-full flex flex-col items-center justify-center">
<div className="inline-flex items-center justify-center w-10 h-10 rounded-full bg-surface-2 mb-3"> <div className="inline-flex items-center justify-center w-10 h-10 rounded-full bg-surface-2 mb-3">
<Sparkles className="h-5 w-5 text-muted-foreground" /> <Sparkles className="h-5 w-5 text-muted-foreground" />
@@ -1201,9 +1233,7 @@ export function ModelConfigDialog({
{selectedProvider.models.map( {selectedProvider.models.map(
(model, index) => ( (model, index) => (
<div <div
key={ key={model.id}
model.id
}
className={cn( className={cn(
"transition-colors duration-150 hover:bg-interactive-hover/50", "transition-colors duration-150 hover:bg-interactive-hover/50",
)} )}
@@ -1437,7 +1467,6 @@ export function ModelConfigDialog({
</ConfigSection> </ConfigSection>
</div> </div>
</ScrollArea> </ScrollArea>
</>
) : ( ) : (
<div className="h-full flex flex-col items-center justify-center p-8 text-center"> <div className="h-full flex flex-col items-center justify-center p-8 text-center">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-surface-2 mb-4"> <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-surface-2 mb-4">

View File

@@ -48,6 +48,7 @@ const PROVIDER_LOGO_MAP: Record<string, string> = {
siliconflow: "siliconflow", siliconflow: "siliconflow",
sglang: "openai", // SGLang is OpenAI-compatible, use OpenAI logo sglang: "openai", // SGLang is OpenAI-compatible, use OpenAI logo
gateway: "vercel", gateway: "vercel",
edgeone: "tencent-cloud",
doubao: "bytedance", doubao: "bytedance",
} }

View File

@@ -395,13 +395,13 @@ function SettingsContent({
<> <>
<span className="text-muted-foreground">·</span> <span className="text-muted-foreground">·</span>
<a <a
href="/about" href={`/${currentLang}/about${currentLang === "zh" ? "/cn" : currentLang === "ja" ? "/ja" : ""}`}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1" className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1"
> >
<Info className="h-3 w-3" /> <Info className="h-3 w-3" />
About {dict.nav.about}
</a> </a>
</> </>
)} )}

View File

@@ -4,7 +4,7 @@
**AI驱动的图表创建工具 - 对话、绘制、可视化** **AI驱动的图表创建工具 - 对话、绘制、可视化**
[English](../README.md) | 中文 | [日本語](./README_JA.md) [English](../../README.md) | 中文 | [日本語](../ja/README_JA.md)
[![TrendShift](https://trendshift.io/api/badge/repositories/15449)](https://next-ai-drawio.jiang.jp/) [![TrendShift](https://trendshift.io/api/badge/repositories/15449)](https://next-ai-drawio.jiang.jp/)
@@ -13,7 +13,7 @@
[![React](https://img.shields.io/badge/React-19.x-61dafb)](https://react.dev/) [![React](https://img.shields.io/badge/React-19.x-61dafb)](https://react.dev/)
[![Sponsor](https://img.shields.io/badge/Sponsor-❤-ea4aaa)](https://github.com/sponsors/DayuanJiang) [![Sponsor](https://img.shields.io/badge/Sponsor-❤-ea4aaa)](https://github.com/sponsors/DayuanJiang)
[![Live Demo](../public/live-demo-button.svg)](https://next-ai-drawio.jiang.jp/) [![Live Demo](../../public/live-demo-button.svg)](https://next-ai-drawio.jiang.jp/)
</div> </div>
@@ -29,14 +29,18 @@ https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
- [示例](#示例) - [示例](#示例)
- [功能特性](#功能特性) - [功能特性](#功能特性)
- [MCP服务器预览](#mcp服务器预览) - [MCP服务器预览](#mcp服务器预览)
- [Claude Code CLI](#claude-code-cli)
- [快速开始](#快速开始) - [快速开始](#快速开始)
- [在线试用](#在线试用) - [在线试用](#在线试用)
- [使用Docker运行推荐](#使用docker运行推荐) - [桌面应用](#桌面应用)
- [使用Docker运行](#使用docker运行)
- [安装](#安装) - [安装](#安装)
- [部署](#部署) - [部署](#部署)
- [部署到腾讯云EdgeOne Pages](#部署到腾讯云edgeone-pages)
- [部署到Vercel推荐](#部署到vercel推荐)
- [部署到Cloudflare Workers](#部署到cloudflare-workers)
- [多提供商支持](#多提供商支持) - [多提供商支持](#多提供商支持)
- [工作原理](#工作原理) - [工作原理](#工作原理)
- [项目结构](#项目结构)
- [支持与联系](#支持与联系) - [支持与联系](#支持与联系)
- [Star历史](#star历史) - [Star历史](#star历史)
@@ -50,31 +54,31 @@ https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
<td colspan="2" valign="top" align="center"> <td colspan="2" valign="top" align="center">
<strong>动画Transformer连接器</strong><br /> <strong>动画Transformer连接器</strong><br />
<p><strong>提示词:</strong> 给我一个带有**动画连接器**的Transformer架构图。</p> <p><strong>提示词:</strong> 给我一个带有**动画连接器**的Transformer架构图。</p>
<img src="../public/animated_connectors.svg" alt="带动画连接器的Transformer架构" width="480" /> <img src="../../public/animated_connectors.svg" alt="带动画连接器的Transformer架构" width="480" />
</td> </td>
</tr> </tr>
<tr> <tr>
<td width="50%" valign="top"> <td width="50%" valign="top">
<strong>GCP架构图</strong><br /> <strong>GCP架构图</strong><br />
<p><strong>提示词:</strong> 使用**GCP图标**生成一个GCP架构图。在这个图中用户连接到托管在实例上的前端。</p> <p><strong>提示词:</strong> 使用**GCP图标**生成一个GCP架构图。在这个图中用户连接到托管在实例上的前端。</p>
<img src="../public/gcp_demo.svg" alt="GCP架构图" width="480" /> <img src="../../public/gcp_demo.svg" alt="GCP架构图" width="480" />
</td> </td>
<td width="50%" valign="top"> <td width="50%" valign="top">
<strong>AWS架构图</strong><br /> <strong>AWS架构图</strong><br />
<p><strong>提示词:</strong> 使用**AWS图标**生成一个AWS架构图。在这个图中用户连接到托管在实例上的前端。</p> <p><strong>提示词:</strong> 使用**AWS图标**生成一个AWS架构图。在这个图中用户连接到托管在实例上的前端。</p>
<img src="../public/aws_demo.svg" alt="AWS架构图" width="480" /> <img src="../../public/aws_demo.svg" alt="AWS架构图" width="480" />
</td> </td>
</tr> </tr>
<tr> <tr>
<td width="50%" valign="top"> <td width="50%" valign="top">
<strong>Azure架构图</strong><br /> <strong>Azure架构图</strong><br />
<p><strong>提示词:</strong> 使用**Azure图标**生成一个Azure架构图。在这个图中用户连接到托管在实例上的前端。</p> <p><strong>提示词:</strong> 使用**Azure图标**生成一个Azure架构图。在这个图中用户连接到托管在实例上的前端。</p>
<img src="../public/azure_demo.svg" alt="Azure架构图" width="480" /> <img src="../../public/azure_demo.svg" alt="Azure架构图" width="480" />
</td> </td>
<td width="50%" valign="top"> <td width="50%" valign="top">
<strong>猫咪素描</strong><br /> <strong>猫咪素描</strong><br />
<p><strong>提示词:</strong> 给我画一只可爱的猫。</p> <p><strong>提示词:</strong> 给我画一只可爱的猫。</p>
<img src="../public/cat_demo.svg" alt="猫咪绘图" width="240" /> <img src="../../public/cat_demo.svg" alt="猫咪绘图" width="240" />
</td> </td>
</tr> </tr>
</table> </table>
@@ -93,7 +97,7 @@ https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
## MCP服务器预览 ## MCP服务器预览
> **预览功能**:此功能为实验性功能,可能会有变化 > **预览功能**:此功能为实验性功能,可能不稳定
通过MCP模型上下文协议在Claude Desktop、Cursor和VS Code等AI代理中使用Next AI Draw.io。 通过MCP模型上下文协议在Claude Desktop、Cursor和VS Code等AI代理中使用Next AI Draw.io。
@@ -119,7 +123,7 @@ claude mcp add drawio -- npx @next-ai-drawio/mcp-server@latest
图表会实时显示在浏览器中! 图表会实时显示在浏览器中!
详情请参阅[MCP服务器README](../packages/mcp-server/README.md)了解VS Code、Cursor等客户端配置。 详情请参阅[MCP服务器README](../../packages/mcp-server/README.md)了解VS Code、Cursor等客户端配置。
## 快速开始 ## 快速开始
@@ -127,39 +131,19 @@ claude mcp add drawio -- npx @next-ai-drawio/mcp-server@latest
无需安装!直接在我们的演示站点试用: 无需安装!直接在我们的演示站点试用:
[![Live Demo](../public/live-demo-button.svg)](https://next-ai-drawio.jiang.jp/) [![Live Demo](../../public/live-demo-button.svg)](https://next-ai-drawio.jiang.jp/)
> **使用自己的 API Key**:您可以使用自己的 API Key 来绕过演示站点的用量限制。点击聊天面板中的设置图标即可配置您的 Provider 和 API Key。您的 Key 仅保存在浏览器本地,不会被存储在服务器上。 > **使用自己的 API Key**:您可以使用自己的 API Key 来绕过演示站点的用量限制。点击聊天面板中的设置图标即可配置您的 Provider 和 API Key。您的 Key 仅保存在浏览器本地,不会被存储在服务器上。
### 使用Docker运行推荐 ### 桌面应用
如果您只想在本地运行最好的方式是使用Docker。 从 [Releases 页面](https://github.com/DayuanJiang/next-ai-draw-io/releases) 下载适用于您平台的原生桌面应用:
首先如果您还没有安装Docker请先安装[获取Docker](https://docs.docker.com/get-docker/) 支持的平台Windows、macOS、Linux。
然后运行 ### 使用Docker运行
```bash [查看 Docker 指南](./docker.md)
docker run -d -p 3000:3000 \
-e AI_PROVIDER=openai \
-e AI_MODEL=gpt-4o \
-e OPENAI_API_KEY=your_api_key \
ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
或者使用 env 文件:
```bash
cp env.example .env
# 编辑 .env 填写您的配置
docker run -d -p 3000:3000 --env-file .env ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
在浏览器中打开 [http://localhost:3000](http://localhost:3000)。
请根据您首选的AI提供商配置替换环境变量。可用选项请参阅[多提供商支持](#多提供商支持)。
> **离线部署:** 如果 `embed.diagrams.net` 被屏蔽,请参阅 [离线部署指南](./offline-deployment.md) 了解配置选项。
### 安装 ### 安装
@@ -168,52 +152,44 @@ docker run -d -p 3000:3000 --env-file .env ghcr.io/dayuanjiang/next-ai-draw-io:l
```bash ```bash
git clone https://github.com/DayuanJiang/next-ai-draw-io git clone https://github.com/DayuanJiang/next-ai-draw-io
cd next-ai-draw-io cd next-ai-draw-io
```
2. 安装依赖:
```bash
npm install npm install
```
3. 配置您的AI提供商
在根目录创建 `.env.local` 文件:
```bash
cp env.example .env.local cp env.example .env.local
``` ```
编辑 `.env.local` 并配置您选择的提供商:
- 将 `AI_PROVIDER` 设置为您选择的提供商bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow, doubao
- 将 `AI_MODEL` 设置为您要使用的特定模型
- 添加您的提供商所需的API密钥
- `TEMPERATURE`:可选的温度设置(例如 `0` 表示确定性输出)。对于不支持此参数的模型(如推理模型),请不要设置。
- `ACCESS_CODE_LIST` 访问密码,可选,可以使用逗号隔开多个密码。
> 警告:如果不填写 `ACCESS_CODE_LIST`,则任何人都可以直接使用你部署后的网站,可能会导致你的 token 被急速消耗完毕,建议填写此选项。
详细设置说明请参阅[提供商配置指南](./ai-providers.md)。 详细设置说明请参阅[提供商配置指南](./ai-providers.md)。
4. 运行开发服务器: 2. 运行开发服务器:
```bash ```bash
npm run dev npm run dev
``` ```
5. 在浏览器中打开 [http://localhost:3000](http://localhost:3000) 查看应用。 3. 在浏览器中打开 [http://localhost:6002](http://localhost:6002) 查看应用。
## 部署 ## 部署
部署Next.js应用最简单的方式是使用Next.js创建者提供的[Vercel平台](https://vercel.com/new)。 ### 部署到腾讯云EdgeOne Pages
您可以通过[腾讯云EdgeOne Pages](https://pages.edgeone.ai/zh)一键部署。
直接点击此按钮一键部署:
[![使用 EdgeOne Pages 部署](https://cdnstatic.tencentcs.com/edgeone/pages/deploy.svg)](https://console.cloud.tencent.com/edgeone/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
查看[腾讯云EdgeOne Pages文档](https://pages.edgeone.ai/zh/document/product-introduction)了解更多详情。
同时通过腾讯云EdgeOne Pages部署也会获得[每日免费的DeepSeek模型额度](https://edgeone.cloud.tencent.com/pages/document/169925463311781888)。
### 部署到Vercel推荐
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
部署Next.js应用最简单的方式是使用Next.js创建者提供的[Vercel平台](https://vercel.com/new)。请确保在Vercel控制台中**设置环境变量**,就像您在本地 `.env.local` 文件中所做的那样。
查看[Next.js部署文档](https://nextjs.org/docs/app/building-your-application/deploying)了解更多详情。 查看[Next.js部署文档](https://nextjs.org/docs/app/building-your-application/deploying)了解更多详情。
或者您可以通过此按钮部署: ### 部署到Cloudflare Workers
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
请确保在Vercel控制台中**设置环境变量**,就像您在本地 `.env.local` 文件中所做的那样。 [查看 Cloudflare 部署指南](./cloudflare-deploy.md)
## 多提供商支持 ## 多提供商支持
@@ -228,14 +204,16 @@ npm run dev
- OpenRouter - OpenRouter
- DeepSeek - DeepSeek
- SiliconFlow - SiliconFlow
- SGLang
- Vercel AI Gateway
除AWS Bedrock和OpenRouter外所有提供商都支持自定义端点。 除AWS Bedrock和OpenRouter外所有提供商都支持自定义端点。
📖 **[详细的提供商配置指南](./ai-providers.md)** - 查看各提供商的设置说明。 📖 **[详细的提供商配置指南](./ai-providers.md)** - 查看各提供商的设置说明。
**模型要求**此任务需要强大的模型能力因为它涉及生成具有严格格式约束的长文本draw.io XML。推荐使用Claude Sonnet 4.5、GPT-4o、Gemini 2.0和DeepSeek V3/R1。 **模型要求**此任务需要强大的模型能力因为它涉及生成具有严格格式约束的长文本draw.io XML。推荐使用 Claude Sonnet 4.5、GPT-5.1、Gemini 3 Pro 和 DeepSeek V3.2/R1。
注意:`claude-sonnet-4-5` 已在带有AWS标志的draw.io图表上进行训练因此如果您想创建AWS架构图,这是最佳选择。 注意:`claude` 系列已在带有 AWS、Azure、GCP 等云架构 Logo 的 draw.io 图表上进行训练,因此如果您想创建架构图,这是最佳选择。
## 工作原理 ## 工作原理
@@ -248,24 +226,6 @@ npm run dev
图表以XML格式表示可在draw.io中渲染。AI处理您的命令并相应地生成或修改此XML。 图表以XML格式表示可在draw.io中渲染。AI处理您的命令并相应地生成或修改此XML。
## 项目结构
```
app/ # Next.js App Router
api/chat/ # 带AI工具的聊天API端点
page.tsx # 带DrawIO嵌入的主页面
components/ # React组件
chat-panel.tsx # 带图表控制的聊天界面
chat-input.tsx # 带文件上传的用户输入组件
history-dialog.tsx # 图表版本历史查看器
ui/ # UI组件按钮、卡片等
contexts/ # React上下文提供者
diagram-context.tsx # 全局图表状态管理
lib/ # 工具函数和辅助程序
ai-providers.ts # 多提供商AI配置
utils.ts # XML处理和转换工具
public/ # 静态资源包括示例图片
```
## 支持与联系 ## 支持与联系

236
docs/cn/ai-providers.md Normal file
View File

@@ -0,0 +1,236 @@
# AI 提供商配置
本指南介绍如何为 next-ai-draw-io 配置不同的 AI 模型提供商。
## 快速开始
1.`.env.example` 复制为 `.env.local`
2. 设置所选提供商的 API 密钥
3.`AI_MODEL` 设置为所需的模型
4. 运行 `npm run dev`
## 支持的提供商
### 豆包 (字节跳动火山引擎)
> **免费 Token**:在 [火山引擎 ARK 平台](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project) 注册,即可获得所有模型 50 万免费 Token
```bash
DOUBAO_API_KEY=your_api_key
AI_MODEL=doubao-seed-1-8-251215 # 或其他豆包模型
```
### Google Gemini
```bash
GOOGLE_GENERATIVE_AI_API_KEY=your_api_key
AI_MODEL=gemini-2.0-flash
```
可选的自定义端点:
```bash
GOOGLE_BASE_URL=https://your-custom-endpoint
```
### OpenAI
```bash
OPENAI_API_KEY=your_api_key
AI_MODEL=gpt-4o
```
可选的自定义端点(用于 OpenAI 兼容服务):
```bash
OPENAI_BASE_URL=https://your-custom-endpoint/v1
```
### Anthropic
```bash
ANTHROPIC_API_KEY=your_api_key
AI_MODEL=claude-sonnet-4-5-20250514
```
可选的自定义端点:
```bash
ANTHROPIC_BASE_URL=https://your-custom-endpoint
```
### DeepSeek
```bash
DEEPSEEK_API_KEY=your_api_key
AI_MODEL=deepseek-chat
```
可选的自定义端点:
```bash
DEEPSEEK_BASE_URL=https://your-custom-endpoint
```
### SiliconFlow (OpenAI 兼容)
```bash
SILICONFLOW_API_KEY=your_api_key
AI_MODEL=deepseek-ai/DeepSeek-V3 # 示例;使用任何 SiliconFlow 模型 ID
```
可选的自定义端点(默认为推荐域名):
```bash
SILICONFLOW_BASE_URL=https://api.siliconflow.com/v1 # 或 https://api.siliconflow.cn/v1
```
### SGLang
```bash
SGLANG_API_KEY=your_api_key
AI_MODEL=your_model_id
```
可选的自定义端点:
```bash
SGLANG_BASE_URL=https://your-custom-endpoint/v1
```
### Azure OpenAI
```bash
AZURE_API_KEY=your_api_key
AZURE_RESOURCE_NAME=your-resource-name # 必填:您的 Azure 资源名称
AI_MODEL=your-deployment-name
```
或者使用自定义端点代替资源名称:
```bash
AZURE_API_KEY=your_api_key
AZURE_BASE_URL=https://your-resource.openai.azure.com # AZURE_RESOURCE_NAME 的替代方案
AI_MODEL=your-deployment-name
```
可选的推理配置:
```bash
AZURE_REASONING_EFFORT=low # 可选low, medium, high
AZURE_REASONING_SUMMARY=detailed # 可选none, brief, detailed
```
### AWS Bedrock
```bash
AWS_REGION=us-west-2
AWS_ACCESS_KEY_ID=your_access_key_id
AWS_SECRET_ACCESS_KEY=your_secret_access_key
AI_MODEL=anthropic.claude-sonnet-4-5-20250514-v1:0
```
注意:在 AWS 环境Lambda、带有 IAM 角色的 EC2凭证会自动从 IAM 角色获取。
### OpenRouter
```bash
OPENROUTER_API_KEY=your_api_key
AI_MODEL=anthropic/claude-sonnet-4
```
可选的自定义端点:
```bash
OPENROUTER_BASE_URL=https://your-custom-endpoint
```
### Ollama (本地)
```bash
AI_PROVIDER=ollama
AI_MODEL=llama3.2
```
可选的自定义 URL
```bash
OLLAMA_BASE_URL=http://localhost:11434
```
### Vercel AI Gateway
Vercel AI Gateway 通过单个 API 密钥提供对多个 AI 提供商的统一访问。这简化了身份验证,让您无需管理多个 API 密钥即可在不同提供商之间切换。
**基本用法Vercel 托管网关):**
```bash
AI_GATEWAY_API_KEY=your_gateway_api_key
AI_MODEL=openai/gpt-4o
```
**自定义网关 URL用于本地开发或自托管网关**
```bash
AI_GATEWAY_API_KEY=your_custom_api_key
AI_GATEWAY_BASE_URL=https://your-custom-gateway.com/v1/ai
AI_MODEL=openai/gpt-4o
```
模型格式使用 `provider/model` 语法:
- `openai/gpt-4o` - OpenAI GPT-4o
- `anthropic/claude-sonnet-4-5` - Anthropic Claude Sonnet 4.5
- `google/gemini-2.0-flash` - Google Gemini 2.0 Flash
**配置说明:**
- 如果未设置 `AI_GATEWAY_BASE_URL`,则使用默认的 Vercel Gateway URL (`https://ai-gateway.vercel.sh/v1/ai`)
- 自定义基础 URL 适用于:
- 使用自定义网关实例进行本地开发
- 自托管 AI Gateway 部署
- 企业代理配置
- 当使用自定义基础 URL 时,必须同时提供 `AI_GATEWAY_API_KEY`
从 [Vercel AI Gateway 仪表板](https://vercel.com/ai-gateway) 获取您的 API 密钥。
## 自动检测
如果您只配置了**一个**提供商的 API 密钥,系统将自动检测并使用该提供商。无需设置 `AI_PROVIDER`
如果您配置了**多个** API 密钥,则必须显式设置 `AI_PROVIDER`
```bash
AI_PROVIDER=google # 或openai, anthropic, deepseek, siliconflow, doubao, azure, bedrock, openrouter, ollama, gateway, sglang
```
## 模型能力要求
此任务对模型能力要求极高因为它涉及生成具有严格格式约束draw.io XML的长文本。
**推荐模型**
- Claude Sonnet 4.5 / Opus 4.5
**关于 Ollama 的说明**:虽然支持将 Ollama 作为提供商,但除非您在本地运行像 DeepSeek R1 或 Qwen3-235B 这样的高性能模型,否则对于此用例通常不太实用。
## 温度设置 (Temperature)
您可以通过环境变量选择性地配置温度:
```bash
TEMPERATURE=0 # 输出更具确定性(推荐用于图表)
```
**重要提示**:对于不支持温度设置的模型(例如以下模型),请勿设置 `TEMPERATURE`
- GPT-5.1 和其他推理模型
- 某些专用模型
未设置时,模型将使用其默认行为。
## 推荐
- **最佳体验**使用支持视觉的模型GPT-4o, Claude, Gemini以获得图像转图表功能
- **经济实惠**DeepSeek 提供具有竞争力的价格
- **隐私保护**:使用 Ollama 进行完全本地、离线的操作(需要强大的硬件支持)
- **灵活性**OpenRouter 通过单一 API 提供对众多模型的访问

View File

@@ -0,0 +1,267 @@
# 部署到 Cloudflare Workers
本项目可以通过 **OpenNext 适配器** 部署为 **Cloudflare Worker**,为您提供:
- 全球边缘部署
- 极低延迟
- 免费的 `workers.dev` 域名托管
- 通过 R2 实现完整的 Next.js ISR 支持(可选)
> **Windows 用户重要提示:** OpenNext 和 Wrangler 在 **原生 Windows 环境下并不完全可靠**。建议方案:
>
> - 使用 **GitHub Codespaces**(完美运行)
> - 或者使用 **WSL (Linux)**
>
> 纯 Windows 构建可能会因为 WASM 文件路径问题而失败。
---
## 前置条件
1. 一个 **Cloudflare 账户**(免费版即可满足基本部署需求)
2. **Node.js 18+**
3. 安装 **Wrangler CLI**(作为开发依赖安装即可):
```bash
npm install -D wrangler
```
4. 登录 Cloudflare
```bash
npx wrangler login
```
> **注意:** 只有在启用 R2 进行 ISR 缓存时才需要绑定支付方式。基本的 Workers 部署是免费的。
---
## 第一步 — 安装依赖
```bash
npm install
```
---
## 第二步 — 配置环境变量
Cloudflare 在本地测试时使用不同的文件。
### 1) 创建 `.dev.vars`(用于 Cloudflare 本地调试 + 部署)
```bash
cp env.example .dev.vars
```
填入您的 API 密钥和配置信息。
### 2) 确保 `.env.local` 也存在(用于常规 Next.js 开发)
```bash
cp env.example .env.local
```
在此处填入相同的值。
---
## 第三步 — 选择部署类型
### 选项 A不使用 R2 部署(简单,免费)
如果您不需要 ISR 缓存,可以选择不使用 R2 进行部署:
**1. 使用简单的 `open-next.config.ts`**
```ts
import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"
export default defineCloudflareConfig({})
```
**2. 使用简单的 `wrangler.jsonc`(不包含 r2_buckets**
```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"main": ".open-next/worker.js",
"name": "next-ai-draw-io-worker",
"compatibility_date": "2025-12-08",
"compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
"assets": {
"directory": ".open-next/assets",
"binding": "ASSETS"
},
"services": [
{
"binding": "WORKER_SELF_REFERENCE",
"service": "next-ai-draw-io-worker"
}
]
}
```
直接跳至 **第四步**
---
### 选项 B使用 R2 部署(完整的 ISR 支持)
R2 开启了 **增量静态再生 (ISR)** 缓存功能。需要在您的 Cloudflare 账户中绑定支付方式。
**1. 在 Cloudflare 控制台中创建 R2 存储桶:**
- 进入 **Storage & Databases → R2**
- 点击 **Create bucket**
- 命名为:`next-inc-cache`
**2. 配置 `open-next.config.ts`**
```ts
import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"
import r2IncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/r2-incremental-cache"
export default defineCloudflareConfig({
incrementalCache: r2IncrementalCache,
})
```
**3. 配置 `wrangler.jsonc`(包含 R2**
```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"main": ".open-next/worker.js",
"name": "next-ai-draw-io-worker",
"compatibility_date": "2025-12-08",
"compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
"assets": {
"directory": ".open-next/assets",
"binding": "ASSETS"
},
"r2_buckets": [
{
"binding": "NEXT_INC_CACHE_R2_BUCKET",
"bucket_name": "next-inc-cache"
}
],
"services": [
{
"binding": "WORKER_SELF_REFERENCE",
"service": "next-ai-draw-io-worker"
}
]
}
```
> **重要提示:** `bucket_name` 必须与您在 Cloudflare 控制台中创建的名称完全一致。
---
## 第四步 — 注册 workers.dev 子域名(仅首次需要)
在首次部署之前,您需要一个 workers.dev 子域名。
**选项 1通过 Cloudflare 控制台(推荐)**
访问https://dash.cloudflare.com → Workers & Pages → Overview → Set up a subdomain
**选项 2在部署过程中**
运行 `npm run deploy`Wrangler 可能会提示:
```
Would you like to register a workers.dev subdomain? (Y/n)
```
输入 `Y` 并选择一个子域名。
> **注意:** 在 CI/CD 或非交互式环境中,该提示不会出现。请先通过控制台进行注册。
---
## 第五步 — 部署到 Cloudflare
```bash
npm run deploy
```
该脚本执行的操作:
- 构建 Next.js 应用
- 通过 OpenNext 将其转换为 Cloudflare Worker
- 上传静态资源
- 发布 Worker
您的应用将可通过以下地址访问:
```
https://<worker-name>.<your-subdomain>.workers.dev
```
---
## 常见问题与修复
### `You need to register a workers.dev subdomain`
**原因:** 您的账户尚未注册 workers.dev 子域名。
**修复:** 前往 https://dash.cloudflare.com → Workers & Pages → Set up a subdomain。
---
### `Please enable R2 through the Cloudflare Dashboard`
**原因:** wrangler.jsonc 中配置了 R2但您的账户尚未启用该功能。
**修复:** 启用 R2需要支付方式或使用选项 A不使用 R2 部署)。
---
### `No R2 binding "NEXT_INC_CACHE_R2_BUCKET" found`
**原因:** `wrangler.jsonc` 中缺少 `r2_buckets` 配置。
**修复:** 添加 `r2_buckets` 部分或切换到选项 A不使用 R2
---
### `Can't set compatibility date in the future`
**原因:** wrangler 配置中的 `compatibility_date` 设置为了未来的日期。
**修复:**`compatibility_date` 修改为今天或更早的日期。
---
### Windows 错误:`resvg.wasm?module` (ENOENT)
**原因:** Windows 文件名不能包含 `?`,但某个 wasm 资源文件名中使用了 `?module`
**修复:** 在 Linux 环境WSL、Codespaces 或 CI上进行构建/部署。
---
## 可选:本地预览
部署前在本地预览 Worker
```bash
npm run preview
```
---
## 总结
| 功能 | 不使用 R2 | 使用 R2 |
|---------|------------|---------|
| 成本 | 免费 | 需要绑定支付方式 |
| ISR 缓存 | 无 | 有 |
| 静态页面 | 支持 | 支持 |
| API 路由 | 支持 | 支持 |
| 配置复杂度 | 简单 | 中等 |
测试或简单应用请选择 **不使用 R2**。需要 ISR 缓存的生产环境应用请选择 **使用 R2**

29
docs/cn/docker.md Normal file
View File

@@ -0,0 +1,29 @@
# 使用 Docker 运行
如果您只是想在本地运行,最好的方式是使用 Docker。
首先,如果您尚未安装 Docker请先安装[获取 Docker](https://docs.docker.com/get-docker/)
然后运行:
```bash
docker run -d -p 3000:3000 \
-e AI_PROVIDER=openai \
-e AI_MODEL=gpt-4o \
-e OPENAI_API_KEY=your_api_key \
ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
或者使用环境变量文件:
```bash
cp env.example .env
# 编辑 .env 文件并填入您的配置
docker run -d -p 3000:3000 --env-file .env ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
在浏览器中打开 [http://localhost:3000](http://localhost:3000)。
请将环境变量替换为您首选的 AI 提供商配置。查看 [AI 提供商](./ai-providers.md) 了解可用选项。
> **离线部署:** 如果无法访问 `embed.diagrams.net`,请参阅 [离线部署](./offline-deployment.md) 了解配置选项。

View File

@@ -0,0 +1,38 @@
# 离线部署
通过自托管 draw.io 来替代 `embed.diagrams.net`,从而离线部署 Next AI Draw.io。
**注意:** `NEXT_PUBLIC_DRAWIO_BASE_URL` 是一个**构建时**变量。修改它需要重新构建 Docker 镜像。
## Docker Compose 设置
1. 克隆仓库并在 `.env` 文件中定义 API 密钥。
2. 创建 `docker-compose.yml`
```yaml
services:
drawio:
image: jgraph/drawio:latest
ports: ["8080:8080"]
next-ai-draw-io:
build:
context: .
args:
- NEXT_PUBLIC_DRAWIO_BASE_URL=http://localhost:8080
ports: ["3000:3000"]
env_file: .env
depends_on: [drawio]
```
3. 运行 `docker compose up -d` 并打开 `http://localhost:3000`
## 配置与重要警告
**`NEXT_PUBLIC_DRAWIO_BASE_URL` 必须是用户浏览器可访问的地址。**
| 场景 | URL 值 |
|----------|-----------|
| 本地主机 (Localhost) | `http://localhost:8080` |
| 远程/服务器 | `http://YOUR_SERVER_IP:8080` |
**切勿使用** Docker 内部别名(如 `http://drawio:8080`),因为浏览器无法解析它们。

View File

@@ -85,7 +85,18 @@ Optional custom endpoint (defaults to the recommended domain):
SILICONFLOW_BASE_URL=https://api.siliconflow.com/v1 # or https://api.siliconflow.cn/v1 SILICONFLOW_BASE_URL=https://api.siliconflow.com/v1 # or https://api.siliconflow.cn/v1
``` ```
### SGLang
```bash
SGLANG_API_KEY=your_api_key
AI_MODEL=your_model_id
```
Optional custom endpoint:
```bash
SGLANG_BASE_URL=https://your-custom-endpoint/v1
```
### Azure OpenAI ### Azure OpenAI
@@ -190,7 +201,7 @@ If you only configure **one** provider's API key, the system will automatically
If you configure **multiple** API keys, you must explicitly set `AI_PROVIDER`: If you configure **multiple** API keys, you must explicitly set `AI_PROVIDER`:
```bash ```bash
AI_PROVIDER=google # or: openai, anthropic, deepseek, siliconflow, doubao, azure, bedrock, openrouter, ollama, gateway AI_PROVIDER=google # or: openai, anthropic, deepseek, siliconflow, doubao, azure, bedrock, openrouter, ollama, gateway, sglang
``` ```
## Model Capability Requirements ## Model Capability Requirements

29
docs/en/docker.md Normal file
View File

@@ -0,0 +1,29 @@
# Run with Docker
If you just want to run it locally, the best way is to use Docker.
First, install Docker if you haven't already: [Get Docker](https://docs.docker.com/get-docker/)
Then run:
```bash
docker run -d -p 3000:3000 \
-e AI_PROVIDER=openai \
-e AI_MODEL=gpt-4o \
-e OPENAI_API_KEY=your_api_key \
ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
Or use an env file:
```bash
cp env.example .env
# Edit .env with your configuration
docker run -d -p 3000:3000 --env-file .env ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
Open [http://localhost:3000](http://localhost:3000) in your browser.
Replace the environment variables with your preferred AI provider configuration. See [AI Providers](./ai-providers.md) for available options.
> **Offline Deployment:** If `embed.diagrams.net` is blocked, see [Offline Deployment](./offline-deployment.md) for configuration options.

View File

@@ -4,7 +4,7 @@
**AI搭載のダイアグラム作成ツール - チャット、描画、可視化** **AI搭載のダイアグラム作成ツール - チャット、描画、可視化**
[English](../README.md) | [中文](./README_CN.md) | 日本語 [English](../../README.md) | [中文](../cn/README_CN.md) | 日本語
[![TrendShift](https://trendshift.io/api/badge/repositories/15449)](https://next-ai-drawio.jiang.jp/) [![TrendShift](https://trendshift.io/api/badge/repositories/15449)](https://next-ai-drawio.jiang.jp/)
@@ -13,7 +13,7 @@
[![React](https://img.shields.io/badge/React-19.x-61dafb)](https://react.dev/) [![React](https://img.shields.io/badge/React-19.x-61dafb)](https://react.dev/)
[![Sponsor](https://img.shields.io/badge/Sponsor-❤-ea4aaa)](https://github.com/sponsors/DayuanJiang) [![Sponsor](https://img.shields.io/badge/Sponsor-❤-ea4aaa)](https://github.com/sponsors/DayuanJiang)
[![Live Demo](../public/live-demo-button.svg)](https://next-ai-drawio.jiang.jp/) [![Live Demo](../../public/live-demo-button.svg)](https://next-ai-drawio.jiang.jp/)
</div> </div>
@@ -29,14 +29,18 @@ https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
- [](#例) - [](#例)
- [機能](#機能) - [機能](#機能)
- [MCPサーバープレビュー](#mcpサーバープレビュー) - [MCPサーバープレビュー](#mcpサーバープレビュー)
- [Claude Code CLI](#claude-code-cli)
- [はじめに](#はじめに) - [はじめに](#はじめに)
- [オンラインで試す](#オンラインで試す) - [オンラインで試す](#オンラインで試す)
- [Dockerで実行推奨](#dockerで実行推奨) - [デスクトップアプリケーション](#デスクトップアプリケーション)
- [Dockerで実行](#dockerで実行)
- [インストール](#インストール) - [インストール](#インストール)
- [デプロイ](#デプロイ) - [デプロイ](#デプロイ)
- [EdgeOne Pagesへのデプロイ](#edgeone-pagesへのデプロイ)
- [Vercelへのデプロイ推奨](#vercelへのデプロイ推奨)
- [Cloudflare Workersへのデプロイ](#cloudflare-workersへのデプロイ)
- [マルチプロバイダーサポート](#マルチプロバイダーサポート) - [マルチプロバイダーサポート](#マルチプロバイダーサポート)
- [仕組み](#仕組み) - [仕組み](#仕組み)
- [プロジェクト構造](#プロジェクト構造)
- [サポート&お問い合わせ](#サポートお問い合わせ) - [サポート&お問い合わせ](#サポートお問い合わせ)
- [スター履歴](#スター履歴) - [スター履歴](#スター履歴)
@@ -50,31 +54,31 @@ https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
<td colspan="2" valign="top" align="center"> <td colspan="2" valign="top" align="center">
<strong>アニメーションTransformerコネクタ</strong><br /> <strong>アニメーションTransformerコネクタ</strong><br />
<p><strong>プロンプト:</strong> **アニメーションコネクタ**付きのTransformerアーキテクチャ図を作成してください。</p> <p><strong>プロンプト:</strong> **アニメーションコネクタ**付きのTransformerアーキテクチャ図を作成してください。</p>
<img src="../public/animated_connectors.svg" alt="アニメーションコネクタ付きTransformerアーキテクチャ" width="480" /> <img src="../../public/animated_connectors.svg" alt="アニメーションコネクタ付きTransformerアーキテクチャ" width="480" />
</td> </td>
</tr> </tr>
<tr> <tr>
<td width="50%" valign="top"> <td width="50%" valign="top">
<strong>GCPアーキテクチャ図</strong><br /> <strong>GCPアーキテクチャ図</strong><br />
<p><strong>プロンプト:</strong> **GCPアイコン**を使用してGCPアーキテクチャ図を生成してください。この図では、ユーザーがインスタンス上でホストされているフロントエンドに接続します。</p> <p><strong>プロンプト:</strong> **GCPアイコン**を使用してGCPアーキテクチャ図を生成してください。この図では、ユーザーがインスタンス上でホストされているフロントエンドに接続します。</p>
<img src="../public/gcp_demo.svg" alt="GCPアーキテクチャ図" width="480" /> <img src="../../public/gcp_demo.svg" alt="GCPアーキテクチャ図" width="480" />
</td> </td>
<td width="50%" valign="top"> <td width="50%" valign="top">
<strong>AWSアーキテクチャ図</strong><br /> <strong>AWSアーキテクチャ図</strong><br />
<p><strong>プロンプト:</strong> **AWSアイコン**を使用してAWSアーキテクチャ図を生成してください。この図では、ユーザーがインスタンス上でホストされているフロントエンドに接続します。</p> <p><strong>プロンプト:</strong> **AWSアイコン**を使用してAWSアーキテクチャ図を生成してください。この図では、ユーザーがインスタンス上でホストされているフロントエンドに接続します。</p>
<img src="../public/aws_demo.svg" alt="AWSアーキテクチャ図" width="480" /> <img src="../../public/aws_demo.svg" alt="AWSアーキテクチャ図" width="480" />
</td> </td>
</tr> </tr>
<tr> <tr>
<td width="50%" valign="top"> <td width="50%" valign="top">
<strong>Azureアーキテクチャ図</strong><br /> <strong>Azureアーキテクチャ図</strong><br />
<p><strong>プロンプト:</strong> **Azureアイコン**を使用してAzureアーキテクチャ図を生成してください。この図では、ユーザーがインスタンス上でホストされているフロントエンドに接続します。</p> <p><strong>プロンプト:</strong> **Azureアイコン**を使用してAzureアーキテクチャ図を生成してください。この図では、ユーザーがインスタンス上でホストされているフロントエンドに接続します。</p>
<img src="../public/azure_demo.svg" alt="Azureアーキテクチャ図" width="480" /> <img src="../../public/azure_demo.svg" alt="Azureアーキテクチャ図" width="480" />
</td> </td>
<td width="50%" valign="top"> <td width="50%" valign="top">
<strong>猫のスケッチ</strong><br /> <strong>猫のスケッチ</strong><br />
<p><strong>プロンプト:</strong> かわいい猫を描いてください。</p> <p><strong>プロンプト:</strong> かわいい猫を描いてください。</p>
<img src="../public/cat_demo.svg" alt="猫の絵" width="240" /> <img src="../../public/cat_demo.svg" alt="猫の絵" width="240" />
</td> </td>
</tr> </tr>
</table> </table>
@@ -93,7 +97,7 @@ https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
## MCPサーバープレビュー ## MCPサーバープレビュー
> **プレビュー機能**:この機能は実験的であり、変更される可能性があります。 > **プレビュー機能**:この機能は実験的であり、安定しない可能性があります。
MCPModel Context Protocolを介して、Claude Desktop、Cursor、VS CodeなどのAIエージェントでNext AI Draw.ioを使用できます。 MCPModel Context Protocolを介して、Claude Desktop、Cursor、VS CodeなどのAIエージェントでNext AI Draw.ioを使用できます。
@@ -119,7 +123,7 @@ Claudeにダイアグラムの作成を依頼
ダイアグラムがリアルタイムでブラウザに表示されます! ダイアグラムがリアルタイムでブラウザに表示されます!
詳細は[MCPサーバーREADME](../packages/mcp-server/README.md)をご覧くださいVS Code、Cursorなどのクライアント設定も含む 詳細は[MCPサーバーREADME](../../packages/mcp-server/README.md)をご覧くださいVS Code、Cursorなどのクライアント設定も含む
## はじめに ## はじめに
@@ -127,39 +131,19 @@ Claudeにダイアグラムの作成を依頼
インストール不要!デモサイトで直接お試しください: インストール不要!デモサイトで直接お試しください:
[![Live Demo](../public/live-demo-button.svg)](https://next-ai-drawio.jiang.jp/) [![Live Demo](../../public/live-demo-button.svg)](https://next-ai-drawio.jiang.jp/)
> **自分のAPIキーを使用**自分のAPIキーを使用することで、デモサイトの利用制限を回避できます。チャットパネルの設定アイコンをクリックして、プロバイダーとAPIキーを設定してください。キーはブラウザのローカルに保存され、サーバーには保存されません。 > **自分のAPIキーを使用**自分のAPIキーを使用することで、デモサイトの利用制限を回避できます。チャットパネルの設定アイコンをクリックして、プロバイダーとAPIキーを設定してください。キーはブラウザのローカルに保存され、サーバーには保存されません。
### Dockerで実行推奨 ### デスクトップアプリケーション
ローカルで実行したいだけなら、Dockerを使用するのが最も簡単です。 [Releases ページ](https://github.com/DayuanJiang/next-ai-draw-io/releases)からお使いのプラットフォーム用のネイティブデスクトップアプリをダウンロードしてください:
まず、Dockerをインストールしていない場合はインストールしてください[Dockerを入手](https://docs.docker.com/get-docker/) 対応プラットフォームWindows、macOS、Linux。
次に実行 ### Dockerで実行
```bash [Docker ガイドを参照](./docker.md)
docker run -d -p 3000:3000 \
-e AI_PROVIDER=openai \
-e AI_MODEL=gpt-4o \
-e OPENAI_API_KEY=your_api_key \
ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
または env ファイルを使用:
```bash
cp env.example .env
# .env を編集して設定を入力
docker run -d -p 3000:3000 --env-file .env ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
ブラウザで [http://localhost:3000](http://localhost:3000) を開いてください。
環境変数はお好みのAIプロバイダー設定に置き換えてください。利用可能なオプションについては[マルチプロバイダーサポート](#マルチプロバイダーサポート)を参照してください。
> **オフラインデプロイ:** `embed.diagrams.net` がブロックされている場合は、[オフラインデプロイガイド](./offline-deployment.md) で設定オプションをご確認ください。
### インストール ### インストール
@@ -168,52 +152,45 @@ docker run -d -p 3000:3000 --env-file .env ghcr.io/dayuanjiang/next-ai-draw-io:l
```bash ```bash
git clone https://github.com/DayuanJiang/next-ai-draw-io git clone https://github.com/DayuanJiang/next-ai-draw-io
cd next-ai-draw-io cd next-ai-draw-io
```
2. 依存関係をインストール:
```bash
npm install npm install
```
3. AIプロバイダーを設定
ルートディレクトリに`.env.local`ファイルを作成:
```bash
cp env.example .env.local cp env.example .env.local
``` ```
`.env.local`を編集して選択したプロバイダーを設定:
- `AI_PROVIDER`を選択したプロバイダーに設定bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow, doubao
- `AI_MODEL`を使用する特定のモデルに設定
- プロバイダーに必要なAPIキーを追加
- `TEMPERATURE`:オプションの温度設定(例:`0`で決定論的な出力)。温度をサポートしないモデル(推論モデルなど)では設定しないでください。
- `ACCESS_CODE_LIST` アクセスパスワード(オプション)。カンマ区切りで複数のパスワードを指定できます。
> 警告:`ACCESS_CODE_LIST`を設定しない場合、誰でもデプロイされたサイトに直接アクセスできるため、トークンが急速に消費される可能性があります。このオプションを設定することをお勧めします。
詳細な設定手順については[プロバイダー設定ガイド](./ai-providers.md)を参照してください。 詳細な設定手順については[プロバイダー設定ガイド](./ai-providers.md)を参照してください。
4. 開発サーバーを起動: 2. 開発サーバーを起動:
```bash ```bash
npm run dev npm run dev
``` ```
5. ブラウザで[http://localhost:3000](http://localhost:3000)を開いてアプリケーションを確認。 3. ブラウザで[http://localhost:6002](http://localhost:6002)を開いてアプリケーションを確認。
## デプロイ ## デプロイ
Next.jsアプリをデプロイする最も簡単な方法は、Next.jsの作成者による[Vercelプラットフォーム](https://vercel.com/new)を使用することです。 ### EdgeOne Pagesへのデプロイ
[Tencent EdgeOne Pages](https://pages.edgeone.ai/)を使用してワンクリックでデプロイできます。
このボタンでデプロイ:
[![Deploy to EdgeOne Pages](https://cdnstatic.tencentcs.com/edgeone/pages/deploy.svg)](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
詳細は[Tencent EdgeOne Pagesドキュメント](https://pages.edgeone.ai/document/deployment-overview)をご覧ください。
また、Tencent EdgeOne Pagesでデプロイすると、[DeepSeekモデルの毎日の無料クォータ](https://pages.edgeone.ai/document/edge-ai)が付与されます。
### Vercelへのデプロイ推奨
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
Next.jsアプリをデプロイする最も簡単な方法は、Next.jsの作成者による[Vercelプラットフォーム](https://vercel.com/new)を使用することです。ローカルの`.env.local`ファイルと同様に、Vercelダッシュボードで**環境変数を設定**してください。
詳細は[Next.jsデプロイメントドキュメント](https://nextjs.org/docs/app/building-your-application/deploying)をご覧ください。 詳細は[Next.jsデプロイメントドキュメント](https://nextjs.org/docs/app/building-your-application/deploying)をご覧ください。
または、このボタンでデプロイできます: ### Cloudflare Workersへのデプロイ
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
ローカルの`.env.local`ファイルと同様に、Vercelダッシュボードで**環境変数を設定**してください。 [Cloudflare デプロイガイドを参照](./cloudflare-deploy.md)
## マルチプロバイダーサポート ## マルチプロバイダーサポート
@@ -228,14 +205,16 @@ Next.jsアプリをデプロイする最も簡単な方法は、Next.jsの作成
- OpenRouter - OpenRouter
- DeepSeek - DeepSeek
- SiliconFlow - SiliconFlow
- SGLang
- Vercel AI Gateway
AWS BedrockとOpenRouter以外のすべてのプロバイダーはカスタムエンドポイントをサポートしています。 AWS BedrockとOpenRouter以外のすべてのプロバイダーはカスタムエンドポイントをサポートしています。
📖 **[詳細なプロバイダー設定ガイド](./ai-providers.md)** - 各プロバイダーの設定手順をご覧ください。 📖 **[詳細なプロバイダー設定ガイド](./ai-providers.md)** - 各プロバイダーの設定手順をご覧ください。
**モデル要件**このタスクは厳密なフォーマット制約draw.io XMLを持つ長文テキスト生成を伴うため、強力なモデル機能が必要です。Claude Sonnet 4.5、GPT-4o、Gemini 2.0、DeepSeek V3/R1を推奨します。 **モデル要件**このタスクは厳密なフォーマット制約draw.io XMLを持つ長文テキスト生成を伴うため、強力なモデル機能が必要です。Claude Sonnet 4.5、GPT-5.1、Gemini 3 Pro、DeepSeek V3.2/R1を推奨します。
注:`claude-sonnet-4-5`はAWSロゴ付きのdraw.ioダイアグラムで学習されているため、AWSアーキテクチャダイアグラムを作成したい場合は最適な選択です。 注:`claude`シリーズはAWS、Azure、GCPなどのクラウドアーキテクチャロゴ付きのdraw.ioダイアグラムで学習されているため、クラウドアーキテクチャダイアグラムを作成したい場合は最適な選択です。
## 仕組み ## 仕組み
@@ -248,24 +227,6 @@ AWS BedrockとOpenRouter以外のすべてのプロバイダーはカスタム
ダイアグラムはdraw.ioでレンダリングできるXMLとして表現されます。AIがコマンドを処理し、それに応じてこのXMLを生成または変更します。 ダイアグラムはdraw.ioでレンダリングできるXMLとして表現されます。AIがコマンドを処理し、それに応じてこのXMLを生成または変更します。
## プロジェクト構造
```
app/ # Next.js App Router
api/chat/ # AIツール付きチャットAPIエンドポイント
page.tsx # DrawIO埋め込み付きメインページ
components/ # Reactコンポーネント
chat-panel.tsx # ダイアグラム制御付きチャットインターフェース
chat-input.tsx # ファイルアップロード付きユーザー入力コンポーネント
history-dialog.tsx # ダイアグラムバージョン履歴ビューア
ui/ # UIコンポーネントボタン、カードなど
contexts/ # Reactコンテキストプロバイダー
diagram-context.tsx # グローバルダイアグラム状態管理
lib/ # ユーティリティ関数とヘルパー
ai-providers.ts # マルチプロバイダーAI設定
utils.ts # XML処理と変換ユーティリティ
public/ # サンプル画像を含む静的アセット
```
## サポート&お問い合わせ ## サポート&お問い合わせ

236
docs/ja/ai-providers.md Normal file
View File

@@ -0,0 +1,236 @@
# AIプロバイダーの設定
このガイドでは、next-ai-draw-io でさまざまな AI モデルプロバイダーを設定する方法について説明します。
## クイックスタート
1. `.env.example``.env.local` にコピーします
2. 選択したプロバイダーの API キーを設定します
3. `AI_MODEL` を希望のモデルに設定します
4. `npm run dev` を実行します
## 対応プロバイダー
### Doubao (ByteDance Volcengine)
> **無料トークン**: [Volcengine ARK プラットフォーム](https://console.volcengine.com/ark/region:ark+cn-beijing/overview?briefPage=0&briefType=introduce&type=new&utm_campaign=doubao&utm_content=aidrawio&utm_medium=github&utm_source=coopensrc&utm_term=project)に登録すると、すべてのモデルで使える50万トークンが無料で入手できます
```bash
DOUBAO_API_KEY=your_api_key
AI_MODEL=doubao-seed-1-8-251215 # または他の Doubao モデル
```
### Google Gemini
```bash
GOOGLE_GENERATIVE_AI_API_KEY=your_api_key
AI_MODEL=gemini-2.0-flash
```
任意のカスタムエンドポイント:
```bash
GOOGLE_BASE_URL=https://your-custom-endpoint
```
### OpenAI
```bash
OPENAI_API_KEY=your_api_key
AI_MODEL=gpt-4o
```
任意のカスタムエンドポイントOpenAI 互換サービス用):
```bash
OPENAI_BASE_URL=https://your-custom-endpoint/v1
```
### Anthropic
```bash
ANTHROPIC_API_KEY=your_api_key
AI_MODEL=claude-sonnet-4-5-20250514
```
任意のカスタムエンドポイント:
```bash
ANTHROPIC_BASE_URL=https://your-custom-endpoint
```
### DeepSeek
```bash
DEEPSEEK_API_KEY=your_api_key
AI_MODEL=deepseek-chat
```
任意のカスタムエンドポイント:
```bash
DEEPSEEK_BASE_URL=https://your-custom-endpoint
```
### SiliconFlow (OpenAI 互換)
```bash
SILICONFLOW_API_KEY=your_api_key
AI_MODEL=deepseek-ai/DeepSeek-V3 # 例; 任意の SiliconFlow モデル ID を使用
```
任意のカスタムエンドポイント(デフォルトは推奨ドメイン):
```bash
SILICONFLOW_BASE_URL=https://api.siliconflow.com/v1 # または https://api.siliconflow.cn/v1
```
### SGLang
```bash
SGLANG_API_KEY=your_api_key
AI_MODEL=your_model_id
```
任意のカスタムエンドポイント:
```bash
SGLANG_BASE_URL=https://your-custom-endpoint/v1
```
### Azure OpenAI
```bash
AZURE_API_KEY=your_api_key
AZURE_RESOURCE_NAME=your-resource-name # 必須: Azure リソース名
AI_MODEL=your-deployment-name
```
またはリソース名の代わりにカスタムエンドポイントを使用:
```bash
AZURE_API_KEY=your_api_key
AZURE_BASE_URL=https://your-resource.openai.azure.com # AZURE_RESOURCE_NAME の代替
AI_MODEL=your-deployment-name
```
任意の推論設定:
```bash
AZURE_REASONING_EFFORT=low # 任意: low, medium, high
AZURE_REASONING_SUMMARY=detailed # 任意: none, brief, detailed
```
### AWS Bedrock
```bash
AWS_REGION=us-west-2
AWS_ACCESS_KEY_ID=your_access_key_id
AWS_SECRET_ACCESS_KEY=your_secret_access_key
AI_MODEL=anthropic.claude-sonnet-4-5-20250514-v1:0
```
注: AWS 上IAM ロールを持つ Lambda や EC2では、認証情報は IAM ロールから自動的に取得されます。
### OpenRouter
```bash
OPENROUTER_API_KEY=your_api_key
AI_MODEL=anthropic/claude-sonnet-4
```
任意のカスタムエンドポイント:
```bash
OPENROUTER_BASE_URL=https://your-custom-endpoint
```
### Ollama (ローカル)
```bash
AI_PROVIDER=ollama
AI_MODEL=llama3.2
```
任意のカスタム URL:
```bash
OLLAMA_BASE_URL=http://localhost:11434
```
### Vercel AI Gateway
Vercel AI Gateway は、単一の API キーで複数の AI プロバイダーへの統合アクセスを提供します。これにより認証が簡素化され、複数の API キーを管理することなくプロバイダーを切り替えることができます。
**基本的な使用法 (Vercel ホストの Gateway):**
```bash
AI_GATEWAY_API_KEY=your_gateway_api_key
AI_MODEL=openai/gpt-4o
```
**カスタム Gateway URL (ローカル開発またはセルフホスト Gateway 用):**
```bash
AI_GATEWAY_API_KEY=your_custom_api_key
AI_GATEWAY_BASE_URL=https://your-custom-gateway.com/v1/ai
AI_MODEL=openai/gpt-4o
```
モデル形式は `provider/model` 構文を使用します:
- `openai/gpt-4o` - OpenAI GPT-4o
- `anthropic/claude-sonnet-4-5` - Anthropic Claude Sonnet 4.5
- `google/gemini-2.0-flash` - Google Gemini 2.0 Flash
**設定に関する注意点:**
- `AI_GATEWAY_BASE_URL` が設定されていない場合、デフォルトの Vercel Gateway URL (`https://ai-gateway.vercel.sh/v1/ai`) が使用されます
- カスタムベース URL は以下の場合に便利です:
- カスタム Gateway インスタンスを使用したローカル開発
- セルフホスト AI Gateway デプロイメント
- エンタープライズプロキシ設定
- カスタムベース URL を使用する場合、`AI_GATEWAY_API_KEY` も指定する必要があります
[Vercel AI Gateway ダッシュボード](https://vercel.com/ai-gateway)から API キーを取得してください。
## 自動検出
**1つ**のプロバイダーの API キーのみを設定した場合、システムはそのプロバイダーを自動的に検出して使用します。`AI_PROVIDER` を設定する必要はありません。
**複数**の API キーを設定する場合は、`AI_PROVIDER` を明示的に設定する必要があります:
```bash
AI_PROVIDER=google # または: openai, anthropic, deepseek, siliconflow, doubao, azure, bedrock, openrouter, ollama, gateway, sglang
```
## モデル性能要件
このタスクは、厳密なフォーマット制約draw.io XMLを伴う長文テキストの生成を含むため、非常に強力なモデル性能が必要です。
**推奨モデル**:
- Claude Sonnet 4.5 / Opus 4.5
**Ollama に関する注意**: Ollama はプロバイダーとしてサポートされていますが、DeepSeek R1 や Qwen3-235B のような高性能モデルをローカルで実行していない限り、このユースケースでは一般的に実用的ではありません。
## Temperature温度設定
環境変数で Temperature を任意に設定できます:
```bash
TEMPERATURE=0 # より決定論的な出力(ダイアグラムに推奨)
```
**重要**: 以下の Temperature 設定をサポートしていないモデルでは、`TEMPERATURE` を未設定のままにしてください:
- GPT-5.1 およびその他の推論モデル
- 一部の特殊なモデル
未設定の場合、モデルはデフォルトの挙動を使用します。
## 推奨事項
- **最高の体験**: 画像からダイアグラムを生成する機能には、ビジョン画像認識をサポートするモデルGPT-4o, Claude, Geminiを使用してください
- **低コスト**: DeepSeek は競争力のある価格を提供しています
- **プライバシー**: 完全にローカルなオフライン操作には Ollama を使用してください(強力なハードウェアが必要です)
- **柔軟性**: OpenRouter は単一の API で多数のモデルへのアクセスを提供します

View File

@@ -0,0 +1,267 @@
# Cloudflare Workers へのデプロイ
このプロジェクトは **OpenNext アダプター** を使用して **Cloudflare Worker** としてデプロイすることができ、以下のメリットがあります:
- グローバルエッジへのデプロイ
- 超低レイテンシー
- 無料の `workers.dev` ホスティング
- R2 を介した完全な Next.js ISR サポート(オプション)
> **Windows ユーザー向けの重要な注意:** OpenNext と Wrangler は、**ネイティブ Windows 環境では完全には信頼できません**。以下の方法を推奨します:
>
> - **GitHub Codespaces** を使用する(完全に動作します)
> - または **WSL (Linux)** を使用する
>
> 純粋な Windows 環境でのビルドは、WASM ファイルパスの問題により失敗する可能性があります。
---
## 前提条件
1. **Cloudflare アカウント**(基本的なデプロイには無料プランで十分です)
2. **Node.js 18以上**
3. **Wrangler CLI** のインストール(開発依存関係で問題ありません):
```bash
npm install -D wrangler
```
4. Cloudflare へのログイン:
```bash
npx wrangler login
```
> **注意:** 支払い方法の登録が必要なのは、ISR キャッシュのために R2 を有効にする場合のみです。基本的な Workers へのデプロイは無料です。
---
## ステップ 1 — 依存関係のインストール
```bash
npm install
```
---
## ステップ 2 — 環境変数の設定
Cloudflare はローカルテスト用に別のファイルを使用します。
### 1) `.dev.vars` の作成Cloudflare ローカルおよびデプロイ用)
```bash
cp env.example .dev.vars
```
API キーと設定を入力してください。
### 2) `.env.local` も存在することを確認(通常の Next.js 開発用)
```bash
cp env.example .env.local
```
同じ値を入力してください。
---
## ステップ 3 — デプロイタイプの選択
### オプション A: R2 なしでのデプロイ(シンプル、無料)
ISR キャッシュが不要な場合は、R2 なしでデプロイできます:
**1. シンプルな `open-next.config.ts` を使用:**
```ts
import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"
export default defineCloudflareConfig({})
```
**2. シンプルな `wrangler.jsonc` を使用r2_buckets なし):**
```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"main": ".open-next/worker.js",
"name": "next-ai-draw-io-worker",
"compatibility_date": "2025-12-08",
"compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
"assets": {
"directory": ".open-next/assets",
"binding": "ASSETS"
},
"services": [
{
"binding": "WORKER_SELF_REFERENCE",
"service": "next-ai-draw-io-worker"
}
]
}
```
**ステップ 4** へ進んでください。
---
### オプション B: R2 ありでのデプロイ(完全な ISR サポート)
R2 を使用すると **Incremental Static Regeneration (ISR)** キャッシュが有効になります。これには Cloudflare アカウントに支払い方法の登録が必要です。
**1. R2 バケットの作成**Cloudflare ダッシュボードにて):
- **Storage & Databases → R2** へ移動
- **Create bucket** をクリック
- 名前を入力: `next-inc-cache`
**2. `open-next.config.ts` の設定:**
```ts
import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"
import r2IncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/r2-incremental-cache"
export default defineCloudflareConfig({
incrementalCache: r2IncrementalCache,
})
```
**3. `wrangler.jsonc` の設定R2 あり):**
```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"main": ".open-next/worker.js",
"name": "next-ai-draw-io-worker",
"compatibility_date": "2025-12-08",
"compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
"assets": {
"directory": ".open-next/assets",
"binding": "ASSETS"
},
"r2_buckets": [
{
"binding": "NEXT_INC_CACHE_R2_BUCKET",
"bucket_name": "next-inc-cache"
}
],
"services": [
{
"binding": "WORKER_SELF_REFERENCE",
"service": "next-ai-draw-io-worker"
}
]
}
```
> **重要:** `bucket_name` は Cloudflare ダッシュボードで作成した名前と完全に一致させる必要があります。
---
## ステップ 4 — workers.dev サブドメインの登録(初回のみ)
初回デプロイの前に、workers.dev サブドメインが必要です。
**オプション 1: Cloudflare ダッシュボード経由(推奨)**
アクセス先: https://dash.cloudflare.com → Workers & Pages → Overview → Set up a subdomain
**オプション 2: デプロイ時**
`npm run deploy` を実行した際、Wrangler が以下のように尋ねてくる場合があります:
```
Would you like to register a workers.dev subdomain? (Y/n)
```
`Y` を入力し、サブドメイン名を選択してください。
> **注意:** CI/CD や非対話型環境では、このプロンプトは表示されません。事前にダッシュボードで登録してください。
---
## ステップ 5 — Cloudflare へのデプロイ
```bash
npm run deploy
```
スクリプトの処理内容:
- Next.js アプリのビルド
- OpenNext を介した Cloudflare Worker への変換
- 静的アセットのアップロード
- Worker の公開
アプリは以下の URL で利用可能になります:
```
https://<worker-name>.<your-subdomain>.workers.dev
```
---
## よくある問題と解決策
### `You need to register a workers.dev subdomain`
**原因:** アカウントに workers.dev サブドメインが登録されていません。
**解決策:** https://dash.cloudflare.com → Workers & Pages → Set up a subdomain から登録してください。
---
### `Please enable R2 through the Cloudflare Dashboard`
**原因:** `wrangler.jsonc` で R2 が設定されていますが、アカウントで R2 が有効になっていません。
**解決策:** R2 を有効にする(支払い方法が必要)か、オプション AR2 なしでデプロイ)を使用してください。
---
### `No R2 binding "NEXT_INC_CACHE_R2_BUCKET" found`
**原因:** `wrangler.jsonc``r2_buckets` がありません。
**解決策:** `r2_buckets` セクションを追加するか、オプション AR2 なし)に切り替えてください。
---
### `Can't set compatibility date in the future`
**原因:** wrangler 設定の `compatibility_date` が未来の日付に設定されています。
**解決策:** `compatibility_date` を今日またはそれ以前の日付に変更してください。
---
### Windows エラー: `resvg.wasm?module` (ENOENT)
**原因:** Windows のファイル名には `?` を含めることができませんが、wasm アセットのファイル名に `?module` が使用されているためです。
**解決策:** Linux 環境WSL、Codespaces、または CIでビルド/デプロイしてください。
---
## オプション: ローカルでのプレビュー
デプロイ前に Worker をローカルでプレビューできます:
```bash
npm run preview
```
---
## まとめ
| 機能 | R2 なし | R2 あり |
|---------|------------|---------|
| コスト | 無料 | 支払い方法が必要 |
| ISR キャッシュ | なし | あり |
| 静的ページ | あり | あり |
| API ルート | あり | あり |
| 設定の複雑さ | シンプル | 普通 |
テストやシンプルなアプリには **R2 なし** を選んでください。ISR キャッシュが必要な本番アプリには **R2 あり** を選んでください。

29
docs/ja/docker.md Normal file
View File

@@ -0,0 +1,29 @@
# Dockerで実行する
ローカルで実行したいだけであれば、Dockerを使用するのが最も良い方法です。
まず、Dockerがまだインストールされていない場合はインストールしてください: [Dockerを入手](https://docs.docker.com/get-docker/)
次に、以下を実行します。
```bash
docker run -d -p 3000:3000 \
-e AI_PROVIDER=openai \
-e AI_MODEL=gpt-4o \
-e OPENAI_API_KEY=your_api_key \
ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
または、envファイルを使用します。
```bash
cp env.example .env
# .envを構成に合わせて編集します
docker run -d -p 3000:3000 --env-file .env ghcr.io/dayuanjiang/next-ai-draw-io:latest
```
ブラウザで[http://localhost:3000](http://localhost:3000)を開きます。
環境変数は、お好みのAIプロバイダー設定に置き換えてください。利用可能なオプションについては、[AIプロバイダー](./ai-providers.md)を参照してください。
> **オフラインデプロイ:** `embed.diagrams.net`がブロックされている場合は、構成オプションについて[オフラインデプロイ](./offline-deployment.md)を参照してください。

View File

@@ -0,0 +1,38 @@
# オフラインデプロイ
`embed.diagrams.net` の代わりに draw.io をセルフホストすることで、Next AI Draw.io をオフライン環境にデプロイできます。
**注:** `NEXT_PUBLIC_DRAWIO_BASE_URL` は**ビルド時**の変数です。これを変更する場合は、Docker イメージの再ビルドが必要です。
## Docker Compose のセットアップ
1. リポジトリをクローンし、`.env` ファイルに API キーを定義します。
2. `docker-compose.yml` を作成します。
```yaml
services:
drawio:
image: jgraph/drawio:latest
ports: ["8080:8080"]
next-ai-draw-io:
build:
context: .
args:
- NEXT_PUBLIC_DRAWIO_BASE_URL=http://localhost:8080
ports: ["3000:3000"]
env_file: .env
depends_on: [drawio]
```
3. `docker compose up -d` を実行し、`http://localhost:3000` にアクセスします。
## 設定と重要な警告
**`NEXT_PUBLIC_DRAWIO_BASE_URL` は、ユーザーのブラウザからアクセスできる必要があります。**
| シナリオ | URL の値 |
|----------|-----------|
| ローカルホスト | `http://localhost:8080` |
| リモート/サーバー | `http://YOUR_SERVER_IP:8080` |
**`http://drawio:8080` のような Docker 内部のエイリアスは絶対に使用しないでください。** ブラウザはこれらを名前解決できません。

View File

@@ -0,0 +1,270 @@
/**
* EdgeOne Pages Edge Function for OpenAI-compatible Chat Completions API
*
* This endpoint provides an OpenAI-compatible API that can be used with
* AI SDK's createOpenAI({ baseURL: '/api/edgeai' })
*
* Uses EdgeOne Edge AI's AI.chatCompletions() which now supports native tool calling.
*/
import { z } from "zod"
// EdgeOne Pages global AI object
declare const AI: {
chatCompletions(options: {
model: string
messages: Array<{ role: string; content: string | null }>
stream?: boolean
max_tokens?: number
temperature?: number
tools?: any
tool_choice?: any
}): Promise<ReadableStream<Uint8Array> | any>
}
const messageItemSchema = z
.object({
role: z.enum(["user", "assistant", "system", "tool", "function"]),
content: z.string().nullable().optional(),
})
.passthrough()
const messageSchema = z
.object({
messages: z.array(messageItemSchema),
model: z.string().optional(),
stream: z.boolean().optional(),
tools: z.any().optional(),
tool_choice: z.any().optional(),
functions: z.any().optional(),
function_call: z.any().optional(),
temperature: z.number().optional(),
top_p: z.number().optional(),
max_tokens: z.number().optional(),
presence_penalty: z.number().optional(),
frequency_penalty: z.number().optional(),
stop: z.union([z.string(), z.array(z.string())]).optional(),
response_format: z.any().optional(),
seed: z.number().optional(),
user: z.string().optional(),
n: z.number().int().optional(),
logit_bias: z.record(z.string(), z.number()).optional(),
parallel_tool_calls: z.boolean().optional(),
stream_options: z.any().optional(),
})
.passthrough()
// Model configuration
const ALLOWED_MODELS = [
"@tx/deepseek-ai/deepseek-v32",
"@tx/deepseek-ai/deepseek-r1-0528",
"@tx/deepseek-ai/deepseek-v3-0324",
]
const MODEL_ALIASES: Record<string, string> = {
"deepseek-v3.2": "@tx/deepseek-ai/deepseek-v32",
"deepseek-r1-0528": "@tx/deepseek-ai/deepseek-r1-0528",
"deepseek-v3-0324": "@tx/deepseek-ai/deepseek-v3-0324",
}
const CORS_HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
}
/**
* Create standardized response with CORS headers
*/
function createResponse(body: any, status = 200, extraHeaders = {}): Response {
return new Response(JSON.stringify(body), {
status,
headers: {
"Content-Type": "application/json",
...CORS_HEADERS,
...extraHeaders,
},
})
}
/**
* Handle OPTIONS request for CORS preflight
*/
function handleOptionsRequest(): Response {
return new Response(null, {
headers: {
...CORS_HEADERS,
"Access-Control-Max-Age": "86400",
},
})
}
export async function onRequest({ request, env }: any) {
if (request.method === "OPTIONS") {
return handleOptionsRequest()
}
request.headers.delete("accept-encoding")
try {
const json = await request.clone().json()
const parseResult = messageSchema.safeParse(json)
if (!parseResult.success) {
return createResponse(
{
error: {
message: parseResult.error.message,
type: "invalid_request_error",
},
},
400,
)
}
const { messages, model, stream, tools, tool_choice, ...extraParams } =
parseResult.data
// Validate messages
const userMessages = messages.filter(
(message) => message.role === "user",
)
if (!userMessages.length) {
return createResponse(
{
error: {
message: "No user message found",
type: "invalid_request_error",
},
},
400,
)
}
// Resolve model
const requestedModel = model || ALLOWED_MODELS[0]
const selectedModel = MODEL_ALIASES[requestedModel] || requestedModel
if (!ALLOWED_MODELS.includes(selectedModel)) {
return createResponse(
{
error: {
message: `Invalid model: ${requestedModel}.`,
type: "invalid_request_error",
},
},
429,
)
}
console.log(
`[EdgeOne] Model: ${selectedModel}, Tools: ${tools?.length || 0}, Stream: ${stream ?? true}`,
)
try {
const isStream = !!stream
// Non-streaming: return mock response for validation
// AI.chatCompletions doesn't support non-streaming mode
if (!isStream) {
const mockResponse = {
id: `chatcmpl-${Date.now()}`,
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: selectedModel,
choices: [
{
index: 0,
message: {
role: "assistant",
content: "OK",
},
finish_reason: "stop",
},
],
usage: {
prompt_tokens: 10,
completion_tokens: 1,
total_tokens: 11,
},
}
return createResponse(mockResponse)
}
// Build AI.chatCompletions options for streaming
const aiOptions: any = {
...extraParams,
model: selectedModel,
messages,
stream: true,
}
// Add tools if provided
if (tools && tools.length > 0) {
aiOptions.tools = tools
}
if (tool_choice !== undefined) {
aiOptions.tool_choice = tool_choice
}
const aiResponse = await AI.chatCompletions(aiOptions)
// Streaming response
return new Response(aiResponse, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-store, no-transform",
"X-Accel-Buffering": "no",
Connection: "keep-alive",
...CORS_HEADERS,
},
})
} catch (error: any) {
// Handle EdgeOne specific errors
try {
const message = JSON.parse(error.message)
if (message.code === 14020) {
return createResponse(
{
error: {
message:
"The daily public quota has been exhausted. After deployment, you can enjoy a personal daily exclusive quota.",
type: "rate_limit_error",
},
},
429,
)
}
return createResponse(
{ error: { message: error.message, type: "api_error" } },
500,
)
} catch {
// Not a JSON error message
}
console.error("[EdgeOne] AI error:", error.message)
return createResponse(
{
error: {
message: error.message || "AI service error",
type: "api_error",
},
},
500,
)
}
} catch (error: any) {
console.error("[EdgeOne] Request error:", error.message)
return createResponse(
{
error: {
message: "Request processing failed",
type: "server_error",
details: error.message,
},
},
500,
)
}
}

5
edgeone.json Normal file
View File

@@ -0,0 +1,5 @@
{
"nodeFunctionsConfig": {
"maxDuration": 120
}
}

View File

@@ -11,7 +11,6 @@ import {
flattenModels, flattenModels,
type ModelConfig, type ModelConfig,
type MultiModelConfig, type MultiModelConfig,
PROVIDER_INFO,
type ProviderConfig, type ProviderConfig,
type ProviderName, type ProviderName,
} from "@/lib/types/model-config" } from "@/lib/types/model-config"

View File

@@ -21,6 +21,7 @@ export type ProviderName =
| "siliconflow" | "siliconflow"
| "sglang" | "sglang"
| "gateway" | "gateway"
| "edgeone"
| "doubao" | "doubao"
interface ModelConfig { interface ModelConfig {
@@ -40,6 +41,8 @@ export interface ClientOverrides {
awsSecretAccessKey?: string | null awsSecretAccessKey?: string | null
awsRegion?: string | null awsRegion?: string | null
awsSessionToken?: string | null awsSessionToken?: string | null
// Custom headers (e.g., for EdgeOne cookie auth)
headers?: Record<string, string>
} }
// Providers that can be used with client-provided API keys // Providers that can be used with client-provided API keys
@@ -54,6 +57,7 @@ const ALLOWED_CLIENT_PROVIDERS: ProviderName[] = [
"siliconflow", "siliconflow",
"sglang", "sglang",
"gateway", "gateway",
"edgeone",
"doubao", "doubao",
] ]
@@ -375,6 +379,7 @@ const PROVIDER_ENV_VARS: Record<ProviderName, string | null> = {
siliconflow: "SILICONFLOW_API_KEY", siliconflow: "SILICONFLOW_API_KEY",
sglang: "SGLANG_API_KEY", sglang: "SGLANG_API_KEY",
gateway: "AI_GATEWAY_API_KEY", gateway: "AI_GATEWAY_API_KEY",
edgeone: null, // No credentials needed - uses EdgeOne Edge AI
doubao: "DOUBAO_API_KEY", doubao: "DOUBAO_API_KEY",
} }
@@ -463,7 +468,12 @@ export function getAIModel(overrides?: ClientOverrides): ModelConfig {
// SECURITY: Prevent SSRF attacks (GHSA-9qf7-mprq-9qgm) // SECURITY: Prevent SSRF attacks (GHSA-9qf7-mprq-9qgm)
// If a custom baseUrl is provided, an API key MUST also be provided. // If a custom baseUrl is provided, an API key MUST also be provided.
// This prevents attackers from redirecting server API keys to malicious endpoints. // This prevents attackers from redirecting server API keys to malicious endpoints.
if (overrides?.baseUrl && !overrides?.apiKey) { // Exception: EdgeOne provider doesn't require API key (uses Edge AI runtime)
if (
overrides?.baseUrl &&
!overrides?.apiKey &&
overrides?.provider !== "edgeone"
) {
throw new Error( throw new Error(
`API key is required when using a custom base URL. ` + `API key is required when using a custom base URL. ` +
`Please provide your own API key in Settings.`, `Please provide your own API key in Settings.`,
@@ -776,7 +786,7 @@ export function getAIModel(overrides?: ClientOverrides): ModelConfig {
`data: ${JSON.stringify(data)}\n\n`, `data: ${JSON.stringify(data)}\n\n`,
), ),
) )
} catch (e) { } catch (_e) {
// If parsing fails, forward the original message to avoid breaking the stream. // If parsing fails, forward the original message to avoid breaking the stream.
controller.enqueue( controller.enqueue(
new TextEncoder().encode( new TextEncoder().encode(
@@ -840,6 +850,21 @@ export function getAIModel(overrides?: ClientOverrides): ModelConfig {
break break
} }
case "edgeone": {
// EdgeOne Pages Edge AI - uses OpenAI-compatible API
// AI SDK appends /chat/completions to baseURL
// /api/edgeai + /chat/completions = /api/edgeai/chat/completions
const baseURL = overrides?.baseUrl || "/api/edgeai"
const edgeoneProvider = createOpenAI({
apiKey: "edgeone", // Dummy key - EdgeOne doesn't require API key
baseURL,
// Pass cookies for EdgeOne Pages authentication (eo_token, eo_time)
...(overrides?.headers && { headers: overrides.headers }),
})
model = edgeoneProvider.chat(modelId)
break
}
case "doubao": { case "doubao": {
const apiKey = overrides?.apiKey || process.env.DOUBAO_API_KEY const apiKey = overrides?.apiKey || process.env.DOUBAO_API_KEY
const baseURL = const baseURL =
@@ -856,7 +881,7 @@ export function getAIModel(overrides?: ClientOverrides): ModelConfig {
default: default:
throw new Error( throw new Error(
`Unknown AI provider: ${provider}. Supported providers: bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow, sglang, gateway, doubao`, `Unknown AI provider: ${provider}. Supported providers: bedrock, openai, anthropic, google, azure, ollama, openrouter, deepseek, siliconflow, sglang, gateway, edgeone, doubao`,
) )
} }
@@ -881,3 +906,34 @@ export function supportsPromptCaching(modelId: string): boolean {
modelId.startsWith("eu.anthropic") modelId.startsWith("eu.anthropic")
) )
} }
/**
* Check if a model supports image/vision input.
* Some models silently drop image parts without error (AI SDK warning only).
*/
export function supportsImageInput(modelId: string): boolean {
const lowerModelId = modelId.toLowerCase()
// Helper to check if model has vision capability indicator
const hasVisionIndicator =
lowerModelId.includes("vision") || lowerModelId.includes("vl")
// Models that DON'T support image/vision input (unless vision variant)
// Kimi K2 models don't support images
if (lowerModelId.includes("kimi") && !hasVisionIndicator) {
return false
}
// DeepSeek text models (not vision variants)
if (lowerModelId.includes("deepseek") && !hasVisionIndicator) {
return false
}
// Qwen text models (not vision variants like qwen-vl)
if (lowerModelId.includes("qwen") && !hasVisionIndicator) {
return false
}
// Default: assume model supports images
return true
}

View File

@@ -46,6 +46,7 @@
"copyResponse": "Copy response", "copyResponse": "Copy response",
"copied": "Copied!", "copied": "Copied!",
"failedToCopy": "Failed to copy", "failedToCopy": "Failed to copy",
"failedToCopyDetail": "Failed to copy message. Please copy manually or check clipboard permissions.",
"goodResponse": "Good response", "goodResponse": "Good response",
"badResponse": "Bad response", "badResponse": "Bad response",
"clickToEdit": "Click to edit", "clickToEdit": "Click to edit",
@@ -141,6 +142,7 @@
"invalidAccessCode": "Invalid or missing access code. Please configure it in Settings.", "invalidAccessCode": "Invalid or missing access code. Please configure it in Settings.",
"networkError": "Network error. Please check your connection.", "networkError": "Network error. Please check your connection.",
"retryLimit": "Auto-retry limit reached ({max}). Please try again manually.", "retryLimit": "Auto-retry limit reached ({max}). Please try again manually.",
"continuationRetryLimit": "Continuation retry limit reached ({max}). The diagram may be too complex.",
"validationFailed": "Diagram validation failed. Please try regenerating.", "validationFailed": "Diagram validation failed. Please try regenerating.",
"malformedXml": "AI generated invalid diagram XML. Please try regenerating.", "malformedXml": "AI generated invalid diagram XML. Please try regenerating.",
"failedToProcess": "Failed to process diagram. Please try regenerating.", "failedToProcess": "Failed to process diagram. Please try regenerating.",
@@ -149,7 +151,9 @@
"failedToRestore": "Failed to restore from localStorage", "failedToRestore": "Failed to restore from localStorage",
"failedToPersist": "Failed to persist state before unload", "failedToPersist": "Failed to persist state before unload",
"failedToExport": "Error fetching chart data", "failedToExport": "Error fetching chart data",
"failedToLoadExample": "Error loading example image" "failedToLoadExample": "Error loading example image",
"failedToRecordFeedback": "Failed to record your feedback. Please try again.",
"storageUpdateFailed": "Chat cleared but browser storage could not be updated"
}, },
"quota": { "quota": {
"dailyLimit": "Daily Quota Reached", "dailyLimit": "Daily Quota Reached",
@@ -186,6 +190,21 @@
"thoughtFor": "Thought for {duration} seconds", "thoughtFor": "Thought for {duration} seconds",
"thoughtBrief": "Thought for a few seconds" "thoughtBrief": "Thought for a few seconds"
}, },
"dev": {
"title": "Dev: XML Streaming Simulator",
"preset": "Preset:",
"selectPreset": "Select a preset...",
"clear": "Clear",
"placeholder": "Paste mxCell XML here or select a preset...",
"interval": "Interval:",
"chars": "Chars:",
"streaming": "Streaming...",
"simulate": "Simulate",
"stop": "Stop",
"testQuotaToast": "Test Quota Toast",
"simulatingMessage": "[Dev] Simulating XML streaming",
"successMessage": "Successfully displayed the diagram."
},
"about": { "about": {
"modelChange": "Model Change & Usage Limits", "modelChange": "Model Change & Usage Limits",
"walletCrying": "(Or: Why My Wallet is Crying)", "walletCrying": "(Or: Why My Wallet is Crying)",

View File

@@ -46,6 +46,7 @@
"copyResponse": "応答をコピー", "copyResponse": "応答をコピー",
"copied": "コピーしました!", "copied": "コピーしました!",
"failedToCopy": "コピーに失敗しました", "failedToCopy": "コピーに失敗しました",
"failedToCopyDetail": "メッセージのコピーに失敗しました。手動でコピーするか、クリップボードの権限を確認してください。",
"goodResponse": "良い応答", "goodResponse": "良い応答",
"badResponse": "悪い応答", "badResponse": "悪い応答",
"clickToEdit": "クリックして編集", "clickToEdit": "クリックして編集",
@@ -141,6 +142,7 @@
"invalidAccessCode": "無効または欠落したアクセスコード。設定で入力してください。", "invalidAccessCode": "無効または欠落したアクセスコード。設定で入力してください。",
"networkError": "ネットワークエラー。接続を確認してください。", "networkError": "ネットワークエラー。接続を確認してください。",
"retryLimit": "自動再試行制限に達しました({max})。手動で再試行してください。", "retryLimit": "自動再試行制限に達しました({max})。手動で再試行してください。",
"continuationRetryLimit": "継続再試行制限に達しました({max})。ダイアグラムが複雑すぎる可能性があります。",
"validationFailed": "ダイアグラムの検証に失敗しました。再生成してみてください。", "validationFailed": "ダイアグラムの検証に失敗しました。再生成してみてください。",
"malformedXml": "AI が無効なダイアグラム XML を生成しました。再生成してみてください。", "malformedXml": "AI が無効なダイアグラム XML を生成しました。再生成してみてください。",
"failedToProcess": "ダイアグラムの処理に失敗しました。再生成してみてください。", "failedToProcess": "ダイアグラムの処理に失敗しました。再生成してみてください。",
@@ -149,7 +151,9 @@
"failedToRestore": "localStorage からの復元に失敗しました", "failedToRestore": "localStorage からの復元に失敗しました",
"failedToPersist": "アンロード前の状態の永続化に失敗しました", "failedToPersist": "アンロード前の状態の永続化に失敗しました",
"failedToExport": "チャートデータの取得エラー", "failedToExport": "チャートデータの取得エラー",
"failedToLoadExample": "例の画像の読み込みエラー" "failedToLoadExample": "例の画像の読み込みエラー",
"failedToRecordFeedback": "フィードバックの記録に失敗しました。もう一度お試しください。",
"storageUpdateFailed": "チャットはクリアされましたが、ブラウザストレージを更新できませんでした"
}, },
"quota": { "quota": {
"dailyLimit": "1日の割当量に達しました", "dailyLimit": "1日の割当量に達しました",
@@ -186,6 +190,21 @@
"thoughtFor": "{duration} 秒考えました", "thoughtFor": "{duration} 秒考えました",
"thoughtBrief": "数秒考えました" "thoughtBrief": "数秒考えました"
}, },
"dev": {
"title": "開発XMLストリーミングシミュレーター",
"preset": "プリセット:",
"selectPreset": "プリセットを選択...",
"clear": "クリア",
"placeholder": "ここに mxCell XML を貼り付けるか、プリセットを選択...",
"interval": "間隔:",
"chars": "文字:",
"streaming": "ストリーミング中...",
"simulate": "シミュレート",
"stop": "停止",
"testQuotaToast": "クォータトーストをテスト",
"simulatingMessage": "[開発] XMLストリーミングをシミュレート中",
"successMessage": "ダイアグラムの表示に成功しました。"
},
"about": { "about": {
"modelChange": "モデル変更と利用制限について", "modelChange": "モデル変更と利用制限について",
"walletCrying": "(別名:お財布が悲鳴を上げています)", "walletCrying": "(別名:お財布が悲鳴を上げています)",

View File

@@ -46,6 +46,7 @@
"copyResponse": "复制响应", "copyResponse": "复制响应",
"copied": "已复制!", "copied": "已复制!",
"failedToCopy": "复制失败", "failedToCopy": "复制失败",
"failedToCopyDetail": "复制消息失败。请手动复制或检查剪贴板权限。",
"goodResponse": "有帮助", "goodResponse": "有帮助",
"badResponse": "无帮助", "badResponse": "无帮助",
"clickToEdit": "点击编辑", "clickToEdit": "点击编辑",
@@ -141,6 +142,7 @@
"invalidAccessCode": "无效或缺少访问码。请在设置中配置。", "invalidAccessCode": "无效或缺少访问码。请在设置中配置。",
"networkError": "网络错误。请检查您的连接。", "networkError": "网络错误。请检查您的连接。",
"retryLimit": "已达到自动重试限制({max})。请手动重试。", "retryLimit": "已达到自动重试限制({max})。请手动重试。",
"continuationRetryLimit": "已达到继续重试限制({max})。图表可能过于复杂。",
"validationFailed": "图表验证失败。请尝试重新生成。", "validationFailed": "图表验证失败。请尝试重新生成。",
"malformedXml": "AI 生成的图表 XML 无效。请尝试重新生成。", "malformedXml": "AI 生成的图表 XML 无效。请尝试重新生成。",
"failedToProcess": "无法处理图表。请尝试重新生成。", "failedToProcess": "无法处理图表。请尝试重新生成。",
@@ -149,7 +151,9 @@
"failedToRestore": "无法从 localStorage 恢复", "failedToRestore": "无法从 localStorage 恢复",
"failedToPersist": "卸载前无法持久化状态", "failedToPersist": "卸载前无法持久化状态",
"failedToExport": "获取图表数据时出错", "failedToExport": "获取图表数据时出错",
"failedToLoadExample": "加载示例图片时出错" "failedToLoadExample": "加载示例图片时出错",
"failedToRecordFeedback": "记录您的反馈失败。请重试。",
"storageUpdateFailed": "聊天已清除,但无法更新浏览器存储"
}, },
"quota": { "quota": {
"dailyLimit": "已达每日配额", "dailyLimit": "已达每日配额",
@@ -186,6 +190,21 @@
"thoughtFor": "思考了 {duration} 秒", "thoughtFor": "思考了 {duration} 秒",
"thoughtBrief": "思考了几秒钟" "thoughtBrief": "思考了几秒钟"
}, },
"dev": {
"title": "开发XML 流式模拟器",
"preset": "预设:",
"selectPreset": "选择预设...",
"clear": "清除",
"placeholder": "在此粘贴 mxCell XML 或选择预设...",
"interval": "间隔:",
"chars": "字符:",
"streaming": "流式传输中...",
"simulate": "模拟",
"stop": "停止",
"testQuotaToast": "测试配额提示",
"simulatingMessage": "[开发] 模拟 XML 流式传输",
"successMessage": "成功显示图表。"
},
"about": { "about": {
"modelChange": "模型变更与用量限制", "modelChange": "模型变更与用量限制",
"walletCrying": "(别名:我的钱包顶不住了)", "walletCrying": "(别名:我的钱包顶不住了)",

View File

@@ -276,7 +276,7 @@ edit_diagram uses ID-based operations to modify cells directly by their id attri
**Operations:** **Operations:**
- **update**: Replace an existing cell. Provide cell_id and new_xml. - **update**: Replace an existing cell. Provide cell_id and new_xml.
- **add**: Add a new cell. Provide cell_id (new unique id) and new_xml. - **add**: Add a new cell. Provide cell_id (new unique id) and new_xml.
- **delete**: Remove a cell. Only cell_id is needed. - **delete**: Remove a cell. **Cascade is automatic**: children AND edges (source/target) are auto-deleted. Only specify ONE cell_id.
**Input Format:** **Input Format:**
\`\`\`json \`\`\`json
@@ -301,9 +301,9 @@ Add new shape:
{"operations": [{"operation": "add", "cell_id": "new1", "new_xml": "<mxCell id=\\"new1\\" value=\\"New Box\\" style=\\"rounded=1;fillColor=#dae8fc;\\" vertex=\\"1\\" parent=\\"1\\">\\n <mxGeometry x=\\"400\\" y=\\"200\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/>\\n</mxCell>"}]} {"operations": [{"operation": "add", "cell_id": "new1", "new_xml": "<mxCell id=\\"new1\\" value=\\"New Box\\" style=\\"rounded=1;fillColor=#dae8fc;\\" vertex=\\"1\\" parent=\\"1\\">\\n <mxGeometry x=\\"400\\" y=\\"200\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/>\\n</mxCell>"}]}
\`\`\` \`\`\`
Delete cell: Delete container (children & edges auto-deleted):
\`\`\`json \`\`\`json
{"operations": [{"operation": "delete", "cell_id": "5"}]} {"operations": [{"operation": "delete", "cell_id": "2"}]}
\`\`\` \`\`\`
**Error Recovery:** **Error Recovery:**

View File

@@ -11,6 +11,7 @@ export type ProviderName =
| "siliconflow" | "siliconflow"
| "sglang" | "sglang"
| "gateway" | "gateway"
| "edgeone"
| "doubao" | "doubao"
// Individual model configuration // Individual model configuration
@@ -85,6 +86,7 @@ export const PROVIDER_INFO: Record<
defaultBaseUrl: "http://127.0.0.1:8000/v1", defaultBaseUrl: "http://127.0.0.1:8000/v1",
}, },
gateway: { label: "AI Gateway" }, gateway: { label: "AI Gateway" },
edgeone: { label: "EdgeOne Pages" },
doubao: { doubao: {
label: "Doubao (ByteDance)", label: "Doubao (ByteDance)",
defaultBaseUrl: "https://ark.cn-beijing.volces.com/api/v3", defaultBaseUrl: "https://ark.cn-beijing.volces.com/api/v3",
@@ -219,6 +221,7 @@ export const SUGGESTED_MODELS: Record<ProviderName, string[]> = {
"anthropic/claude-3-5-sonnet", "anthropic/claude-3-5-sonnet",
"google/gemini-2.0-flash", "google/gemini-2.0-flash",
], ],
edgeone: ["@tx/deepseek-ai/deepseek-v32"],
doubao: [ doubao: [
// ByteDance Doubao models // ByteDance Doubao models
"doubao-1.5-thinking-pro-250415", "doubao-1.5-thinking-pro-250415",

View File

@@ -633,32 +633,77 @@ export function applyDiagramOperations(
// Add to map // Add to map
cellMap.set(op.cell_id, importedNode) cellMap.set(op.cell_id, importedNode)
} else if (op.operation === "delete") { } else if (op.operation === "delete") {
const existingCell = cellMap.get(op.cell_id) // Protect root cells from deletion
if (!existingCell) { if (op.cell_id === "0" || op.cell_id === "1") {
errors.push({ errors.push({
type: "delete", type: "delete",
cellId: op.cell_id, cellId: op.cell_id,
message: `Cell with id="${op.cell_id}" not found`, message: `Cannot delete root cell "${op.cell_id}"`,
}) })
continue continue
} }
// Check for edges referencing this cell (warning only, still delete) const existingCell = cellMap.get(op.cell_id)
const referencingEdges = root.querySelectorAll( if (!existingCell) {
`mxCell[source="${op.cell_id}"], mxCell[target="${op.cell_id}"]`, // Cell not found - might have been cascade-deleted by a previous operation
// Skip silently instead of erroring (AI may redundantly list children/edges)
continue
}
// Cascade delete: collect all cells to delete (children + edges + self)
const cellsToDelete = new Set<string>()
// Recursive function to find all descendants
const collectDescendants = (cellId: string) => {
if (cellsToDelete.has(cellId)) return
cellsToDelete.add(cellId)
// Find children (cells where parent === cellId)
const children = root.querySelectorAll(
`mxCell[parent="${cellId}"]`,
) )
if (referencingEdges.length > 0) { children.forEach((child) => {
const edgeIds = Array.from(referencingEdges) const childId = child.getAttribute("id")
.map((e) => e.getAttribute("id")) if (childId && childId !== "0" && childId !== "1") {
.join(", ") collectDescendants(childId)
console.warn( }
`[applyDiagramOperations] Deleting cell "${op.cell_id}" which is referenced by edges: ${edgeIds}`, })
}
// Collect the target cell and all its descendants
collectDescendants(op.cell_id)
// Find edges referencing any of the cells to be deleted
// Also recursively collect children of those edges (e.g., edge labels)
for (const cellId of cellsToDelete) {
const referencingEdges = root.querySelectorAll(
`mxCell[source="${cellId}"], mxCell[target="${cellId}"]`,
)
referencingEdges.forEach((edge) => {
const edgeId = edge.getAttribute("id")
// Protect root cells from being added via edge references
if (edgeId && edgeId !== "0" && edgeId !== "1") {
// Recurse to collect edge's children (like labels)
collectDescendants(edgeId)
}
})
}
// Log what will be deleted
if (cellsToDelete.size > 1) {
console.log(
`[applyDiagramOperations] Cascade delete "${op.cell_id}" → deleting ${cellsToDelete.size} cells: ${Array.from(cellsToDelete).join(", ")}`,
) )
} }
// Remove the node // Delete all collected cells
existingCell.parentNode?.removeChild(existingCell) for (const cellId of cellsToDelete) {
cellMap.delete(op.cell_id) const cell = cellMap.get(cellId)
if (cell) {
cell.parentNode?.removeChild(cell)
cellMap.delete(cellId)
}
}
} }
} }

260
package-lock.json generated
View File

@@ -93,6 +93,11 @@
"typescript": "^5", "typescript": "^5",
"wait-on": "^9.0.3", "wait-on": "^9.0.3",
"wrangler": "4.54.0" "wrangler": "4.54.0"
},
"optionalDependencies": {
"@tailwindcss/oxide-linux-x64-gnu": "^4.1.18",
"lightningcss": "^1.30.2",
"lightningcss-linux-x64-gnu": "^1.30.2"
} }
}, },
"node_modules/@acemir/cssom": { "node_modules/@acemir/cssom": {
@@ -6012,6 +6017,111 @@
"node": ">= 10" "node": ">= 10"
} }
}, },
"node_modules/@next/swc-darwin-x64": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.1.1.tgz",
"integrity": "sha512-hbyKtrDGUkgkyQi1m1IyD3q4I/3m9ngr+V93z4oKHrPcmxwNL5iMWORvLSGAf2YujL+6HxgVvZuCYZfLfb4bGw==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.1.1.tgz",
"integrity": "sha512-/fvHet+EYckFvRLQ0jPHJCUI5/B56+2DpI1xDSvi80r/3Ez+Eaa2Yq4tJcRTaB1kqj/HrYKn8Yplm9bNoMJpwQ==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.1.1.tgz",
"integrity": "sha512-MFHrgL4TXNQbBPzkKKur4Fb5ICEJa87HM7fczFs2+HWblM7mMLdco3dvyTI+QmLBU9xgns/EeeINSZD6Ar+oLg==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.1.1.tgz",
"integrity": "sha512-20bYDfgOQAPUkkKBnyP9PTuHiJGM7HzNBbuqmD0jiFVZ0aOldz+VnJhbxzjcSabYsnNjMPsE0cyzEudpYxsrUQ==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.1.1.tgz",
"integrity": "sha512-9pRbK3M4asAHQRkwaXwu601oPZHghuSC8IXNENgbBSyImHv/zY4K5udBusgdHkvJ/Tcr96jJwQYOll0qU8+fPA==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.1.1.tgz",
"integrity": "sha512-bdfQkggaLgnmYrFkSQfsHfOhk/mCYmjnrbRCGgkMcoOBZ4n+TRRSLmT/CU5SATzlBJ9TpioUyBW/vWFXTqQRiA==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.1.1.tgz",
"integrity": "sha512-Ncwbw2WJ57Al5OX0k4chM68DKhEPlrXBaSXDCi2kPi5f4d8b3ejr3RRJGfKBLrn2YJL5ezNS7w2TZLHSti8CMw==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/third-parties": { "node_modules/@next/third-parties": {
"version": "16.1.1", "version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/third-parties/-/third-parties-16.1.1.tgz", "resolved": "https://registry.npmjs.org/@next/third-parties/-/third-parties-16.1.1.tgz",
@@ -8609,6 +8719,22 @@
"node": ">= 10" "node": ">= 10"
} }
}, },
"node_modules/@tailwindcss/oxide-linux-x64-gnu": {
"version": "4.1.18",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.1.18.tgz",
"integrity": "sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tailwindcss/postcss": { "node_modules/@tailwindcss/postcss": {
"version": "4.1.18", "version": "4.1.18",
"resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.1.18.tgz", "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.1.18.tgz",
@@ -15017,7 +15143,7 @@
"version": "1.30.2", "version": "1.30.2",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz",
"integrity": "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ==", "integrity": "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ==",
"dev": true, "devOptional": true,
"license": "MPL-2.0", "license": "MPL-2.0",
"dependencies": { "dependencies": {
"detect-libc": "^2.0.3" "detect-libc": "^2.0.3"
@@ -15050,7 +15176,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MPL-2.0", "license": "MPL-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -15064,6 +15189,26 @@
"url": "https://opencollective.com/parcel" "url": "https://opencollective.com/parcel"
} }
}, },
"node_modules/lightningcss-linux-x64-gnu": {
"version": "1.30.2",
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.30.2.tgz",
"integrity": "sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==",
"cpu": [
"x64"
],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 12.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
}
},
"node_modules/lint-staged": { "node_modules/lint-staged": {
"version": "16.2.7", "version": "16.2.7",
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-16.2.7.tgz", "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-16.2.7.tgz",
@@ -17867,9 +18012,9 @@
} }
}, },
"node_modules/qs": { "node_modules/qs": {
"version": "6.14.0", "version": "6.14.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
"integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
"side-channel": "^1.1.0" "side-channel": "^1.1.0"
@@ -21357,111 +21502,6 @@
"type": "github", "type": "github",
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
} }
},
"node_modules/@next/swc-darwin-x64": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.1.1.tgz",
"integrity": "sha512-hbyKtrDGUkgkyQi1m1IyD3q4I/3m9ngr+V93z4oKHrPcmxwNL5iMWORvLSGAf2YujL+6HxgVvZuCYZfLfb4bGw==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.1.1.tgz",
"integrity": "sha512-/fvHet+EYckFvRLQ0jPHJCUI5/B56+2DpI1xDSvi80r/3Ez+Eaa2Yq4tJcRTaB1kqj/HrYKn8Yplm9bNoMJpwQ==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.1.1.tgz",
"integrity": "sha512-MFHrgL4TXNQbBPzkKKur4Fb5ICEJa87HM7fczFs2+HWblM7mMLdco3dvyTI+QmLBU9xgns/EeeINSZD6Ar+oLg==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.1.1.tgz",
"integrity": "sha512-20bYDfgOQAPUkkKBnyP9PTuHiJGM7HzNBbuqmD0jiFVZ0aOldz+VnJhbxzjcSabYsnNjMPsE0cyzEudpYxsrUQ==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.1.1.tgz",
"integrity": "sha512-9pRbK3M4asAHQRkwaXwu601oPZHghuSC8IXNENgbBSyImHv/zY4K5udBusgdHkvJ/Tcr96jJwQYOll0qU8+fPA==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.1.1.tgz",
"integrity": "sha512-bdfQkggaLgnmYrFkSQfsHfOhk/mCYmjnrbRCGgkMcoOBZ4n+TRRSLmT/CU5SATzlBJ9TpioUyBW/vWFXTqQRiA==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.1.1.tgz",
"integrity": "sha512-Ncwbw2WJ57Al5OX0k4chM68DKhEPlrXBaSXDCi2kPi5f4d8b3ejr3RRJGfKBLrn2YJL5ezNS7w2TZLHSti8CMw==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
} }
} }
} }

View File

@@ -21,11 +21,11 @@
"electron:compile": "npx esbuild electron/main/index.ts electron/preload/index.ts electron/preload/settings.ts --bundle --platform=node --outdir=dist-electron --external:electron --sourcemap --packages=external && npx shx cp -r electron/settings dist-electron/", "electron:compile": "npx esbuild electron/main/index.ts electron/preload/index.ts electron/preload/settings.ts --bundle --platform=node --outdir=dist-electron --external:electron --sourcemap --packages=external && npx shx cp -r electron/settings dist-electron/",
"electron:start": "npx cross-env NODE_ENV=development npx electron .", "electron:start": "npx cross-env NODE_ENV=development npx electron .",
"electron:prepare": "node scripts/prepare-electron-build.mjs", "electron:prepare": "node scripts/prepare-electron-build.mjs",
"dist": "npm run electron:build && npm run electron:prepare && npx electron-builder", "dist": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml",
"dist:mac": "npm run electron:build && npm run electron:prepare && npx electron-builder --mac", "dist:mac": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml --mac",
"dist:win": "npm run electron:build && npm run electron:prepare && npx electron-builder --win", "dist:win": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml --win",
"dist:linux": "npm run electron:build && npm run electron:prepare && npx electron-builder --linux", "dist:linux": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml --linux",
"dist:all": "npm run electron:build && npm run electron:prepare && npx electron-builder --mac --win --linux" "dist:all": "npm run electron:build && npm run electron:prepare && npx electron-builder --config electron/electron-builder.yml --mac --win --linux"
}, },
"dependencies": { "dependencies": {
"@ai-sdk/amazon-bedrock": "^4.0.1", "@ai-sdk/amazon-bedrock": "^4.0.1",
@@ -88,6 +88,11 @@
"unpdf": "^1.4.0", "unpdf": "^1.4.0",
"zod": "^4.1.12" "zod": "^4.1.12"
}, },
"optionalDependencies": {
"lightningcss": "^1.30.2",
"lightningcss-linux-x64-gnu": "^1.30.2",
"@tailwindcss/oxide-linux-x64-gnu": "^4.1.18"
},
"lint-staged": { "lint-staged": {
"*.{js,ts,jsx,tsx,json,css}": [ "*.{js,ts,jsx,tsx,json,css}": [
"biome check --write --no-errors-on-unmatched", "biome check --write --no-errors-on-unmatched",

View File

@@ -97,7 +97,7 @@ Use the standard MCP configuration with:
| Tool | Description | | Tool | Description |
|------|-------------| |------|-------------|
| `start_session` | Opens browser with real-time diagram preview | | `start_session` | Opens browser with real-time diagram preview |
| `display_diagram` | Create a new diagram from XML | | `create_new_diagram` | Create a new diagram from XML (requires `xml` argument) |
| `edit_diagram` | Edit diagram by ID-based operations (update/add/delete cells) | | `edit_diagram` | Edit diagram by ID-based operations (update/add/delete cells) |
| `get_diagram` | Get the current diagram XML | | `get_diagram` | Get the current diagram XML |
| `export_diagram` | Save diagram to a `.drawio` file | | `export_diagram` | Save diagram to a `.drawio` file |

View File

@@ -1,18 +1,18 @@
{ {
"name": "@next-ai-drawio/mcp-server", "name": "@next-ai-drawio/mcp-server",
"version": "0.1.6", "version": "0.1.11",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@next-ai-drawio/mcp-server", "name": "@next-ai-drawio/mcp-server",
"version": "0.1.6", "version": "0.1.11",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "^1.0.4", "@modelcontextprotocol/sdk": "^1.0.4",
"linkedom": "^0.18.0", "linkedom": "^0.18.0",
"open": "^11.0.0", "open": "^11.0.0",
"zod": "^3.24.0" "zod": "^4.0.0"
}, },
"bin": { "bin": {
"next-ai-drawio-mcp": "dist/index.js" "next-ai-drawio-mcp": "dist/index.js"
@@ -2051,9 +2051,9 @@
} }
}, },
"node_modules/zod": { "node_modules/zod": {
"version": "3.25.76", "version": "4.3.4",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.4.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "integrity": "sha512-Zw/uYiiyF6pUT1qmKbZziChgNPRu+ZRneAsMUDU6IwmXdWt5JwcUfy2bvLOCUtz5UniaN/Zx5aFttZYbYc7O/A==",
"license": "MIT", "license": "MIT",
"peer": true, "peer": true,
"funding": { "funding": {

View File

@@ -1,6 +1,6 @@
{ {
"name": "@next-ai-drawio/mcp-server", "name": "@next-ai-drawio/mcp-server",
"version": "0.1.6", "version": "0.1.11",
"description": "MCP server for Next AI Draw.io - AI-powered diagram generation with real-time browser preview", "description": "MCP server for Next AI Draw.io - AI-powered diagram generation with real-time browser preview",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
@@ -39,7 +39,7 @@
"@modelcontextprotocol/sdk": "^1.0.4", "@modelcontextprotocol/sdk": "^1.0.4",
"linkedom": "^0.18.0", "linkedom": "^0.18.0",
"open": "^11.0.0", "open": "^11.0.0",
"zod": "^3.24.0" "zod": "^4.0.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",

View File

@@ -182,32 +182,77 @@ export function applyDiagramOperations(
// Add to map // Add to map
cellMap.set(op.cell_id, importedNode) cellMap.set(op.cell_id, importedNode)
} else if (op.operation === "delete") { } else if (op.operation === "delete") {
const existingCell = cellMap.get(op.cell_id) // Protect root cells from deletion
if (!existingCell) { if (op.cell_id === "0" || op.cell_id === "1") {
errors.push({ errors.push({
type: "delete", type: "delete",
cellId: op.cell_id, cellId: op.cell_id,
message: `Cell with id="${op.cell_id}" not found`, message: `Cannot delete root cell "${op.cell_id}"`,
}) })
continue continue
} }
// Check for edges referencing this cell (warning only, still delete) const existingCell = cellMap.get(op.cell_id)
const referencingEdges = root.querySelectorAll( if (!existingCell) {
`mxCell[source="${op.cell_id}"], mxCell[target="${op.cell_id}"]`, // Cell not found - might have been cascade-deleted by a previous operation
// Skip silently instead of erroring (AI may redundantly list children/edges)
continue
}
// Cascade delete: collect all cells to delete (children + edges + self)
const cellsToDelete = new Set<string>()
// Recursive function to find all descendants
const collectDescendants = (cellId: string) => {
if (cellsToDelete.has(cellId)) return
cellsToDelete.add(cellId)
// Find children (cells where parent === cellId)
const children = root.querySelectorAll(
`mxCell[parent="${cellId}"]`,
) )
if (referencingEdges.length > 0) { children.forEach((child) => {
const edgeIds = Array.from(referencingEdges) const childId = child.getAttribute("id")
.map((e) => e.getAttribute("id")) if (childId && childId !== "0" && childId !== "1") {
.join(", ") collectDescendants(childId)
console.warn( }
`[applyDiagramOperations] Deleting cell "${op.cell_id}" which is referenced by edges: ${edgeIds}`, })
}
// Collect the target cell and all its descendants
collectDescendants(op.cell_id)
// Find edges referencing any of the cells to be deleted
// Also recursively collect children of those edges (e.g., edge labels)
for (const cellId of cellsToDelete) {
const referencingEdges = root.querySelectorAll(
`mxCell[source="${cellId}"], mxCell[target="${cellId}"]`,
)
referencingEdges.forEach((edge) => {
const edgeId = edge.getAttribute("id")
// Protect root cells from being added via edge references
if (edgeId && edgeId !== "0" && edgeId !== "1") {
// Recurse to collect edge's children (like labels)
collectDescendants(edgeId)
}
})
}
// Log what will be deleted
if (cellsToDelete.size > 1) {
console.log(
`[applyDiagramOperations] Cascade delete "${op.cell_id}" → deleting ${cellsToDelete.size} cells: ${Array.from(cellsToDelete).join(", ")}`,
) )
} }
// Remove the node // Delete all collected cells
existingCell.parentNode?.removeChild(existingCell) for (const cellId of cellsToDelete) {
cellMap.delete(op.cell_id) const cell = cellMap.get(cellId)
if (cell) {
cell.parentNode?.removeChild(cell)
cellMap.delete(cellId)
}
}
} }
} }

View File

@@ -127,7 +127,12 @@ function cleanupExpiredSessions(): void {
} }
} }
setInterval(cleanupExpiredSessions, 5 * 60 * 1000) const cleanupIntervalId = setInterval(cleanupExpiredSessions, 5 * 60 * 1000)
export function shutdown(): void {
clearInterval(cleanupIntervalId)
stopHttpServer()
}
export function getServerPort(): number { export function getServerPort(): number {
return serverPort return serverPort

View File

@@ -39,6 +39,7 @@ import {
getState, getState,
requestSync, requestSync,
setState, setState,
shutdown,
startHttpServer, startHttpServer,
waitForSync, waitForSync,
} from "./http-server.js" } from "./http-server.js"
@@ -47,7 +48,7 @@ import { validateAndFixXml } from "./xml-validation.js"
// Server configuration // Server configuration
const config = { const config = {
port: parseInt(process.env.PORT || "6002"), port: parseInt(process.env.PORT || "6002", 10),
} }
// Session state (single session for simplicity) // Session state (single session for simplicity)
@@ -78,7 +79,7 @@ server.prompt(
## Creating a New Diagram ## Creating a New Diagram
1. Call start_session to open the browser preview 1. Call start_session to open the browser preview
2. Use display_diagram with complete mxGraphModel XML to create a new diagram 2. Use create_new_diagram with complete mxGraphModel XML to create a new diagram
## Adding Elements to Existing Diagram ## Adding Elements to Existing Diagram
1. Use edit_diagram with "add" operation 1. Use edit_diagram with "add" operation
@@ -91,7 +92,7 @@ server.prompt(
3. For update, provide the cell_id and complete new mxCell XML 3. For update, provide the cell_id and complete new mxCell XML
## Important Notes ## Important Notes
- display_diagram REPLACES the entire diagram - only use for new diagrams - create_new_diagram REPLACES the entire diagram - only use for new diagrams
- edit_diagram PRESERVES user's manual changes (fetches browser state first) - edit_diagram PRESERVES user's manual changes (fetches browser state first)
- Always use unique cell_ids when adding elements (e.g., "shape-1", "arrow-2")`, - Always use unique cell_ids when adding elements (e.g., "shape-1", "arrow-2")`,
}, },
@@ -150,19 +151,59 @@ server.registerTool(
}, },
) )
// Tool: display_diagram // Tool: create_new_diagram
server.registerTool( server.registerTool(
"display_diagram", "create_new_diagram",
{ {
description: description: `Create a NEW diagram from mxGraphModel XML. Use this when creating a diagram from scratch or replacing the current diagram entirely.
"Display a NEW draw.io diagram from XML. REPLACES the entire diagram. " +
"Use this for creating new diagrams from scratch. " + CRITICAL: You MUST provide the 'xml' argument in EVERY call. Do NOT call this tool without xml.
"To ADD elements to an existing diagram, use edit_diagram with 'add' operation instead. " +
"You should generate valid draw.io/mxGraph XML format.", When to use this tool:
- Creating a new diagram from scratch
- Replacing the current diagram with a completely different one
- Major structural changes that require regenerating the diagram
When to use edit_diagram instead:
- Small modifications to existing diagram
- Adding/removing individual elements
- Changing labels, colors, or positions
XML FORMAT - Full mxGraphModel structure:
<mxGraphModel>
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" value="Shape" style="rounded=1;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
LAYOUT CONSTRAINTS:
- Keep all elements within x=0-800, y=0-600 (single page viewport)
- Start from margins (x=40, y=40), keep elements grouped closely
- Use unique IDs starting from "2" (0 and 1 are reserved)
- Set parent="1" for top-level shapes
- Space shapes 150-200px apart for clear edge routing
EDGE ROUTING RULES:
- Never let multiple edges share the same path - use different exitY/entryY values
- For bidirectional connections (A↔B), use OPPOSITE sides
- Always specify exitX, exitY, entryX, entryY explicitly in edge style
- Route edges AROUND obstacles using waypoints (add 20-30px clearance)
- Use natural connection points based on flow (not corners)
COMMON STYLES:
- Shapes: rounded=1; fillColor=#hex; strokeColor=#hex
- Edges: endArrow=classic; edgeStyle=orthogonalEdgeStyle; curved=1
- Text: fontSize=14; fontStyle=1 (bold); align=center`,
inputSchema: { inputSchema: {
xml: z xml: z
.string() .string()
.describe("The draw.io XML to display (mxGraphModel format)"), .describe(
"REQUIRED: The complete mxGraphModel XML. Must always be provided.",
),
}, },
}, },
async ({ xml: inputXml }) => { async ({ xml: inputXml }) => {
@@ -199,7 +240,7 @@ server.registerTool(
} }
} }
log.info(`Displaying diagram, ${xml.length} chars`) log.info(`Setting diagram content, ${xml.length} chars`)
// Sync from browser state first // Sync from browser state first
const browserState = getState(currentSession.id) const browserState = getState(currentSession.id)
@@ -226,20 +267,20 @@ server.registerTool(
// Save AI result (no SVG yet - will be captured by browser) // Save AI result (no SVG yet - will be captured by browser)
addHistory(currentSession.id, xml, "") addHistory(currentSession.id, xml, "")
log.info(`Diagram displayed successfully`) log.info(`Diagram content set successfully`)
return { return {
content: [ content: [
{ {
type: "text", type: "text",
text: `Diagram displayed successfully!\n\nThe diagram is now visible in your browser.\n\nXML length: ${xml.length} characters`, text: `Diagram content set successfully!\n\nThe diagram is now visible in your browser.\n\nXML length: ${xml.length} characters`,
}, },
], ],
} }
} catch (error) { } catch (error) {
const message = const message =
error instanceof Error ? error.message : String(error) error instanceof Error ? error.message : String(error)
log.error("display_diagram failed:", message) log.error("create_new_diagram failed:", message)
return { return {
content: [{ type: "text", text: `Error: ${message}` }], content: [{ type: "text", text: `Error: ${message}` }],
isError: true, isError: true,
@@ -340,7 +381,7 @@ server.registerTool(
content: [ content: [
{ {
type: "text", type: "text",
text: "Error: No diagram to edit. Please create a diagram first with display_diagram.", text: "Error: No diagram to edit. Please create a diagram first with create_new_diagram.",
}, },
], ],
isError: true, isError: true,
@@ -474,7 +515,7 @@ server.registerTool(
content: [ content: [
{ {
type: "text", type: "text",
text: "No diagram exists yet. Use display_diagram to create one.", text: "No diagram exists yet. Use create_new_diagram to create one.",
}, },
], ],
} }
@@ -578,6 +619,31 @@ server.registerTool(
}, },
) )
// Graceful shutdown handler
let isShuttingDown = false
function gracefulShutdown(reason: string) {
if (isShuttingDown) return
isShuttingDown = true
log.info(`Shutting down: ${reason}`)
shutdown()
process.exit(0)
}
// Handle stdin close (primary method - works on all platforms including Windows)
process.stdin.on("close", () => gracefulShutdown("stdin closed"))
process.stdin.on("end", () => gracefulShutdown("stdin ended"))
// Handle signals (may not work reliably on Windows)
process.on("SIGINT", () => gracefulShutdown("SIGINT"))
process.on("SIGTERM", () => gracefulShutdown("SIGTERM"))
// Handle broken pipe (writing to closed stdout)
process.stdout.on("error", (err) => {
if (err.code === "EPIPE" || err.code === "ERR_STREAM_DESTROYED") {
gracefulShutdown("stdout error")
}
})
// Start the MCP server // Start the MCP server
async function main() { async function main() {
log.info("Starting MCP server for Next AI Draw.io (embedded mode)...") log.info("Starting MCP server for Next AI Draw.io (embedded mode)...")

View File

@@ -253,7 +253,7 @@ async function main() {
}, },
) )
console.log("👀 Watching for preset configuration changes...") console.log("👀 Watching for preset configuration changes...")
} catch (err) { } catch (_err) {
// File might not exist yet, that's ok // File might not exist yet, that's ok
setTimeout(setupConfigWatcher, 5000) setTimeout(setupConfigWatcher, 5000)
} }

View File

@@ -22,6 +22,7 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"files": ["electron/electron.d.ts"],
"include": [ "include": [
"next-env.d.ts", "next-env.d.ts",
"**/*.ts", "**/*.ts",