mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-10-11 03:59:58 +08:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1067cba4d9 | ||
|
|
2757509d4e | ||
|
|
cd5352ca88 | ||
|
|
498ee628f1 | ||
|
|
a6e812d3a5 | ||
|
|
02eaa0bd22 | ||
|
|
4cba863fd9 | ||
|
|
7682e479e3 | ||
|
|
a7ae114edf | ||
|
|
e117095c7b | ||
|
|
f0f0bc0dc0 | ||
|
|
d5096b9628 | ||
|
|
2418c47764 | ||
|
|
04d34534fd | ||
|
|
17ea4811fb | ||
|
|
c513d1a0c2 | ||
|
|
18a20aa1ca | ||
|
|
802f0ada9f | ||
|
|
257a4bca06 | ||
|
|
83f190e1cd | ||
|
|
8639779a23 |
@@ -34,15 +34,7 @@ jobs:
|
||||
node-version: 24
|
||||
cache: "npm"
|
||||
|
||||
- name: Download draw.io static files for offline use
|
||||
run: |
|
||||
rm -rf public/drawio
|
||||
git clone --depth 1 https://github.com/jgraph/drawio.git /tmp/drawio
|
||||
mkdir -p public/drawio
|
||||
cp -r /tmp/drawio/src/main/webapp/* public/drawio/
|
||||
rm -rf public/drawio/WEB-INF
|
||||
rm -rf public/drawio/META-INF
|
||||
|
||||
# npm run build downloads draw.io first (prebuild)
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
@@ -66,16 +58,7 @@ jobs:
|
||||
node-version: 24
|
||||
cache: "npm"
|
||||
|
||||
- name: Download draw.io static files for offline use
|
||||
shell: bash
|
||||
run: |
|
||||
rm -rf public/drawio
|
||||
git clone --depth 1 https://github.com/jgraph/drawio.git /tmp/drawio
|
||||
mkdir -p public/drawio
|
||||
cp -r /tmp/drawio/src/main/webapp/* public/drawio/
|
||||
rm -rf public/drawio/WEB-INF
|
||||
rm -rf public/drawio/META-INF
|
||||
|
||||
# npm run build downloads draw.io first (prebuild)
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
@@ -103,6 +86,9 @@ jobs:
|
||||
artifact-configuration-slug: 'windows-exe'
|
||||
github-artifact-id: ${{ steps.upload-unsigned.outputs.artifact-id }}
|
||||
wait-for-completion: true
|
||||
# The release-signing policy needs a manual approval in SignPath;
|
||||
# the default 600 s wait made the job fail before anyone could approve.
|
||||
wait-for-completion-timeout-in-seconds: 3600
|
||||
output-artifact-directory: release-signed
|
||||
|
||||
- name: Upload signed artifacts to release
|
||||
|
||||
@@ -43,8 +43,14 @@ jobs:
|
||||
run: npm --prefix packages/mcp-server run build && npm --prefix packages/mcp-server run check-package
|
||||
|
||||
e2e:
|
||||
name: E2E Tests
|
||||
# Six jobs at once, each with a sixth of the tests and one worker: the
|
||||
# same conditions per test, a fraction of the time
|
||||
name: E2E Tests (${{ matrix.shard }}/6)
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
@@ -76,7 +82,7 @@ jobs:
|
||||
run: npm run build
|
||||
|
||||
- name: Run E2E tests
|
||||
run: npm run test:e2e
|
||||
run: npm run test:e2e -- --shard=${{ matrix.shard }}/6
|
||||
env:
|
||||
CI: true
|
||||
|
||||
@@ -84,6 +90,6 @@ jobs:
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
name: playwright-report-${{ matrix.shard }}
|
||||
path: playwright-report/
|
||||
retention-days: 7
|
||||
|
||||
+3
-2
@@ -23,8 +23,9 @@ COPY . .
|
||||
# Disable Next.js telemetry during build
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
# Build-time argument for self-hosted draw.io URL
|
||||
ARG NEXT_PUBLIC_DRAWIO_BASE_URL=https://embed.diagrams.net
|
||||
# Build-time argument for an external draw.io URL. Leave empty to use the
|
||||
# copy bundled into public/drawio (downloaded by `npm run build`)
|
||||
ARG NEXT_PUBLIC_DRAWIO_BASE_URL=""
|
||||
ENV NEXT_PUBLIC_DRAWIO_BASE_URL=${NEXT_PUBLIC_DRAWIO_BASE_URL}
|
||||
|
||||
# Build-time argument to show About link and Notice icon
|
||||
|
||||
@@ -1,120 +1,98 @@
|
||||
# Next AI Draw.io
|
||||
|
||||
<div align="center">
|
||||
|
||||
**AI-Powered Diagram Creation Tool - Chat, Draw, Visualize**
|
||||
# Next AI Draw.io
|
||||
|
||||
**Draw and edit draw.io diagrams by chatting with an AI.**
|
||||
|
||||
English | [中文](./docs/cn/README_CN.md) | [日本語](./docs/ja/README_JA.md)
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
[](https://nextjs.org/)
|
||||
[](https://react.dev/)
|
||||
[](https://github.com/sponsors/DayuanJiang)
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
[**Live Demo**](https://next-ai-drawio.jiang.jp/) · [**Desktop App**](https://github.com/DayuanJiang/next-ai-draw-io/releases) · [**MCP Server**](#in-your-ai-agent-mcp)
|
||||
|
||||
</div>
|
||||
|
||||
A Next.js web application that integrates AI capabilities with draw.io diagrams. Create, modify, and enhance diagrams through natural language commands and AI-assisted visualization.
|
||||
https://github.com/user-attachments/assets/66b9f12f-219f-4d62-acc0-0725e6850eec
|
||||
|
||||
> Note: Thanks to <img src="https://raw.githubusercontent.com/DayuanJiang/next-ai-draw-io/main/public/doubao-color.png" alt="" height="20" /> [ByteDance Doubao](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio) sponsorship, the demo site now uses the powerful glm-4.7 model!
|
||||
Describe a diagram in a sentence and the AI draws it on a real draw.io canvas. Edit it by hand like any draw.io file, or select a few shapes and tell the AI what to change. Every AI change is a version you can compare, restore or undo, and the result exports as `.drawio`, `.png` or `.svg`.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.atlascloud.ai/?utm_source=github&utm_medium=link&utm_campaign=next-ai-draw-io">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./public/atlas-cloud-logo-white.svg">
|
||||
<img src="./public/atlas-cloud-logo.svg" alt="Atlas Cloud" width="200">
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
Available as a web app, a desktop app for Windows, macOS and Linux, and an MCP server for AI agents such as Claude Code, Cursor and VS Code.
|
||||
|
||||
> 🎁 Thanks to **[Atlas Cloud](https://www.atlascloud.ai/?utm_source=github&utm_medium=link&utm_campaign=next-ai-draw-io)** for sponsoring next-ai-draw-io. Its OpenAI-compatible API gives diagram workflows one provider connection for DeepSeek, Qwen, GLM, Kimi, MiniMax, and more. Budget-friendly access is available through the [Coding Plan](https://www.atlascloud.ai/console/coding-plan).
|
||||
## Highlights
|
||||
|
||||
**Draw**
|
||||
|
||||
https://github.com/user-attachments/assets/9d60a3e8-4a1c-4b5e-acbb-26af2d3eabd1
|
||||
- Architecture diagrams, flowcharts, sequence diagrams and more from one sentence, with built-in AWS, Azure, GCP and Kubernetes icon libraries
|
||||
- Connectors can carry a flowing animation
|
||||
- Upload a screenshot or a sketch and the AI redraws it; upload PDF, Markdown, code and other text files and get a diagram of their content
|
||||
|
||||
**Edit**
|
||||
|
||||
- Edit by chat: changes stream onto the canvas and the shapes the AI just changed are highlighted
|
||||
- Ask about a selection: select shapes on the canvas and the AI changes only those
|
||||
- Versions and undo: every AI change is a version card with a thumbnail; compare it with the canvas, restore it or undo it, and Ctrl+Z on the canvas also takes back an AI change in one step
|
||||
- It is a normal draw.io diagram: double-click to rename, drag, restyle, use several pages, and export as `.drawio`, `.png`, `.svg` or `.drawio.svg` at any time
|
||||
|
||||
## Table of Contents
|
||||
- [Next AI Draw.io](#next-ai-drawio)
|
||||
- [Table of Contents](#table-of-contents)
|
||||
- [Examples](#examples)
|
||||
- [Features](#features)
|
||||
- [MCP Server](#mcp-server)
|
||||
- [Claude Code CLI](#claude-code-cli)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Try it Online](#try-it-online)
|
||||
- [Desktop Application](#desktop-application)
|
||||
- [Run with Docker](#run-with-docker)
|
||||
- [Installation](#installation)
|
||||
- [Deployment](#deployment)
|
||||
- [Deploy to EdgeOne Pages](#deploy-to-edgeone-pages)
|
||||
- [Deploy on Vercel](#deploy-on-vercel)
|
||||
- [Deploy on Cloudflare Workers](#deploy-on-cloudflare-workers)
|
||||
- [Multi-Provider Support](#multi-provider-support)
|
||||
- [Server-Side Multi-Model Configuration](#server-side-multi-model-configuration)
|
||||
- [Admin Panel](#admin-panel)
|
||||
- [How It Works](#how-it-works)
|
||||
- [Support \& Contact](#support--contact)
|
||||
- [FAQ](#faq)
|
||||
- [Star History](#star-history)
|
||||
**Use**
|
||||
|
||||
- 24 model providers; enter your own API key in the browser and it stays on your machine
|
||||
- Models that reason show their thinking
|
||||
- Dark mode; the interface is available in English, Simplified Chinese, Traditional Chinese and Japanese
|
||||
|
||||
## Examples
|
||||
|
||||
Here are some example prompts and their generated diagrams:
|
||||
|
||||
<div align="center">
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td colspan="2" valign="top" align="center">
|
||||
<strong>Animated transformer connectors</strong><br />
|
||||
<p><strong>Prompt:</strong> Give me a **animated connector** diagram of transformer's architecture.</p>
|
||||
<img src="./public/animated_connectors.svg" alt="Transformer Architecture with Animated Connectors" width="480" />
|
||||
<strong>Transformer architecture with animated connectors</strong><br />
|
||||
<p><strong>Prompt:</strong> Give me a <strong>animated connector</strong> diagram of transformer's architecture.</p>
|
||||
<img src="./public/animated_connectors.svg" alt="Transformer architecture with animated connectors" width="440" />
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<strong>RAG Technique Diagram</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate a RAG architecture diagram for **chat application**. Use connected diagram for data ingestion</p>
|
||||
<img src="./public/rag_prod.svg" alt="RAG Architecture Diagram" width="480" />
|
||||
<strong>RAG architecture</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate a RAG architecture diagram for <strong>chat application</strong>. Use connected diagram for data ingestion</p>
|
||||
<img src="./public/rag_prod.svg" alt="RAG architecture diagram" width="400" />
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<strong>Authentication using React and AWS</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate authentication process using React with **AWS**. Use Serverless architecture.</p>
|
||||
<img src="./public/auth.svg" alt="Authentication Architecture Diagram" width="480" />
|
||||
<strong>Authentication with React and AWS</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate authentication process using React with <strong>AWS</strong>. Use Serverless architecture.</p>
|
||||
<img src="./public/auth.svg" alt="Authentication architecture diagram" width="400" />
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<strong>Open Innovation</strong><br />
|
||||
<strong>Open Innovation model</strong><br />
|
||||
<p><strong>Prompt:</strong> Create visualization of Henry Chesbrough's Open Innovation model.</p>
|
||||
<img src="./public/inno.svg" alt="Open Innovation Diagram" width="480" />
|
||||
<img src="./public/inno.svg" alt="Open Innovation diagram" width="400" />
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<strong>Cat sketch</strong><br />
|
||||
<p><strong>Prompt:</strong> Draw a cute cat for me.</p>
|
||||
<img src="./public/cat_demo.svg" alt="Cat Drawing" width="240" />
|
||||
<img src="./public/cat_demo.svg" alt="Cat drawing" width="200" />
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
## Features
|
||||
## Use it
|
||||
|
||||
- **LLM-Powered Diagram Creation**: Leverage Large Language Models to create and manipulate draw.io diagrams directly through natural language commands
|
||||
- **Image-Based Diagram Replication**: Upload existing diagrams or images and have the AI replicate and enhance them automatically
|
||||
- **PDF & Text File Upload**: Upload PDF documents and text files to extract content and generate diagrams from existing documents
|
||||
- **AI Reasoning Display**: View the AI's thinking process for supported models (OpenAI o1/o3, Gemini, Claude, etc.)
|
||||
- **Diagram History**: Comprehensive version control that tracks all changes, allowing you to view and restore previous versions of your diagrams before the AI editing.
|
||||
- **Interactive Chat Interface**: Communicate with AI to refine your diagrams in real-time
|
||||
- **Cloud Architecture Diagram Support**: Specialized support for generating cloud architecture diagrams (AWS, GCP, Azure)
|
||||
- **Animated Connectors**: Create dynamic and animated connectors between diagram elements for better visualization
|
||||
### Online demo
|
||||
|
||||
## MCP Server
|
||||
Open [next-ai-drawio.jiang.jp](https://next-ai-drawio.jiang.jp/), nothing to install. The demo has a usage limit; click the settings icon in the chat panel and enter your own provider and API key to lift it. The key stays in your browser and is never sent to the server for storage.
|
||||
|
||||
Use Next AI Draw.io with AI agents like Claude Desktop, Cursor, and VS Code via MCP (Model Context Protocol).
|
||||
### Desktop app
|
||||
|
||||
Download the Windows, macOS or Linux installer from the [Releases page](https://github.com/DayuanJiang/next-ai-draw-io/releases).
|
||||
|
||||
### In your AI agent (MCP)
|
||||
|
||||
Through MCP (Model Context Protocol, the protocol AI agents use to call outside tools), Claude Desktop, Cursor, VS Code and others can draw draw.io diagrams directly. Add this to your client's MCP configuration:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -127,165 +105,61 @@ Use Next AI Draw.io with AI agents like Claude Desktop, Cursor, and VS Code via
|
||||
}
|
||||
```
|
||||
|
||||
### Claude Code CLI
|
||||
For Claude Code, one command does it:
|
||||
|
||||
```bash
|
||||
claude mcp add drawio -- npx @next-ai-drawio/mcp-server@latest
|
||||
```
|
||||
|
||||
Then ask Claude to create diagrams:
|
||||
> "Create a flowchart showing user authentication with login, MFA, and session management"
|
||||
Then ask the AI for "a flowchart of user authentication with login, MFA and session management" and the diagram appears in your browser as it is drawn. The MCP server has most of the web app's drawing features:
|
||||
|
||||
The diagram appears in your browser in real-time!
|
||||
- The same drawing rules and icon libraries (AWS, Azure, GCP, Kubernetes and more)
|
||||
- A screenshot tool, so the AI can look at the rendered diagram and fix it
|
||||
- Version history, multi-page diagrams, and download as `.drawio`, `.png`, `.svg` or `.drawio.svg`
|
||||
- Auto-save to `~/.next-ai-drawio/`, so a diagram survives a restart
|
||||
|
||||
The MCP server includes most of the web app's drawing features:
|
||||
See the [MCP server README](./packages/mcp-server/README.md) for VS Code, Cursor and other client configurations.
|
||||
|
||||
- The same drawing rules and shape libraries (AWS, Azure, GCP, Kubernetes and more)
|
||||
- A screenshot tool, so the AI can check the rendered diagram and fix it
|
||||
- Version history, multi-page diagrams, and download as `.drawio`, `.png`, `.svg`, or `.drawio.svg`
|
||||
- Auto-save to `~/.next-ai-drawio/`, so you can continue a diagram after a restart
|
||||
## Self-host
|
||||
|
||||
See the [MCP Server README](./packages/mcp-server/README.md) for VS Code, Cursor, and other client configurations.
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Try it Online
|
||||
|
||||
No installation needed! Try the app directly on our demo site:
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
|
||||
|
||||
> **Bring Your Own API Key**: You can use your own API key to bypass usage limits on the demo site. Click the Settings icon in the chat panel to configure your provider and API key. Your key is stored locally in your browser and is never stored on the server.
|
||||
|
||||
### Desktop Application
|
||||
|
||||
Download the native desktop app for your platform from the [Releases page](https://github.com/DayuanJiang/next-ai-draw-io/releases):
|
||||
|
||||
Supported platforms: Windows, macOS, Linux.
|
||||
|
||||
### Run with Docker
|
||||
|
||||
[Go to Docker Guide](./docs/en/docker.md)
|
||||
|
||||
### Installation
|
||||
|
||||
1. Clone the repository:
|
||||
### Run locally
|
||||
|
||||
```bash
|
||||
git clone https://github.com/DayuanJiang/next-ai-draw-io
|
||||
cd next-ai-draw-io
|
||||
npm install
|
||||
cp env.example .env.local
|
||||
```
|
||||
|
||||
See the [Provider Configuration Guide](./docs/en/ai-providers.md) for detailed setup instructions for each provider.
|
||||
|
||||
2. Run the development server:
|
||||
|
||||
```bash
|
||||
cp env.example .env.local # add your provider and API key, see "Models and providers" below
|
||||
npm run dev
|
||||
```
|
||||
|
||||
3. Open [http://localhost:6002](http://localhost:6002) in your browser to see the application.
|
||||
Open [http://localhost:6002](http://localhost:6002).
|
||||
|
||||
## Deployment
|
||||
### One-click deploy
|
||||
|
||||
### Deploy to EdgeOne Pages
|
||||
| Platform | How |
|
||||
| --- | --- |
|
||||
| Tencent EdgeOne Pages | [](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io) Deploying there also gives you a [daily free quota for DeepSeek models](https://pages.edgeone.ai/document/edge-ai) |
|
||||
| Vercel | [](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io) Set the same environment variables in the Vercel dashboard as in your `.env.local` |
|
||||
| Cloudflare Workers | [Cloudflare deploy guide](./docs/en/cloudflare-deploy.md) |
|
||||
| Docker | [Docker guide](./docs/en/docker.md) |
|
||||
| Offline or intranet | [Offline deployment](./docs/en/offline-deployment.md) |
|
||||
|
||||
You can deploy with one click using [Tencent EdgeOne Pages](https://pages.edgeone.ai/).
|
||||
### Models and providers
|
||||
|
||||
Deploy by this button:
|
||||
24 providers are supported: AWS Bedrock (default), OpenAI, Anthropic, Google AI, Google Vertex AI, Azure OpenAI, Ollama, OpenRouter, AIHubMix, DeepSeek, SiliconFlow, SGLang, Vercel AI Gateway, Tencent EdgeOne, ByteDance Doubao, ModelScope, Zhipu GLM, Qwen, Qiniu, Kimi, MiniMax, Novita, Xiaomi MiMo and Atlas Cloud. The environment variables and notes for each are in the [provider configuration guide](./docs/en/ai-providers.md).
|
||||
|
||||
[](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
**Which model**: the task is to produce long text in a strict format (draw.io XML), so pick a capable model; small models tend to produce broken diagrams.
|
||||
|
||||
Check out the [Tencent EdgeOne Pages documentation](https://pages.edgeone.ai/document/deployment-overview) for more details.
|
||||
**Several models and the admin panel**: list several model IDs in `AI_MODEL` separated by commas, or configure models from several providers with the `AI_MODELS_CONFIG` environment variable or an `ai-models.json` file, and every user can use them without a key of their own. Set `ADMIN_PASSWORD` and open `/admin` to manage models, access codes, feature switches, observability and quotas from a web page; see the [admin panel guide](./docs/en/admin-panel.md).
|
||||
|
||||
Additionally, deploying through Tencent EdgeOne Pages will also grant you a [daily free quota for DeepSeek models](https://pages.edgeone.ai/document/edge-ai).
|
||||
## Support
|
||||
|
||||
### Deploy on Vercel
|
||||
- Questions and ideas: open a [GitHub issue](https://github.com/DayuanJiang/next-ai-draw-io/issues) or email me[at]jiang.jp
|
||||
- Common problems: [FAQ](./docs/en/FAQ.md)
|
||||
- If the project is useful to you, consider [sponsoring](https://github.com/sponsors/DayuanJiang) to help keep the demo site running
|
||||
|
||||
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
|
||||
The easiest way to deploy is using [Vercel](https://vercel.com/new), the creators of Next.js. Be sure to **set the environment variables** in the Vercel dashboard as you did in your local `.env.local` file.
|
||||
|
||||
See the [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
|
||||
### Deploy on Cloudflare Workers
|
||||
|
||||
[Go to Cloudflare Deploy Guide](./docs/en/cloudflare-deploy.md)
|
||||
|
||||
|
||||
|
||||
## Multi-Provider Support
|
||||
|
||||
- [ByteDance Doubao](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio)
|
||||
- AWS Bedrock (default)
|
||||
- OpenAI
|
||||
- Anthropic
|
||||
- Google AI
|
||||
- Google Vertex AI
|
||||
- Azure OpenAI
|
||||
- Ollama
|
||||
- OpenRouter
|
||||
- AIHubMix
|
||||
- DeepSeek
|
||||
- SiliconFlow
|
||||
- ModelScope
|
||||
- SGLang
|
||||
- Vercel AI Gateway
|
||||
- [Atlas Cloud](https://www.atlascloud.ai/?utm_source=github&utm_medium=link&utm_campaign=next-ai-draw-io)
|
||||
|
||||
|
||||
All providers except AWS Bedrock and OpenRouter support custom endpoints.
|
||||
|
||||
📖 **[Detailed Provider Configuration Guide](./docs/en/ai-providers.md)** - See setup instructions for each provider.
|
||||
|
||||
### Server-Side Multi-Model Configuration
|
||||
|
||||
Administrators can configure multiple server-side models that are available to all users without requiring personal API keys. Configure via `AI_MODELS_CONFIG` environment variable (JSON string) or `ai-models.json` file. For a single-provider quick setup, list comma-separated model IDs in `AI_MODEL`.
|
||||
|
||||
### Admin Panel
|
||||
|
||||
Set the `ADMIN_PASSWORD` environment variable and visit `/admin` to manage server settings (models, access codes, features, observability, quota) from a web panel instead of hand-editing `.env`.
|
||||
|
||||
📖 **[Admin Panel Guide](./docs/en/admin-panel.md)** — setup, precedence rules, and notes.
|
||||
|
||||
**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 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
|
||||
|
||||
The application uses the following technologies:
|
||||
|
||||
- **Next.js**: For the frontend framework and routing
|
||||
- **Vercel AI SDK** (`ai` + `@ai-sdk/*`): For streaming AI responses and multi-provider support
|
||||
- **react-drawio**: For diagram representation and manipulation
|
||||
|
||||
Diagrams are represented as XML that can be rendered in draw.io. The AI processes your commands and generates or modifies this XML accordingly.
|
||||
|
||||
|
||||
## Support & Contact
|
||||
|
||||
**Special thanks to [ByteDance Doubao](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio) for sponsoring the API token usage of the demo site!** Register on the ARK platform to get 500K free tokens for all models!
|
||||
|
||||
**Special thanks to [Atlas Cloud](https://www.atlascloud.ai/?utm_source=github&utm_medium=link&utm_campaign=next-ai-draw-io) for sponsoring next-ai-draw-io and supporting its multi-provider ecosystem!** Try its OpenAI-compatible LLM API through the [Atlas Cloud Coding Plan](https://www.atlascloud.ai/console/coding-plan).
|
||||
|
||||
If you find this project useful, please consider [sponsoring](https://github.com/sponsors/DayuanJiang) to help me host the live demo site!
|
||||
|
||||
For support or inquiries, please open an issue on the GitHub repository or contact the maintainer at:
|
||||
|
||||
- Email: me[at]jiang.jp
|
||||
|
||||
## FAQ
|
||||
|
||||
See [FAQ](./docs/en/FAQ.md) for common issues and solutions.
|
||||
|
||||
## Star History
|
||||
<div align="center">
|
||||
|
||||
[](https://www.star-history.com/#DayuanJiang/next-ai-draw-io&type=date&legend=top-left)
|
||||
|
||||
---
|
||||
</div>
|
||||
|
||||
@@ -66,54 +66,6 @@ export default function AboutCN() {
|
||||
<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="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-yellow-400 opacity-20" />
|
||||
<div className="relative rounded-2xl bg-white/80 backdrop-blur-sm p-6">
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900 tracking-tight">
|
||||
由字节跳动豆包提供支持
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Story */}
|
||||
<div className="space-y-3 text-sm text-gray-700 leading-relaxed mb-5">
|
||||
<p>
|
||||
好消息!感谢{" "}
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-semibold text-blue-600 hover:underline"
|
||||
>
|
||||
字节跳动豆包
|
||||
</a>
|
||||
的慷慨赞助,演示站点现已接入强大的{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
glm-4.7
|
||||
</span>{" "}
|
||||
模型,图表生成效果更佳!点击链接注册即可领取{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
50万免费Token
|
||||
</span>
|
||||
,适用于所有模型!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Invite Poster */}
|
||||
<div className="text-center mb-5">
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
src="/volcengine-invite.png"
|
||||
alt="火山引擎方舟 Coding Plan"
|
||||
width={300}
|
||||
height={400}
|
||||
className="mx-auto rounded-lg"
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Bring Your Own Key */}
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
@@ -149,8 +101,10 @@ export default function AboutCN() {
|
||||
:上传现有图表或图像,让AI自动复制和增强
|
||||
</li>
|
||||
<li>
|
||||
<strong>图表历史记录</strong>
|
||||
:全面的版本控制,跟踪所有更改,允许您查看和恢复AI编辑前的图表版本
|
||||
<strong>版本与撤销</strong>
|
||||
:AI
|
||||
的每次修改都会成为聊天里的一个版本,可以对比、恢复或撤销;在画布上按
|
||||
Ctrl+Z 也能撤回
|
||||
</li>
|
||||
<li>
|
||||
<strong>交互式聊天界面</strong>
|
||||
@@ -294,7 +248,8 @@ export default function AboutCN() {
|
||||
):用于流式AI响应和多提供商支持
|
||||
</li>
|
||||
<li>
|
||||
<strong>react-drawio</strong>:用于图表表示和操作
|
||||
<strong>draw.io</strong>
|
||||
:内置在应用里的编辑器,应用可以直接控制它
|
||||
</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
@@ -306,16 +261,7 @@ export default function AboutCN() {
|
||||
多提供商支持
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-1">
|
||||
<li>
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
字节跳动豆包
|
||||
</a>
|
||||
</li>
|
||||
<li>字节跳动豆包</li>
|
||||
<li>AWS Bedrock(默认)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI兼容API(通过{" "}
|
||||
@@ -340,18 +286,6 @@ export default function AboutCN() {
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
支持与联系
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4 font-semibold">
|
||||
特别感谢{" "}
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
字节跳动豆包
|
||||
</a>{" "}
|
||||
为本站提供 API Token 支持!
|
||||
</p>
|
||||
<p className="text-gray-700">
|
||||
如果您觉得这个项目有用,请考虑{" "}
|
||||
<a
|
||||
|
||||
@@ -74,37 +74,6 @@ export default function AboutJA() {
|
||||
<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="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-yellow-400 opacity-20" />
|
||||
<div className="relative rounded-2xl bg-white/80 backdrop-blur-sm p-6">
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900 tracking-tight">
|
||||
ByteDance Doubao提供
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Story */}
|
||||
<div className="space-y-3 text-sm text-gray-700 leading-relaxed mb-5">
|
||||
<p>
|
||||
朗報です!
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-semibold text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>
|
||||
様のご支援により、デモサイトでは強力な{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
glm-4.7
|
||||
</span>{" "}
|
||||
モデルを利用できるようになり、より高品質なダイアグラム生成が可能になりました。リンクから登録すると、すべてのモデルで使える{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
50万トークン
|
||||
</span>
|
||||
が無料でもらえます!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Bring Your Own Key */}
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
@@ -138,8 +107,10 @@ export default function AboutJA() {
|
||||
:既存のダイアグラムや画像をアップロードし、AIが自動的に複製・強化
|
||||
</li>
|
||||
<li>
|
||||
<strong>ダイアグラム履歴</strong>
|
||||
:すべての変更を追跡する包括的なバージョン管理。AI編集前のダイアグラムの以前のバージョンを表示・復元可能
|
||||
<strong>バージョンと取り消し</strong>
|
||||
:AI
|
||||
の変更はそれぞれチャット内のバージョンになり、比較・復元・取り消しができます。キャンバスで
|
||||
Ctrl+Z を押しても元に戻せます
|
||||
</li>
|
||||
<li>
|
||||
<strong>
|
||||
@@ -290,8 +261,8 @@ export default function AboutJA() {
|
||||
):ストリーミングAIレスポンスとマルチプロバイダーサポート
|
||||
</li>
|
||||
<li>
|
||||
<strong>react-drawio</strong>
|
||||
:ダイアグラムの表現と操作
|
||||
<strong>draw.io</strong>
|
||||
:アプリに同梱されたエディター。アプリから直接操作できます
|
||||
</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
@@ -303,16 +274,7 @@ export default function AboutJA() {
|
||||
マルチプロバイダーサポート
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-1">
|
||||
<li>
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>
|
||||
</li>
|
||||
<li>ByteDance Doubao</li>
|
||||
<li>AWS Bedrock(デフォルト)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI互換API(<code>OPENAI_BASE_URL</code>
|
||||
@@ -337,18 +299,6 @@ export default function AboutJA() {
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
サポート&お問い合わせ
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4 font-semibold">
|
||||
デモサイトのAPIトークン使用を支援してくださった{" "}
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>{" "}
|
||||
様に、心より感謝申し上げます。
|
||||
</p>
|
||||
<p className="text-gray-700">
|
||||
このプロジェクトが役に立ったら、ライブデモサイトのホスティングを支援するために{" "}
|
||||
<a
|
||||
|
||||
@@ -74,39 +74,6 @@ export default function About() {
|
||||
<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="absolute inset-0 rounded-2xl bg-gradient-to-br from-amber-400 via-orange-400 to-yellow-400 opacity-20" />
|
||||
<div className="relative rounded-2xl bg-white/80 backdrop-blur-sm p-6">
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900 tracking-tight">
|
||||
Sponsored by ByteDance Doubao
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Story */}
|
||||
<div className="space-y-3 text-sm text-gray-700 leading-relaxed mb-5">
|
||||
<p>
|
||||
Great news! Thanks to the generous
|
||||
sponsorship from{" "}
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-semibold text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>
|
||||
, the demo site now uses the powerful{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
glm-4.7
|
||||
</span>{" "}
|
||||
model for better diagram generation! Sign up
|
||||
via the link to get{" "}
|
||||
<span className="font-semibold text-amber-700">
|
||||
500K free tokens
|
||||
</span>{" "}
|
||||
for all models!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Bring Your Own Key */}
|
||||
<div className="text-center">
|
||||
<h4 className="text-base font-bold text-gray-900 mb-2">
|
||||
@@ -150,10 +117,10 @@ export default function About() {
|
||||
replicate and enhance them automatically
|
||||
</li>
|
||||
<li>
|
||||
<strong>Diagram History</strong>: Comprehensive
|
||||
version control that tracks all changes, allowing
|
||||
you to view and restore previous versions of your
|
||||
diagrams before the AI editing
|
||||
<strong>Versions and Undo</strong>: Every AI change
|
||||
becomes a version in the chat that you can compare,
|
||||
restore or undo; Ctrl+Z on the canvas takes it back
|
||||
too
|
||||
</li>
|
||||
<li>
|
||||
<strong>Interactive Chat Interface</strong>:
|
||||
@@ -304,8 +271,8 @@ export default function About() {
|
||||
and multi-provider support
|
||||
</li>
|
||||
<li>
|
||||
<strong>react-drawio</strong>: For diagram
|
||||
representation and manipulation
|
||||
<strong>draw.io</strong>: The editor, bundled with
|
||||
the app so it can be driven directly
|
||||
</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
@@ -319,16 +286,7 @@ export default function About() {
|
||||
Multi-Provider Support
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-1">
|
||||
<li>
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>
|
||||
</li>
|
||||
<li>ByteDance Doubao</li>
|
||||
<li>AWS Bedrock (default)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI-compatible APIs (via{" "}
|
||||
@@ -355,18 +313,6 @@ export default function About() {
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
Support & Contact
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4 font-semibold">
|
||||
Special thanks to{" "}
|
||||
<a
|
||||
href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
ByteDance Doubao
|
||||
</a>{" "}
|
||||
for sponsoring the API token usage of the demo site!
|
||||
</p>
|
||||
<p className="text-gray-700">
|
||||
If you find this project useful, please consider{" "}
|
||||
<a
|
||||
|
||||
+15
-4
@@ -1,19 +1,25 @@
|
||||
import { GoogleAnalytics } from "@next/third-parties/google"
|
||||
import type { Metadata, Viewport } from "next"
|
||||
import { JetBrains_Mono, Plus_Jakarta_Sans } from "next/font/google"
|
||||
import { Instrument_Sans, JetBrains_Mono } from "next/font/google"
|
||||
import { notFound } from "next/navigation"
|
||||
import Script from "next/script"
|
||||
import { AppToaster } from "@/components/workspace/app-toaster"
|
||||
import { DiagramProvider } from "@/contexts/diagram-context"
|
||||
import { DictionaryProvider } from "@/hooks/use-dictionary"
|
||||
import type { Locale } from "@/lib/i18n/config"
|
||||
import { i18n } from "@/lib/i18n/config"
|
||||
import { getDictionary, hasLocale } from "@/lib/i18n/dictionaries"
|
||||
import { THEME_INIT_SCRIPT } from "@/stores/settings-store"
|
||||
|
||||
import "../globals.css"
|
||||
|
||||
const plusJakarta = Plus_Jakarta_Sans({
|
||||
variable: "--font-sans",
|
||||
const instrumentSans = Instrument_Sans({
|
||||
variable: "--font-latin",
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600", "700"],
|
||||
// Chinese and Japanese text falls through to system fonts, in the
|
||||
// order globals.css picks for the page's language
|
||||
fallback: [],
|
||||
})
|
||||
|
||||
const jetbrainsMono = JetBrains_Mono({
|
||||
@@ -165,17 +171,22 @@ export default async function RootLayout({
|
||||
return (
|
||||
<html lang={validLang} suppressHydrationWarning>
|
||||
<head>
|
||||
{/* Apply dark mode before the first paint (no white flash) */}
|
||||
<Script id="theme-init" strategy="beforeInteractive">
|
||||
{THEME_INIT_SCRIPT}
|
||||
</Script>
|
||||
<script
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
|
||||
/>
|
||||
</head>
|
||||
<body
|
||||
className={`${plusJakarta.variable} ${jetbrainsMono.variable} antialiased`}
|
||||
className={`${instrumentSans.variable} ${jetbrainsMono.variable} antialiased`}
|
||||
>
|
||||
<DictionaryProvider dictionary={dictionary}>
|
||||
<DiagramProvider>{children}</DiagramProvider>
|
||||
</DictionaryProvider>
|
||||
<AppToaster />
|
||||
</body>
|
||||
{process.env.NEXT_PUBLIC_GA_ID && (
|
||||
<GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GA_ID} />
|
||||
|
||||
+6
-251
@@ -1,256 +1,11 @@
|
||||
"use client"
|
||||
import { usePathname, useRouter } from "next/navigation"
|
||||
import { Suspense, useCallback, useEffect, useRef, useState } from "react"
|
||||
import { DrawIoEmbed } from "react-drawio"
|
||||
import type { ImperativePanelHandle } from "react-resizable-panels"
|
||||
import ChatPanel from "@/components/chat-panel"
|
||||
import {
|
||||
ResizableHandle,
|
||||
ResizablePanel,
|
||||
ResizablePanelGroup,
|
||||
} from "@/components/ui/resizable"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { type DrawioTheme, isDrawioTheme } from "@/lib/drawio-themes"
|
||||
import { i18n, type Locale } from "@/lib/i18n/config"
|
||||
import { Suspense } from "react"
|
||||
import { Workspace } from "@/components/workspace/workspace"
|
||||
|
||||
export default function Home() {
|
||||
const {
|
||||
drawioRef,
|
||||
handleDiagramExport,
|
||||
handleDiagramAutoSave,
|
||||
onDrawioLoad,
|
||||
resetDrawioReady,
|
||||
} = useDiagram()
|
||||
const router = useRouter()
|
||||
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 [isChatVisible, setIsChatVisible] = useState(true)
|
||||
const [drawioUi, setDrawioUi] = useState<DrawioTheme>("kennedy")
|
||||
const [darkMode, setDarkMode] = useState(false)
|
||||
const [isLoaded, setIsLoaded] = useState(false)
|
||||
const [isDrawioReady, setIsDrawioReady] = useState(false)
|
||||
const [isElectron, setIsElectron] = useState(false)
|
||||
const [drawioBaseUrl, setDrawioBaseUrl] = useState(
|
||||
process.env.NEXT_PUBLIC_DRAWIO_BASE_URL || "https://embed.diagrams.net",
|
||||
)
|
||||
|
||||
const chatPanelRef = useRef<ImperativePanelHandle>(null)
|
||||
|
||||
// Load preferences from localStorage after mount
|
||||
useEffect(() => {
|
||||
// Restore saved locale and redirect if needed
|
||||
const savedLocale = localStorage.getItem("next-ai-draw-io-locale")
|
||||
if (savedLocale && i18n.locales.includes(savedLocale as Locale)) {
|
||||
const pathParts = pathname.split("/").filter(Boolean)
|
||||
const currentLocale = pathParts[0]
|
||||
if (currentLocale !== savedLocale) {
|
||||
pathParts[0] = savedLocale
|
||||
// Keep the query (e.g. ?session=) and hash
|
||||
const { search, hash } = window.location
|
||||
router.replace(`/${pathParts.join("/")}${search}${hash}`)
|
||||
return // Wait for redirect
|
||||
}
|
||||
}
|
||||
|
||||
const savedUi = localStorage.getItem("drawio-theme")
|
||||
if (isDrawioTheme(savedUi)) {
|
||||
setDrawioUi(savedUi)
|
||||
}
|
||||
|
||||
const savedDarkMode = localStorage.getItem("next-ai-draw-io-dark-mode")
|
||||
if (savedDarkMode !== null) {
|
||||
const isDark = savedDarkMode === "true"
|
||||
setDarkMode(isDark)
|
||||
document.documentElement.classList.toggle("dark", isDark)
|
||||
} else {
|
||||
const prefersDark = window.matchMedia(
|
||||
"(prefers-color-scheme: dark)",
|
||||
).matches
|
||||
setDarkMode(prefersDark)
|
||||
document.documentElement.classList.toggle("dark", prefersDark)
|
||||
}
|
||||
|
||||
// Detect Electron and use bundled draw.io files for offline use
|
||||
// Note: react-drawio uses `new URL(baseUrl)` so we need absolute URL
|
||||
// Include /index.html because Next.js doesn't auto-serve index.html for directories
|
||||
const electronDetected =
|
||||
!process.env.NEXT_PUBLIC_DRAWIO_BASE_URL &&
|
||||
!!(window as unknown as { electronAPI?: unknown }).electronAPI
|
||||
if (electronDetected) {
|
||||
setIsElectron(true)
|
||||
setDrawioBaseUrl(`${window.location.origin}/drawio/index.html`)
|
||||
}
|
||||
|
||||
setIsLoaded(true)
|
||||
}, [pathname, router])
|
||||
|
||||
const handleDrawioLoad = useCallback(() => {
|
||||
setIsDrawioReady(true)
|
||||
onDrawioLoad()
|
||||
}, [onDrawioLoad])
|
||||
|
||||
const handleDarkModeChange = () => {
|
||||
const newValue = !darkMode
|
||||
setDarkMode(newValue)
|
||||
localStorage.setItem("next-ai-draw-io-dark-mode", String(newValue))
|
||||
document.documentElement.classList.toggle("dark", newValue)
|
||||
setIsDrawioReady(false)
|
||||
resetDrawioReady()
|
||||
}
|
||||
|
||||
const handleDrawioUiChange = (theme: DrawioTheme) => {
|
||||
localStorage.setItem("drawio-theme", theme)
|
||||
setDrawioUi(theme)
|
||||
setIsDrawioReady(false)
|
||||
resetDrawioReady()
|
||||
}
|
||||
|
||||
// Check mobile. No panel is remounted when crossing the breakpoint, so
|
||||
// the draw.io ready state and the chat's turn stay as they are.
|
||||
useEffect(() => {
|
||||
const checkMobile = () => {
|
||||
setIsMobile(window.innerWidth < 768)
|
||||
}
|
||||
|
||||
checkMobile()
|
||||
window.addEventListener("resize", checkMobile)
|
||||
return () => window.removeEventListener("resize", checkMobile)
|
||||
}, [])
|
||||
|
||||
// Give the chat panel the size of this side of the breakpoint. It is
|
||||
// open on both sides: the mobile panel cannot be collapsed, and one
|
||||
// collapsed on desktop comes back open
|
||||
useEffect(() => {
|
||||
chatPanelRef.current?.resize(isMobile ? 50 : 33)
|
||||
setIsChatVisible(true)
|
||||
}, [isMobile])
|
||||
|
||||
const toggleChatPanel = () => {
|
||||
const panel = chatPanelRef.current
|
||||
if (panel) {
|
||||
if (panel.isCollapsed()) {
|
||||
panel.expand()
|
||||
setIsChatVisible(true)
|
||||
} else {
|
||||
panel.collapse()
|
||||
setIsChatVisible(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keyboard shortcut for toggling chat panel
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === "b") {
|
||||
event.preventDefault()
|
||||
toggleChatPanel()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [])
|
||||
|
||||
// The workspace reads ?session= from the URL, which needs a Suspense boundary
|
||||
return (
|
||||
<div className="h-screen bg-background relative overflow-hidden">
|
||||
<ResizablePanelGroup
|
||||
id="main-panel-group"
|
||||
direction={isMobile ? "vertical" : "horizontal"}
|
||||
className="h-full"
|
||||
>
|
||||
<ResizablePanel
|
||||
id="drawio-panel"
|
||||
defaultSize={isMobile ? 50 : 67}
|
||||
minSize={20}
|
||||
>
|
||||
<div
|
||||
className={`h-full relative ${
|
||||
isMobile ? "p-1" : "p-2"
|
||||
}`}
|
||||
>
|
||||
<div className="h-full rounded-xl overflow-hidden shadow-soft-lg border border-border/30 relative">
|
||||
{isLoaded && (
|
||||
<div
|
||||
className={`h-full w-full ${isDrawioReady ? "" : "invisible absolute inset-0"}`}
|
||||
>
|
||||
<DrawIoEmbed
|
||||
key={`${drawioUi}-${darkMode}-${currentLang}-${isElectron}`}
|
||||
ref={drawioRef}
|
||||
autosave
|
||||
onAutoSave={handleDiagramAutoSave}
|
||||
onExport={handleDiagramExport}
|
||||
onLoad={handleDrawioLoad}
|
||||
baseUrl={drawioBaseUrl}
|
||||
urlParameters={{
|
||||
ui: drawioUi,
|
||||
spin: false,
|
||||
libraries: false,
|
||||
saveAndExit: false,
|
||||
noSaveBtn: true,
|
||||
noExitBtn: true,
|
||||
dark:
|
||||
darkMode || drawioUi === "dark",
|
||||
// draw.io names Traditional Chinese "zh-tw"
|
||||
lang:
|
||||
currentLang === "zh-Hant"
|
||||
? "zh-tw"
|
||||
: currentLang,
|
||||
// Enable offline mode in Electron to disable external service calls
|
||||
...(isElectron && {
|
||||
offline: true,
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{(!isLoaded || !isDrawioReady) && (
|
||||
<div className="h-full w-full bg-background flex items-center justify-center">
|
||||
<span className="text-muted-foreground">
|
||||
Draw.io panel is loading...
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
|
||||
<ResizableHandle withHandle />
|
||||
|
||||
{/* Chat Panel */}
|
||||
<ResizablePanel
|
||||
id="chat-panel"
|
||||
ref={chatPanelRef}
|
||||
defaultSize={isMobile ? 50 : 33}
|
||||
minSize={isMobile ? 20 : 15}
|
||||
maxSize={isMobile ? 80 : 50}
|
||||
collapsible={!isMobile}
|
||||
collapsedSize={isMobile ? 0 : 3}
|
||||
onCollapse={() => setIsChatVisible(false)}
|
||||
onExpand={() => setIsChatVisible(true)}
|
||||
>
|
||||
<div className={`h-full ${isMobile ? "p-1" : "py-2 pr-2"}`}>
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="h-full bg-card rounded-xl border border-border/30 flex items-center justify-center text-muted-foreground">
|
||||
Loading chat...
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ChatPanel
|
||||
isVisible={isChatVisible}
|
||||
onToggleVisibility={toggleChatPanel}
|
||||
drawioUi={drawioUi}
|
||||
onDrawioUiChange={handleDrawioUiChange}
|
||||
darkMode={darkMode}
|
||||
onToggleDarkMode={handleDarkModeChange}
|
||||
isMobile={isMobile}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
<Suspense fallback={<div className="fixed inset-0 bg-canvas" />}>
|
||||
<Workspace />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
+30
-11
@@ -25,6 +25,7 @@ import { findCachedResponse } from "@/lib/cached-responses"
|
||||
import {
|
||||
dropInvalidToolCalls,
|
||||
fixToolInputJson,
|
||||
formatSelectionContext,
|
||||
replaceHistoricalToolInputs,
|
||||
validateFileParts,
|
||||
} from "@/lib/chat-helpers"
|
||||
@@ -54,12 +55,16 @@ import { allowPrivateUrls, isPrivateUrl } from "@/lib/ssrf-protection"
|
||||
import { getSystemPrompt } from "@/lib/system-prompts"
|
||||
import { normalizeBaseUrl } from "@/lib/types/model-config"
|
||||
import { getUserIdFromRequest } from "@/lib/user-id"
|
||||
import { foldCells } from "@/packages/mcp-server/src/compact-cells.ts"
|
||||
import { hasCells } from "@/packages/mcp-server/src/pages.ts"
|
||||
import {
|
||||
getShapeLibrary,
|
||||
SHAPE_LIBRARY_LIST,
|
||||
} from "@/packages/mcp-server/src/shape-library.ts"
|
||||
import { SWIMLANE_EXAMPLE } from "@/packages/mcp-server/src/xml-examples.ts"
|
||||
import {
|
||||
STYLE_CLASS_EXAMPLE,
|
||||
SWIMLANE_EXAMPLE,
|
||||
} from "@/packages/mcp-server/src/xml-examples.ts"
|
||||
|
||||
// No explicit cap: a reasoning model can spend minutes planning before it emits
|
||||
// the tool call, so take whatever the host allows. Vercel's own default is 300s,
|
||||
@@ -97,6 +102,11 @@ function createCachedStreamResponse(xml: string): Response {
|
||||
|
||||
// Responses streamed from the model, whose trace streamText's callbacks end
|
||||
const modelStreamResponses = new WeakSet<Response>()
|
||||
// A Request's signal follows the client's disconnect only while the Request
|
||||
// object itself is alive: once it is garbage collected, the abort is lost
|
||||
// (nodejs/undici#3644) and a stopped chat would run on at the provider.
|
||||
// Each request is kept as long as its answer streams.
|
||||
const requestOfResponse = new WeakMap<Response, Request>()
|
||||
|
||||
// Inner handler function
|
||||
const DEBUG_LLM_PAYLOAD = process.env.DEBUG_LLM_PAYLOAD === "true"
|
||||
@@ -513,21 +523,24 @@ ${userInputText}
|
||||
const isSingleSystemProvider =
|
||||
SINGLE_SYSTEM_PROVIDERS.has(resolvedProvider) || isCustomOpenAIEndpoint
|
||||
|
||||
const selectionContext = formatSelectionContext(body.selectedCells)
|
||||
// The model reads the diagram in the compact notation it writes
|
||||
// (compact-cells.ts); the canvas itself keeps the full XML
|
||||
const xmlContext = `${
|
||||
previousXml
|
||||
? `Previous diagram XML (before user's last message):
|
||||
"""xml
|
||||
${previousXml}
|
||||
${foldCells(previousXml)}
|
||||
"""
|
||||
|
||||
`
|
||||
: ""
|
||||
}Current diagram XML (AUTHORITATIVE - the source of truth):
|
||||
}Current diagram XML (AUTHORITATIVE - the source of truth), shown in the same compact notation you write (shapes with x, y, w, h; edges with source and target):
|
||||
"""xml
|
||||
${xml || ""}
|
||||
${foldCells(xml || "")}
|
||||
"""
|
||||
|
||||
IMPORTANT: The "Current diagram XML" is the SINGLE SOURCE OF TRUTH for what's on the canvas right now. The user can manually add, delete, or modify shapes directly in draw.io. Always count and describe elements based on the CURRENT XML, not on what you previously generated. If both previous and current XML are shown, compare them to understand what the user changed.`
|
||||
IMPORTANT: The "Current diagram XML" is the SINGLE SOURCE OF TRUTH for what's on the canvas right now. The user can manually add, delete, or modify shapes directly in draw.io. Always count and describe elements based on the CURRENT XML, not on what you previously generated. If both previous and current XML are shown, compare them to understand what the user changed.${selectionContext ? `\n\n${selectionContext}` : ""}`
|
||||
|
||||
const systemMessages = isSingleSystemProvider
|
||||
? [
|
||||
@@ -652,19 +665,24 @@ IMPORTANT: The "Current diagram XML" is the SINGLE SOURCE OF TRUTH for what's on
|
||||
tools: {
|
||||
// Client-side tool that will be executed on the client
|
||||
display_diagram: {
|
||||
description: `Display a diagram on draw.io. Pass ONLY the mxCell elements - wrapper tags and root cells are added automatically.
|
||||
description: `Display a diagram on draw.io. Pass ONLY the mxStyle definitions and the mxCell elements - wrapper tags and root cells are added automatically.
|
||||
|
||||
VALIDATION RULES (XML will be rejected if violated):
|
||||
1. Generate ONLY mxCell elements - NO wrapper tags (<mxfile>, <mxGraphModel>, <root>)
|
||||
1. Generate ONLY mxStyle definitions and mxCell elements - NO wrapper tags (<mxfile>, <mxGraphModel>, <root>)
|
||||
2. Do NOT include root cells (id="0" or id="1") - they are added automatically
|
||||
3. All mxCell elements must be siblings - never nested
|
||||
4. Every mxCell needs a unique id (start from "2")
|
||||
5. Every mxCell needs a valid parent attribute (use "1" for top-level)
|
||||
5. parent defaults to "1"; write parent="<container-id>" only for shapes inside a container
|
||||
6. Escape special chars in values: < > & "
|
||||
|
||||
A shape is one self-closing mxCell with x, y, w and h; an edge is one with source and target (a cell with source or target is always an edge). vertex="1", edge="1", parent="1" and the mxGeometry element are added automatically. Write parent only for a shape inside a container, and an mxGeometry element only for edge waypoints or for a separate label cell placed on an edge: <mxCell id="9" value="yes" style="edgeLabel;" parent="<edge id>" connectable="0"><mxGeometry x="-0.5" relative="1" as="geometry"/></mxCell>. An edge's own text simply goes in its value.
|
||||
|
||||
Example (generate ONLY this - no wrapper tags):
|
||||
${SWIMLANE_EXAMPLE}
|
||||
|
||||
Styles: define a style used by several cells ONCE with <mxStyle name="..." value="..."/> before the cells and use the name in style like a CSS class; overrides after the name win. Name only styles that two or more cells share; names must not be draw.io's own style names (text, ellipse, rhombus, swimlane, label, image, blue, green, red, gray, yellow, orange, purple, pink). A definition applies to the call it is in. html=1 and whiteSpace=wrap are added automatically, never write them. Labels are HTML: use <br> for a line break, never \\n; a literal < or > is written &lt; or &gt;.
|
||||
${STYLE_CLASS_EXAMPLE}
|
||||
|
||||
Notes:
|
||||
- For AWS diagrams, use **AWS 2025 icons**.
|
||||
- For animated connectors, add "flowAnimation=1" to edge style.
|
||||
@@ -683,12 +701,12 @@ Operations:
|
||||
- add: Add a new cell. Provide cell_id (new unique id) and new_xml.
|
||||
- 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 is the complete mxCell in the compact form (a shape with x, y, w, h; an edge with source and target), with its complete style (named styles are not available in edit_diagram).
|
||||
|
||||
⚠️ JSON ESCAPING: Every " inside new_xml MUST be escaped as \\". Example: id=\\"5\\" value=\\"Label\\"
|
||||
|
||||
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=1;\\" x=\\"100\\" y=\\"100\\" w=\\"120\\" h=\\"60\\"/>"}]}
|
||||
|
||||
Example - Delete container (children & edges auto-deleted):
|
||||
{"operations": [{"operation": "delete", "cell_id": "2"}]}`,
|
||||
@@ -728,7 +746,7 @@ CRITICAL INSTRUCTIONS:
|
||||
3. Complete the remaining mxCell elements
|
||||
4. If still truncated, call append_diagram again with the next fragment
|
||||
|
||||
Example: If previous output ended with '<mxCell id="x" style="rounded=1', continue with ';" vertex="1">...' and complete the remaining elements.`,
|
||||
Example: If previous output ended with '<mxCell id="x" style="rounded=1', continue with ';" x="40" y="40" w="120" h="60"/>' and complete the remaining elements.`,
|
||||
inputSchema: z.object({
|
||||
xml: z
|
||||
.string()
|
||||
@@ -785,6 +803,7 @@ Call this tool to get shape names and usage syntax for a specific library.`,
|
||||
},
|
||||
})
|
||||
modelStreamResponses.add(response)
|
||||
requestOfResponse.set(response, req)
|
||||
return response
|
||||
}
|
||||
|
||||
|
||||
@@ -104,11 +104,14 @@ export async function POST(req: Request) {
|
||||
|
||||
// Validate credentials based on provider
|
||||
if (provider === "bedrock") {
|
||||
if (!awsAccessKeyId || !awsSecretAccessKey || !awsRegion) {
|
||||
if (
|
||||
!(apiKey || (awsAccessKeyId && awsSecretAccessKey)) ||
|
||||
!awsRegion
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
valid: false,
|
||||
error: "AWS credentials (Access Key ID, Secret Access Key, Region) are required",
|
||||
error: "AWS credentials (a Bedrock API key, or an Access Key ID and Secret Access Key, and a Region) are required",
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
|
||||
+200
-293
@@ -8,21 +8,8 @@
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-sans);
|
||||
--font-sans: var(--font-latin), var(--font-cjk), system-ui, sans-serif;
|
||||
--font-mono: var(--font-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
@@ -43,161 +30,16 @@
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.75rem;
|
||||
|
||||
/* Clean Light Modern Palette */
|
||||
--background: oklch(0.985 0.002 240);
|
||||
--foreground: oklch(0.23 0.02 260);
|
||||
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.23 0.02 260);
|
||||
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.23 0.02 260);
|
||||
|
||||
/* Dark primary - slightly lighter */
|
||||
--primary: oklch(0.35 0.01 260);
|
||||
--primary-foreground: oklch(0.99 0 0);
|
||||
|
||||
/* Warm gray secondary */
|
||||
--secondary: oklch(0.96 0.005 260);
|
||||
--secondary-foreground: oklch(0.35 0.02 260);
|
||||
|
||||
/* Light muted tones */
|
||||
--muted: oklch(0.965 0.005 260);
|
||||
--muted-foreground: oklch(0.5 0.02 260);
|
||||
|
||||
/* Soft lavender accent */
|
||||
--accent: oklch(0.94 0.03 280);
|
||||
--accent-foreground: oklch(0.35 0.08 270);
|
||||
|
||||
/* Muted rose destructive */
|
||||
--destructive: oklch(0.45 0.12 10);
|
||||
|
||||
/* Subtle borders */
|
||||
--border: oklch(0.92 0.01 260);
|
||||
--input: oklch(0.94 0.01 260);
|
||||
--ring: oklch(0.25 0.01 260);
|
||||
|
||||
/* Chart colors - harmonious palette */
|
||||
--chart-1: oklch(0.55 0.18 265);
|
||||
--chart-2: oklch(0.65 0.15 170);
|
||||
--chart-3: oklch(0.7 0.18 45);
|
||||
--chart-4: oklch(0.6 0.2 330);
|
||||
--chart-5: oklch(0.5 0.15 200);
|
||||
|
||||
/* Sidebar */
|
||||
--sidebar: oklch(0.99 0.002 260);
|
||||
--sidebar-foreground: oklch(0.23 0.02 260);
|
||||
--sidebar-primary: oklch(0.55 0.18 265);
|
||||
--sidebar-primary-foreground: oklch(0.99 0 0);
|
||||
--sidebar-accent: oklch(0.96 0.02 270);
|
||||
--sidebar-accent-foreground: oklch(0.35 0.05 265);
|
||||
--sidebar-border: oklch(0.93 0.01 260);
|
||||
--sidebar-ring: oklch(0.55 0.18 265);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.15 0.015 260);
|
||||
--foreground: oklch(0.95 0.01 260);
|
||||
|
||||
--card: oklch(0.2 0.015 260);
|
||||
--card-foreground: oklch(0.95 0.01 260);
|
||||
|
||||
--popover: oklch(0.2 0.015 260);
|
||||
--popover-foreground: oklch(0.95 0.01 260);
|
||||
|
||||
--primary: oklch(0.7 0.16 265);
|
||||
--primary-foreground: oklch(0.15 0.02 260);
|
||||
|
||||
--secondary: oklch(0.25 0.015 260);
|
||||
--secondary-foreground: oklch(0.9 0.01 260);
|
||||
|
||||
--muted: oklch(0.25 0.015 260);
|
||||
--muted-foreground: oklch(0.65 0.02 260);
|
||||
|
||||
--accent: oklch(0.3 0.04 280);
|
||||
--accent-foreground: oklch(0.9 0.03 270);
|
||||
|
||||
--destructive: oklch(0.55 0.12 10);
|
||||
|
||||
--border: oklch(0.28 0.015 260);
|
||||
--input: oklch(0.25 0.015 260);
|
||||
--ring: oklch(0.7 0.16 265);
|
||||
|
||||
--chart-1: oklch(0.7 0.16 265);
|
||||
--chart-2: oklch(0.7 0.13 170);
|
||||
--chart-3: oklch(0.75 0.16 45);
|
||||
--chart-4: oklch(0.7 0.18 330);
|
||||
--chart-5: oklch(0.6 0.13 200);
|
||||
|
||||
--sidebar: oklch(0.18 0.015 260);
|
||||
--sidebar-foreground: oklch(0.95 0.01 260);
|
||||
--sidebar-primary: oklch(0.7 0.16 265);
|
||||
--sidebar-primary-foreground: oklch(0.15 0.02 260);
|
||||
--sidebar-accent: oklch(0.25 0.03 270);
|
||||
--sidebar-accent-foreground: oklch(0.9 0.02 265);
|
||||
--sidebar-border: oklch(0.28 0.015 260);
|
||||
--sidebar-ring: oklch(0.7 0.16 265);
|
||||
}
|
||||
|
||||
/* ============================================
|
||||
REFINED MINIMAL DESIGN SYSTEM
|
||||
============================================ */
|
||||
|
||||
:root {
|
||||
/* Surface layers for depth */
|
||||
--surface-0: oklch(1 0 0);
|
||||
--surface-1: oklch(0.985 0.002 240);
|
||||
--surface-2: oklch(0.97 0.004 240);
|
||||
--surface-elevated: oklch(1 0 0);
|
||||
|
||||
/* Subtle borders */
|
||||
--border-subtle: oklch(0.94 0.008 260);
|
||||
--border-default: oklch(0.91 0.012 260);
|
||||
|
||||
/* Interactive states */
|
||||
--interactive-hover: oklch(0.96 0.015 260);
|
||||
--interactive-active: oklch(0.93 0.02 265);
|
||||
|
||||
/* Success state */
|
||||
--success: oklch(0.65 0.18 145);
|
||||
--success-muted: oklch(0.95 0.03 145);
|
||||
|
||||
/* Animation timing */
|
||||
--duration-fast: 120ms;
|
||||
--duration-normal: 200ms;
|
||||
--duration-slow: 300ms;
|
||||
--ease-out: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
--ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
--ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--surface-0: oklch(0.15 0.015 260);
|
||||
--surface-1: oklch(0.18 0.015 260);
|
||||
--surface-2: oklch(0.22 0.015 260);
|
||||
--surface-elevated: oklch(0.25 0.015 260);
|
||||
|
||||
--border-subtle: oklch(0.25 0.012 260);
|
||||
--border-default: oklch(0.3 0.015 260);
|
||||
|
||||
--interactive-hover: oklch(0.25 0.02 265);
|
||||
--interactive-active: oklch(0.3 0.025 270);
|
||||
|
||||
--success: oklch(0.7 0.16 145);
|
||||
--success-muted: oklch(0.25 0.04 145);
|
||||
}
|
||||
|
||||
/* Expose surface colors to Tailwind */
|
||||
@theme inline {
|
||||
/* App-specific tokens */
|
||||
--color-canvas: var(--canvas);
|
||||
--color-faint: var(--faint);
|
||||
--color-marker: var(--marker);
|
||||
--color-marker-soft: var(--marker-soft);
|
||||
--color-marker-ink: var(--marker-ink);
|
||||
--color-surface-0: var(--surface-0);
|
||||
--color-surface-1: var(--surface-1);
|
||||
--color-surface-2: var(--surface-2);
|
||||
--color-surface-elevated: var(--surface-elevated);
|
||||
--color-border-subtle: var(--border-subtle);
|
||||
--color-border-default: var(--border-default);
|
||||
--color-interactive-hover: var(--interactive-hover);
|
||||
@@ -206,12 +48,151 @@
|
||||
--color-success-muted: var(--success-muted);
|
||||
}
|
||||
|
||||
/*
|
||||
* Light: a quiet light table. Ink for primary actions, a highlighter
|
||||
* yellow reserved for what the AI just changed.
|
||||
*/
|
||||
:root {
|
||||
--radius: 0.75rem;
|
||||
|
||||
--canvas: #f4f5f7;
|
||||
--background: #f4f5f7;
|
||||
--foreground: #14181d;
|
||||
|
||||
--card: #ffffff;
|
||||
--card-foreground: #14181d;
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: #14181d;
|
||||
|
||||
--primary: #14181d;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #f1f3f5;
|
||||
--secondary-foreground: #14181d;
|
||||
--muted: #f1f3f5;
|
||||
--muted-foreground: #5d6672;
|
||||
--faint: #687180;
|
||||
--accent: #eef0f3;
|
||||
--accent-foreground: #14181d;
|
||||
--destructive: #c9372c;
|
||||
|
||||
--border: #e4e7eb;
|
||||
--input: #dfe3e8;
|
||||
--ring: #14181d;
|
||||
|
||||
--marker: #ffd84d;
|
||||
--marker-soft: #fff4bf;
|
||||
--marker-ink: #6b5200;
|
||||
|
||||
--surface-0: #ffffff;
|
||||
--surface-1: #f7f8fa;
|
||||
--surface-2: #f1f3f5;
|
||||
--border-subtle: #eceef1;
|
||||
--border-default: #e4e7eb;
|
||||
--interactive-hover: #f1f3f5;
|
||||
--interactive-active: #e7eaee;
|
||||
--success: #1f9e5a;
|
||||
--success-muted: #e3f5ea;
|
||||
|
||||
--shadow-float:
|
||||
0 1px 2px rgb(20 24 29 / 0.05), 0 10px 30px -8px rgb(20 24 29 / 0.14);
|
||||
--shadow-pop:
|
||||
0 1px 2px rgb(20 24 29 / 0.06), 0 18px 48px -12px rgb(20 24 29 / 0.22);
|
||||
|
||||
--duration-normal: 200ms;
|
||||
--ease-out: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
--ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Han characters are drawn differently in Simplified Chinese, Traditional
|
||||
* Chinese and Japanese: each language lists its own system fonts first.
|
||||
*/
|
||||
:root {
|
||||
--font-cjk:
|
||||
"PingFang SC", "Hiragino Sans GB", "Noto Sans CJK SC",
|
||||
"Microsoft YaHei", "Hiragino Sans", "Meiryo";
|
||||
}
|
||||
:root:lang(ja) {
|
||||
--font-cjk:
|
||||
"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Noto Sans CJK JP",
|
||||
"Yu Gothic UI", "Meiryo", "PingFang SC";
|
||||
}
|
||||
:root:lang(zh-Hant) {
|
||||
--font-cjk:
|
||||
"PingFang TC", "Noto Sans CJK TC", "Microsoft JhengHei",
|
||||
"Hiragino Sans", "PingFang SC";
|
||||
}
|
||||
|
||||
/*
|
||||
* Dark: a blueprint-blue table. Surfaces get lighter the higher they float.
|
||||
* The diagram stays on a white sheet so it looks the way it will export;
|
||||
* primary actions are paper-white, and amber only marks AI changes.
|
||||
*/
|
||||
.dark {
|
||||
/* Neutral greys: the canvas matches draw.io's own dark workspace */
|
||||
--canvas: #1b1d1e;
|
||||
--background: #1b1d1e;
|
||||
--foreground: #ececec;
|
||||
|
||||
--card: #242627;
|
||||
--card-foreground: #ececec;
|
||||
--popover: #2a2c2d;
|
||||
--popover-foreground: #ececec;
|
||||
|
||||
--primary: #ececec;
|
||||
--primary-foreground: #1b1d1e;
|
||||
--secondary: #2d2f30;
|
||||
--secondary-foreground: #ececec;
|
||||
--muted: #2d2f30;
|
||||
--muted-foreground: #a7a9aa;
|
||||
--faint: #8a8c8d;
|
||||
--accent: #353738;
|
||||
--accent-foreground: #ececec;
|
||||
--destructive: #f07167;
|
||||
|
||||
--border: rgb(255 255 255 / 0.1);
|
||||
--input: rgb(255 255 255 / 0.16);
|
||||
--ring: #ececec;
|
||||
|
||||
--marker: #f5b13d;
|
||||
--marker-soft: rgb(245 177 61 / 0.16);
|
||||
--marker-ink: #f7c46b;
|
||||
|
||||
--surface-0: #242627;
|
||||
--surface-1: #202223;
|
||||
--surface-2: #2d2f30;
|
||||
--border-subtle: rgb(255 255 255 / 0.08);
|
||||
--border-default: rgb(255 255 255 / 0.13);
|
||||
--interactive-hover: #353738;
|
||||
--interactive-active: #3c3e3f;
|
||||
--success: #4fd18b;
|
||||
--success-muted: rgb(79 209 139 / 0.14);
|
||||
|
||||
--shadow-float:
|
||||
0 0 0 1px rgb(255 255 255 / 0.07), 0 14px 34px -12px rgb(0 0 0 / 0.6);
|
||||
--shadow-pop:
|
||||
0 0 0 1px rgb(255 255 255 / 0.1), 0 22px 56px -14px rgb(0 0 0 / 0.7);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
html {
|
||||
color-scheme: light;
|
||||
}
|
||||
html.dark {
|
||||
color-scheme: dark;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground font-sans;
|
||||
font-size: 14px;
|
||||
line-height: 1.55;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
::selection {
|
||||
background: var(--marker-soft);
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,46 +202,66 @@
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
/* Custom scrollbar */
|
||||
@layer utilities {
|
||||
.scrollbar-thin {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: oklch(0.85 0.01 260) transparent;
|
||||
scrollbar-color: color-mix(in oklab, var(--foreground) 18%, transparent)
|
||||
transparent;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-thumb {
|
||||
background-color: oklch(0.85 0.01 260);
|
||||
background-color: color-mix(
|
||||
in oklab,
|
||||
var(--foreground) 18%,
|
||||
transparent
|
||||
);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-thumb:hover {
|
||||
background-color: oklch(0.75 0.01 260);
|
||||
background-color: color-mix(
|
||||
in oklab,
|
||||
var(--foreground) 30%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
/* Dark mode scrollbar */
|
||||
.dark .scrollbar-thin {
|
||||
scrollbar-color: oklch(0.35 0.015 260) transparent;
|
||||
/* Diagram pictures always render as on paper, also in dark mode
|
||||
(draw.io SVGs use light-dark() colors) */
|
||||
.sheet-light {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.dark .scrollbar-thin::-webkit-scrollbar-thumb {
|
||||
background-color: oklch(0.35 0.015 260);
|
||||
.shadow-float {
|
||||
box-shadow: var(--shadow-float);
|
||||
}
|
||||
|
||||
.dark .scrollbar-thin::-webkit-scrollbar-thumb:hover {
|
||||
background-color: oklch(0.45 0.015 260);
|
||||
.shadow-pop {
|
||||
box-shadow: var(--shadow-pop);
|
||||
}
|
||||
/* Older names kept for components that still use them */
|
||||
.shadow-soft {
|
||||
box-shadow: var(--shadow-float);
|
||||
}
|
||||
.shadow-dialog {
|
||||
box-shadow: var(--shadow-pop);
|
||||
}
|
||||
}
|
||||
|
||||
/* Smooth page transitions */
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes messageIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
@@ -271,121 +272,18 @@
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slideInRight {
|
||||
/* The first prompt moves from the middle of the canvas into the panel */
|
||||
@keyframes panelIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(16px);
|
||||
transform: translateX(12px) scale(0.985);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
transform: translateX(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-fade-in {
|
||||
animation: fadeIn 0.3s ease-out forwards;
|
||||
}
|
||||
|
||||
.animate-slide-in-right {
|
||||
animation: slideInRight 0.3s ease-out forwards;
|
||||
}
|
||||
|
||||
/* Message bubble animations */
|
||||
@keyframes messageIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(12px) scale(0.98);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-message-in {
|
||||
animation: messageIn 0.25s ease-out forwards;
|
||||
}
|
||||
|
||||
/* Subtle floating shadow for cards */
|
||||
.shadow-soft {
|
||||
box-shadow:
|
||||
0 1px 2px oklch(0.23 0.02 260 / 0.04),
|
||||
0 4px 12px oklch(0.23 0.02 260 / 0.06),
|
||||
0 8px 24px oklch(0.23 0.02 260 / 0.04);
|
||||
}
|
||||
|
||||
.shadow-soft-lg {
|
||||
box-shadow:
|
||||
0 2px 4px oklch(0.23 0.02 260 / 0.04),
|
||||
0 8px 20px oklch(0.23 0.02 260 / 0.08),
|
||||
0 16px 40px oklch(0.23 0.02 260 / 0.06);
|
||||
}
|
||||
|
||||
/* Gradient text utility */
|
||||
.text-gradient-primary {
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
oklch(0.55 0.18 265),
|
||||
oklch(0.6 0.2 290)
|
||||
);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
/* ============================================
|
||||
REFINED DIALOG STYLES
|
||||
============================================ */
|
||||
|
||||
/* Refined dialog shadow - multi-layer soft shadow */
|
||||
.shadow-dialog {
|
||||
box-shadow:
|
||||
0 0 0 1px oklch(0 0 0 / 0.03),
|
||||
0 2px 4px oklch(0 0 0 / 0.02),
|
||||
0 12px 24px oklch(0 0 0 / 0.06),
|
||||
0 24px 48px oklch(0 0 0 / 0.04);
|
||||
}
|
||||
|
||||
.dark .shadow-dialog {
|
||||
box-shadow:
|
||||
0 0 0 1px oklch(1 0 0 / 0.05),
|
||||
0 2px 4px oklch(0 0 0 / 0.2),
|
||||
0 12px 24px oklch(0 0 0 / 0.3),
|
||||
0 24px 48px oklch(0 0 0 / 0.2);
|
||||
}
|
||||
|
||||
/* Dialog animations */
|
||||
@keyframes dialog-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate(-50%, -48%) scale(0.96);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, -50%) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes dialog-out {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, -50%) scale(1);
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translate(-50%, -48%) scale(0.96);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-dialog-in {
|
||||
animation: dialog-in var(--duration-normal) var(--ease-out) forwards;
|
||||
}
|
||||
|
||||
.animate-dialog-out {
|
||||
animation: dialog-out 150ms var(--ease-out) forwards;
|
||||
}
|
||||
|
||||
/* Check pop animation for validation success */
|
||||
@keyframes check-pop {
|
||||
0% {
|
||||
transform: scale(0.8);
|
||||
@@ -400,14 +298,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
.animate-fade-in {
|
||||
animation: fadeIn 0.25s var(--ease-out) forwards;
|
||||
}
|
||||
.animate-message-in {
|
||||
animation: messageIn 0.22s var(--ease-out) forwards;
|
||||
}
|
||||
.animate-panel-in {
|
||||
animation: panelIn 0.32s var(--ease-out) both;
|
||||
}
|
||||
.animate-check-pop {
|
||||
animation: check-pop 0.25s var(--ease-spring) forwards;
|
||||
}
|
||||
|
||||
/* Reduced motion support */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.animate-dialog-in,
|
||||
.animate-dialog-out,
|
||||
.animate-fade-in,
|
||||
.animate-message-in,
|
||||
.animate-panel-in,
|
||||
.animate-check-pop {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { useParams } from "next/navigation"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { DrawioFrame } from "@/components/canvas/drawio-frame"
|
||||
import { SelectionAsk } from "@/components/canvas/selection-ask"
|
||||
import { useChatEngine } from "@/components/chat/chat-engine"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { DRAWIO_CSS, getDrawioSrc } from "@/lib/drawio/drawio-config"
|
||||
import { keepCenter, refitIfRecent } from "@/lib/drawio/editor-bridge"
|
||||
import { i18n, type Locale } from "@/lib/i18n/config"
|
||||
import { STORAGE_KEYS } from "@/lib/storage"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useCanvasStore } from "@/stores/canvas-store"
|
||||
import { useSettingsStore } from "@/stores/settings-store"
|
||||
|
||||
/**
|
||||
* The draw.io canvas, with draw.io's own toolbar, menus and page tabs, and
|
||||
* the "ask AI" button laid over it (only when the page can drive draw.io
|
||||
* directly, not with an external cross-origin draw.io).
|
||||
*/
|
||||
export function CanvasStage({
|
||||
className,
|
||||
style,
|
||||
hideOverlays = false,
|
||||
}: {
|
||||
className?: string
|
||||
style?: React.CSSProperties
|
||||
/** Hide the "ask AI" button (e.g. while the start screen covers the canvas) */
|
||||
hideOverlays?: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const params = useParams<{ lang: string }>()
|
||||
const lang = (
|
||||
i18n.locales.includes(params.lang as Locale)
|
||||
? params.lang
|
||||
: i18n.defaultLocale
|
||||
) as Locale
|
||||
const {
|
||||
drawioRef,
|
||||
handleDiagramAutoSave,
|
||||
handleDiagramExport,
|
||||
onDrawioLoad,
|
||||
resetDrawioReady,
|
||||
isDrawioReady,
|
||||
} = useDiagram()
|
||||
const engine = useChatEngine()
|
||||
const isDark = useSettingsStore((s) => s.isDark)
|
||||
const hasEditor = useCanvasStore((s) => s.hasEditor)
|
||||
// Canvas width when the chat panel starts sliding in or out
|
||||
const slideStartWidthRef = useRef(0)
|
||||
|
||||
const [src, setSrc] = useState<string | null>(null)
|
||||
// null until draw.io tells us whether we can drive it directly
|
||||
const [editorAccess, setEditorAccess] = useState<boolean | null>(null)
|
||||
const stageRef = useRef<HTMLDivElement>(null)
|
||||
const [size, setSize] = useState({ width: 0, height: 0 })
|
||||
|
||||
useEffect(() => {
|
||||
// The page is about to switch to the language picked last time
|
||||
// (useSavedLocale): load draw.io once, in that language
|
||||
const saved = localStorage.getItem(STORAGE_KEYS.locale)
|
||||
if (saved && saved !== lang && i18n.locales.includes(saved as Locale)) {
|
||||
return
|
||||
}
|
||||
const isElectron = !!(window as { electronAPI?: unknown }).electronAPI
|
||||
// The theme class is set before the page renders; the settings store
|
||||
// may not have read it yet
|
||||
const dark = document.documentElement.classList.contains("dark")
|
||||
setSrc(getDrawioSrc({ lang, isElectron, dark }))
|
||||
}, [lang])
|
||||
|
||||
// A new iframe starts over: draw.io reports load and access again
|
||||
useEffect(() => {
|
||||
resetDrawioReady()
|
||||
setEditorAccess(null)
|
||||
}, [src])
|
||||
|
||||
// Cross-origin draw.io only takes its dark mode when it starts: reload
|
||||
// it when that is not the theme now (also one switched while it
|
||||
// loaded). Same-origin switches it in place.
|
||||
useEffect(() => {
|
||||
if (editorAccess !== false || !src) return
|
||||
const startedDark = new URL(src).searchParams.get("dark") === "1"
|
||||
if (startedDark === isDark) return
|
||||
const isElectron = !!(window as { electronAPI?: unknown }).electronAPI
|
||||
setSrc(getDrawioSrc({ lang, isElectron, dark: isDark }))
|
||||
}, [isDark, editorAccess, lang, src])
|
||||
|
||||
useEffect(() => {
|
||||
const stage = stageRef.current
|
||||
if (!stage) return
|
||||
// React passes no transitionstart
|
||||
const onSlideStart = (event: TransitionEvent) => {
|
||||
if (event.target !== stage || event.propertyName !== "right") return
|
||||
slideStartWidthRef.current = stage.clientWidth
|
||||
}
|
||||
stage.addEventListener("transitionstart", onSlideStart)
|
||||
const observer = new ResizeObserver(([entry]) => {
|
||||
setSize({
|
||||
width: entry.contentRect.width,
|
||||
height: entry.contentRect.height,
|
||||
})
|
||||
refitIfRecent()
|
||||
})
|
||||
observer.observe(stage)
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
stage.removeEventListener("transitionstart", onSlideStart)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const showOverlays = hasEditor && isDrawioReady && !hideOverlays
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={stageRef}
|
||||
className={cn("absolute overflow-hidden bg-canvas", className)}
|
||||
style={style}
|
||||
data-testid="canvas-stage"
|
||||
// The chat panel slides in or out (the canvas's right edge moves):
|
||||
// once the canvas has its final size, fit a diagram just drawn,
|
||||
// or keep the view's middle
|
||||
onTransitionEnd={(event) => {
|
||||
if (event.target !== event.currentTarget) return
|
||||
if (event.propertyName !== "right") return
|
||||
const stage = event.currentTarget
|
||||
// Let draw.io take the new size first
|
||||
setTimeout(() => {
|
||||
if (refitIfRecent(4000)) return
|
||||
keepCenter(slideStartWidthRef.current, stage.clientWidth)
|
||||
}, 60)
|
||||
}}
|
||||
>
|
||||
{src && (
|
||||
<DrawioFrame
|
||||
key={src}
|
||||
ref={drawioRef}
|
||||
src={src}
|
||||
configCss={DRAWIO_CSS}
|
||||
editorCss={DRAWIO_CSS}
|
||||
dark={isDark}
|
||||
onLoad={onDrawioLoad}
|
||||
onAutoSave={handleDiagramAutoSave}
|
||||
onExport={handleDiagramExport}
|
||||
onEditorAccess={setEditorAccess}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Covers the iframe until draw.io has loaded and been styled */}
|
||||
{(!isDrawioReady || editorAccess === null) && (
|
||||
<div
|
||||
className="absolute inset-0 flex items-center justify-center bg-canvas"
|
||||
data-testid="canvas-loading"
|
||||
>
|
||||
<div className="flex items-center gap-2.5 text-[13px] text-muted-foreground">
|
||||
<span className="size-3.5 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-muted-foreground" />
|
||||
{dict.workspace.canvasLoading}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showOverlays && (
|
||||
<SelectionAsk
|
||||
width={size.width}
|
||||
height={size.height}
|
||||
hidden={engine.isBusy}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
"use client"
|
||||
|
||||
import { forwardRef, useEffect, useImperativeHandle, useRef } from "react"
|
||||
import {
|
||||
DRAWIO_CONFIG,
|
||||
EMPTY_DRAWIO_DOCUMENT,
|
||||
} from "@/lib/drawio/drawio-config"
|
||||
import {
|
||||
attachEditor,
|
||||
detachEditor,
|
||||
watchForEditorUi,
|
||||
} from "@/lib/drawio/editor-bridge"
|
||||
|
||||
export interface DrawioExportEvent {
|
||||
event: "export"
|
||||
format: string
|
||||
data: string
|
||||
xml: string
|
||||
message: { message?: string; [key: string]: unknown }
|
||||
}
|
||||
|
||||
export interface DrawioFrameHandle {
|
||||
load: (data: { xml: string }) => void
|
||||
exportDiagram: (data: {
|
||||
format: string
|
||||
message?: string
|
||||
[key: string]: unknown
|
||||
}) => void
|
||||
}
|
||||
|
||||
interface DrawioFrameProps {
|
||||
src: string
|
||||
/** CSS sent with the configure message (works cross-origin too) */
|
||||
configCss: string
|
||||
/** CSS injected once the editor is reachable directly (same origin) */
|
||||
editorCss: string
|
||||
/** draw.io's dark mode, switched in place when the editor is reachable */
|
||||
dark: boolean
|
||||
onLoad?: () => void
|
||||
onAutoSave?: (data: { xml?: string }) => void
|
||||
onExport?: (data: DrawioExportEvent) => void
|
||||
/** Called once we know whether the editor can be driven directly */
|
||||
onEditorAccess?: (hasEditor: boolean) => void
|
||||
}
|
||||
|
||||
const STYLE_ID = "next-ai-drawio-theme"
|
||||
|
||||
/**
|
||||
* The draw.io editor in an iframe, speaking draw.io's postMessage embed
|
||||
* protocol (same messages react-drawio used). When the iframe is same-origin
|
||||
* it also hands the editor object to editor-bridge for direct control.
|
||||
*/
|
||||
export const DrawioFrame = forwardRef<DrawioFrameHandle, DrawioFrameProps>(
|
||||
function DrawioFrame(
|
||||
{
|
||||
src,
|
||||
configCss,
|
||||
editorCss,
|
||||
dark,
|
||||
onLoad,
|
||||
onAutoSave,
|
||||
onExport,
|
||||
onEditorAccess,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
const editorUiRef = useRef<any>(null)
|
||||
const attachedRef = useRef(false)
|
||||
const configCssRef = useRef(configCss)
|
||||
configCssRef.current = configCss
|
||||
const editorCssRef = useRef(editorCss)
|
||||
editorCssRef.current = editorCss
|
||||
const darkRef = useRef(dark)
|
||||
darkRef.current = dark
|
||||
// Handlers change on every render; the message listener reads refs
|
||||
const handlersRef = useRef({
|
||||
onLoad,
|
||||
onAutoSave,
|
||||
onExport,
|
||||
onEditorAccess,
|
||||
})
|
||||
handlersRef.current = { onLoad, onAutoSave, onExport, onEditorAccess }
|
||||
|
||||
// draw.io's origin: messages go only there, and only its messages
|
||||
// count (the frame could be navigated to another site)
|
||||
// (read on use: there is no window while the page renders on the server)
|
||||
const drawioOrigin = () => new URL(src, window.location.href).origin
|
||||
|
||||
const send = (action: string, data: Record<string, unknown> = {}) => {
|
||||
iframeRef.current?.contentWindow?.postMessage(
|
||||
JSON.stringify({ action, ...data }),
|
||||
drawioOrigin(),
|
||||
)
|
||||
}
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
load: ({ xml }) => send("load", { xml, autosave: 1 }),
|
||||
exportDiagram: (data) => send("export", data),
|
||||
}))
|
||||
|
||||
// Same-origin only: keep the theme CSS current without a reload
|
||||
const applyThemeCss = () => {
|
||||
if (!attachedRef.current) return
|
||||
try {
|
||||
const doc = iframeRef.current?.contentDocument
|
||||
if (!doc?.head) return
|
||||
let style = doc.getElementById(STYLE_ID)
|
||||
if (!style) {
|
||||
style = doc.createElement("style")
|
||||
style.id = STYLE_ID
|
||||
doc.head.appendChild(style)
|
||||
}
|
||||
style.textContent = editorCssRef.current
|
||||
} catch {
|
||||
// Cross-origin: the configure message already applied it
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
applyThemeCss()
|
||||
}, [editorCss])
|
||||
|
||||
// Same-origin only: draw.io's own dark mode, without a reload
|
||||
const applyDarkMode = () => {
|
||||
if (!attachedRef.current) return
|
||||
try {
|
||||
// Runs on every load: switch only when it differs
|
||||
const frameWindow = iframeRef.current?.contentWindow as any
|
||||
if (frameWindow?.Editor?.isDarkMode?.() === darkRef.current) {
|
||||
return
|
||||
}
|
||||
editorUiRef.current?.setDarkMode?.(darkRef.current)
|
||||
} catch (error) {
|
||||
console.warn("Failed to set draw.io's dark mode:", error)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
applyDarkMode()
|
||||
}, [dark])
|
||||
|
||||
useEffect(() => {
|
||||
const iframe = iframeRef.current
|
||||
if (!iframe) return
|
||||
editorUiRef.current = null
|
||||
attachedRef.current = false
|
||||
let reported: boolean | null = null
|
||||
const report = (value: boolean) => {
|
||||
if (reported === value) return
|
||||
reported = value
|
||||
handlersRef.current.onEditorAccess?.(value)
|
||||
}
|
||||
|
||||
// Watch for draw.io's scripts so the editor object can be caught
|
||||
// as it starts. Stops once hooked, or when the frame turns out to
|
||||
// be cross-origin.
|
||||
const startedAt = Date.now()
|
||||
const poll = setInterval(() => {
|
||||
const frameWindow = iframe.contentWindow as any
|
||||
if (!frameWindow) return
|
||||
let ready = false
|
||||
try {
|
||||
ready =
|
||||
frameWindow.location.href !== "about:blank" &&
|
||||
!!frameWindow.EditorUi
|
||||
} catch {
|
||||
clearInterval(poll)
|
||||
report(false)
|
||||
return
|
||||
}
|
||||
if (ready) {
|
||||
clearInterval(poll)
|
||||
// Called on every action state update: once per editor
|
||||
const ok = watchForEditorUi(frameWindow, (ui) => {
|
||||
if (editorUiRef.current === ui) return
|
||||
editorUiRef.current = ui
|
||||
// draw.io follows the system's theme on its own:
|
||||
// keep the app's
|
||||
ui.addListener?.("darkModeChanged", () =>
|
||||
applyDarkMode(),
|
||||
)
|
||||
})
|
||||
if (!ok) report(false)
|
||||
} else if (Date.now() - startedAt > 60_000) {
|
||||
clearInterval(poll)
|
||||
}
|
||||
}, 5)
|
||||
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
if (event.source !== iframe.contentWindow) return
|
||||
if (event.origin !== drawioOrigin()) return
|
||||
if (typeof event.data !== "string") return
|
||||
let data: any
|
||||
try {
|
||||
data = JSON.parse(event.data)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const handlers = handlersRef.current
|
||||
switch (data.event) {
|
||||
case "init":
|
||||
send("load", {
|
||||
xml: EMPTY_DRAWIO_DOCUMENT,
|
||||
autosave: 1,
|
||||
})
|
||||
break
|
||||
case "configure":
|
||||
send("configure", {
|
||||
config: {
|
||||
...DRAWIO_CONFIG,
|
||||
css: configCssRef.current,
|
||||
},
|
||||
})
|
||||
break
|
||||
case "load": {
|
||||
const tryAttach = () => {
|
||||
const ui = editorUiRef.current
|
||||
if (!ui || !iframe.contentWindow) return false
|
||||
attachEditor(ui, iframe.contentWindow)
|
||||
attachedRef.current = true
|
||||
applyThemeCss()
|
||||
applyDarkMode()
|
||||
report(true)
|
||||
return true
|
||||
}
|
||||
// The editor object is usually caught before the
|
||||
// first load; give it a moment, then fall back to
|
||||
// draw.io's own toolbar
|
||||
if (!tryAttach()) {
|
||||
setTimeout(() => {
|
||||
if (!tryAttach()) report(false)
|
||||
}, 800)
|
||||
}
|
||||
handlers.onLoad?.()
|
||||
break
|
||||
}
|
||||
case "autosave":
|
||||
handlers.onAutoSave?.(data)
|
||||
break
|
||||
case "export":
|
||||
handlers.onExport?.(data)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("message", handleMessage)
|
||||
return () => {
|
||||
clearInterval(poll)
|
||||
window.removeEventListener("message", handleMessage)
|
||||
detachEditor()
|
||||
}
|
||||
}, [src])
|
||||
|
||||
return (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={src}
|
||||
title="draw.io"
|
||||
allow="clipboard-read; clipboard-write"
|
||||
className="block h-full w-full border-0"
|
||||
/>
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Sparkles } from "lucide-react"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { modKey } from "@/lib/platform"
|
||||
import { useCanvasStore } from "@/stores/canvas-store"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
|
||||
const BUTTON_HEIGHT = 32
|
||||
const GAP = 10
|
||||
|
||||
/**
|
||||
* "Ask AI to change this" next to the selected shapes. Clicking it moves
|
||||
* focus to the chat input, where the selection already shows as a chip.
|
||||
*/
|
||||
export function SelectionAsk({
|
||||
width,
|
||||
height,
|
||||
hidden,
|
||||
}: {
|
||||
/** Size of the canvas area, for keeping the button inside it */
|
||||
width: number
|
||||
height: number
|
||||
hidden: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const rect = useCanvasStore((s) => s.selectionRect)
|
||||
const selection = useCanvasStore((s) => s.selection)
|
||||
const isFreehand = useCanvasStore((s) => s.isFreehand)
|
||||
const popupOpen = useCanvasStore((s) => s.isDrawioPopupOpen)
|
||||
const focusComposer = useUiStore((s) => s.focusComposer)
|
||||
|
||||
if (hidden || popupOpen || !rect || selection.length === 0 || isFreehand) {
|
||||
return null
|
||||
}
|
||||
// Selection scrolled out of view
|
||||
if (
|
||||
rect.x + rect.width < 0 ||
|
||||
rect.y + rect.height < 0 ||
|
||||
rect.x > width ||
|
||||
rect.y > height
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Above the selection's top-right corner, kept inside the canvas
|
||||
const approxWidth = 168
|
||||
const left = Math.min(
|
||||
Math.max(8, rect.x + rect.width - approxWidth / 2),
|
||||
width - approxWidth - 8,
|
||||
)
|
||||
const above = rect.y - BUTTON_HEIGHT - GAP
|
||||
const top =
|
||||
above > 64
|
||||
? above
|
||||
: Math.min(rect.y + rect.height + GAP, height - BUTTON_HEIGHT - 72)
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={focusComposer}
|
||||
className="pointer-events-auto absolute z-10 flex h-8 items-center gap-1.5 rounded-xl bg-card pr-2.5 pl-2 text-[13px] font-medium text-foreground shadow-pop transition-transform animate-fade-in hover:-translate-y-px"
|
||||
style={{ left, top }}
|
||||
data-testid="selection-ask"
|
||||
>
|
||||
<Sparkles className="size-4 text-marker-ink" />
|
||||
{dict.workspace.askAi}
|
||||
<kbd className="ml-1 font-sans text-[11px] text-muted-foreground">
|
||||
{modKey}/
|
||||
</kbd>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
Cloud,
|
||||
FileText,
|
||||
GitBranch,
|
||||
Palette,
|
||||
Terminal,
|
||||
Zap,
|
||||
} from "lucide-react"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { getAssetUrl } from "@/lib/base-path"
|
||||
|
||||
interface ExampleCardProps {
|
||||
icon: React.ReactNode
|
||||
title: string
|
||||
description: string
|
||||
onClick: () => void
|
||||
isNew?: boolean
|
||||
}
|
||||
|
||||
function ExampleCard({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
onClick,
|
||||
isNew,
|
||||
}: ExampleCardProps) {
|
||||
const dict = useDictionary()
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={`group w-full text-left p-4 rounded-xl border bg-card hover:bg-accent/50 hover:border-primary/30 transition-all duration-200 hover:shadow-sm ${
|
||||
isNew
|
||||
? "border-primary/40 ring-1 ring-primary/20"
|
||||
: "border-border/60"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div
|
||||
className={`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 transition-colors ${
|
||||
isNew
|
||||
? "bg-primary/20 group-hover:bg-primary/25"
|
||||
: "bg-primary/10 group-hover:bg-primary/15"
|
||||
}`}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-sm font-medium text-foreground group-hover:text-primary transition-colors">
|
||||
{title}
|
||||
</h3>
|
||||
{isNew && (
|
||||
<span className="px-1.5 py-0.5 text-[10px] font-semibold bg-primary text-primary-foreground rounded">
|
||||
{dict.common.new}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ExamplePanel({
|
||||
setInput,
|
||||
setFiles,
|
||||
minimal = false,
|
||||
}: {
|
||||
setInput: (input: string) => void
|
||||
setFiles: (files: File[]) => void
|
||||
minimal?: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const isSelfHosted = process.env.NEXT_PUBLIC_SELFHOSTED === "true"
|
||||
|
||||
const handleReplicateFlowchart = async () => {
|
||||
setInput("Replicate this flowchart.")
|
||||
|
||||
try {
|
||||
const response = await fetch(getAssetUrl("/example.png"))
|
||||
const blob = await response.blob()
|
||||
const file = new File([blob], "example.png", { type: "image/png" })
|
||||
setFiles([file])
|
||||
} catch (error) {
|
||||
console.error(dict.errors.failedToLoadExample, error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReplicateArchitecture = async () => {
|
||||
setInput("Replicate this in aws style")
|
||||
|
||||
try {
|
||||
const response = await fetch(getAssetUrl("/architecture.png"))
|
||||
const blob = await response.blob()
|
||||
const file = new File([blob], "architecture.png", {
|
||||
type: "image/png",
|
||||
})
|
||||
setFiles([file])
|
||||
} catch (error) {
|
||||
console.error(dict.errors.failedToLoadExample, error)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePdfExample = async () => {
|
||||
setInput("Summarize this paper as a diagram")
|
||||
|
||||
try {
|
||||
const response = await fetch(getAssetUrl("/chain-of-thought.txt"))
|
||||
const blob = await response.blob()
|
||||
const file = new File([blob], "chain-of-thought.txt", {
|
||||
type: "text/plain",
|
||||
})
|
||||
setFiles([file])
|
||||
} catch (error) {
|
||||
console.error(dict.errors.failedToLoadExample, error)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={minimal ? "" : "py-6 px-2 animate-fade-in"}>
|
||||
{!minimal && (
|
||||
<>
|
||||
{/* MCP Server Notice, hidden on self-hosted deployments */}
|
||||
{!isSelfHosted && (
|
||||
<a
|
||||
href="https://github.com/DayuanJiang/next-ai-draw-io/tree/main/packages/mcp-server"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block mb-4 p-3 rounded-xl bg-gradient-to-r from-purple-500/10 to-blue-500/10 border border-purple-500/20 hover:border-purple-500/40 transition-colors group"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded-lg bg-purple-500/20 flex items-center justify-center shrink-0">
|
||||
<Terminal className="w-4 h-4 text-purple-500" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-foreground group-hover:text-purple-500 transition-colors">
|
||||
{dict.examples.mcpServer}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.examples.mcpDescription}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{/* Welcome section */}
|
||||
<div className="text-center mb-6">
|
||||
<h2 className="text-lg font-semibold text-foreground mb-2">
|
||||
{dict.examples.title}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground max-w-xs mx-auto">
|
||||
{dict.examples.subtitle}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Examples grid */}
|
||||
<div className="space-y-3">
|
||||
{!minimal && (
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wider px-1">
|
||||
{dict.examples.quickExamples}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="grid gap-2">
|
||||
<ExampleCard
|
||||
icon={<FileText className="w-4 h-4 text-primary" />}
|
||||
title={dict.examples.paperToDiagram}
|
||||
description={dict.examples.paperDescription}
|
||||
onClick={handlePdfExample}
|
||||
isNew
|
||||
/>
|
||||
|
||||
<ExampleCard
|
||||
icon={<Zap className="w-4 h-4 text-primary" />}
|
||||
title={dict.examples.animatedDiagram}
|
||||
description={dict.examples.animatedDescription}
|
||||
onClick={() => {
|
||||
setInput(
|
||||
"Give me a **animated connector** diagram of transformer's architecture",
|
||||
)
|
||||
setFiles([])
|
||||
}}
|
||||
/>
|
||||
|
||||
<ExampleCard
|
||||
icon={<Cloud className="w-4 h-4 text-primary" />}
|
||||
title={dict.examples.awsArchitecture}
|
||||
description={dict.examples.awsDescription}
|
||||
onClick={handleReplicateArchitecture}
|
||||
/>
|
||||
|
||||
<ExampleCard
|
||||
icon={<GitBranch className="w-4 h-4 text-primary" />}
|
||||
title={dict.examples.replicateFlowchart}
|
||||
description={dict.examples.replicateDescription}
|
||||
onClick={handleReplicateFlowchart}
|
||||
/>
|
||||
|
||||
<ExampleCard
|
||||
icon={<Palette className="w-4 h-4 text-primary" />}
|
||||
title={dict.examples.creativeDrawing}
|
||||
description={dict.examples.creativeDescription}
|
||||
onClick={() => {
|
||||
setInput("Draw a cat for me")
|
||||
setFiles([])
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-[11px] text-muted-foreground/60 text-center mt-4">
|
||||
{dict.examples.cachedNote}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,669 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
BookmarkPlus,
|
||||
Download,
|
||||
History,
|
||||
Image as ImageIcon,
|
||||
Link,
|
||||
Send,
|
||||
Square,
|
||||
} from "lucide-react"
|
||||
import type React from "react"
|
||||
import {
|
||||
type Dispatch,
|
||||
forwardRef,
|
||||
type SetStateAction,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
import { toast } from "sonner"
|
||||
import { ButtonWithTooltip } from "@/components/button-with-tooltip"
|
||||
import { TemplateCreateDialog } from "@/components/chat/TemplateCreateDialog"
|
||||
import { ErrorToast } from "@/components/error-toast"
|
||||
import { HistoryDialog } from "@/components/history-dialog"
|
||||
import { ModelSelector } from "@/components/model-selector"
|
||||
import { SaveDialog } from "@/components/save-dialog"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { UrlInputDialog } from "@/components/url-input-dialog"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { isPdfFile, isTextFile } from "@/lib/pdf-utils"
|
||||
import { STORAGE_KEYS } from "@/lib/storage"
|
||||
import type { FlattenedModel } from "@/lib/types/model-config"
|
||||
import { extractUrlContent, type UrlData } from "@/lib/url-utils"
|
||||
import { isRealDiagram } from "@/lib/utils"
|
||||
import { FilePreviewList } from "./file-preview-list"
|
||||
|
||||
const MAX_IMAGE_SIZE = 2 * 1024 * 1024 // 2MB
|
||||
const MAX_FILES = 5
|
||||
// Image formats every supported model provider accepts (SVG is read as text)
|
||||
const SUPPORTED_IMAGE_TYPES = [
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
]
|
||||
|
||||
function isValidFileType(file: File): boolean {
|
||||
return (
|
||||
SUPPORTED_IMAGE_TYPES.includes(file.type) ||
|
||||
isPdfFile(file) ||
|
||||
isTextFile(file)
|
||||
)
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
const mb = bytes / 1024 / 1024
|
||||
if (mb < 0.01) return `${(bytes / 1024).toFixed(0)}KB`
|
||||
return `${mb.toFixed(2)}MB`
|
||||
}
|
||||
|
||||
function showErrorToast(message: React.ReactNode) {
|
||||
toast.custom(
|
||||
(t) => (
|
||||
<ErrorToast message={message} onDismiss={() => toast.dismiss(t)} />
|
||||
),
|
||||
{ duration: 5000 },
|
||||
)
|
||||
}
|
||||
|
||||
interface ValidationResult {
|
||||
validFiles: File[]
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
function validateFiles(
|
||||
newFiles: File[],
|
||||
existingCount: number,
|
||||
dict: any,
|
||||
): ValidationResult {
|
||||
const errors: string[] = []
|
||||
const validFiles: File[] = []
|
||||
|
||||
const availableSlots = MAX_FILES - existingCount
|
||||
|
||||
if (availableSlots <= 0) {
|
||||
errors.push(formatMessage(dict.errors.maxFiles, { max: MAX_FILES }))
|
||||
return { validFiles, errors }
|
||||
}
|
||||
|
||||
for (const file of newFiles) {
|
||||
if (validFiles.length >= availableSlots) {
|
||||
errors.push(
|
||||
formatMessage(dict.errors.onlyMoreAllowed, {
|
||||
slots: availableSlots,
|
||||
}),
|
||||
)
|
||||
break
|
||||
}
|
||||
if (!isValidFileType(file)) {
|
||||
errors.push(
|
||||
formatMessage(dict.errors.unsupportedType, { name: file.name }),
|
||||
)
|
||||
continue
|
||||
}
|
||||
// Only check size for images (PDFs/text files are extracted client-side, so file size doesn't matter)
|
||||
const isExtractedFile = isPdfFile(file) || isTextFile(file)
|
||||
if (!isExtractedFile && file.size > MAX_IMAGE_SIZE) {
|
||||
const maxSizeMB = MAX_IMAGE_SIZE / 1024 / 1024
|
||||
errors.push(
|
||||
formatMessage(dict.errors.fileExceeds, {
|
||||
name: file.name,
|
||||
size: formatFileSize(file.size),
|
||||
max: maxSizeMB,
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
validFiles.push(file)
|
||||
}
|
||||
}
|
||||
|
||||
return { validFiles, errors }
|
||||
}
|
||||
|
||||
function showValidationErrors(errors: string[], dict: any) {
|
||||
if (errors.length === 0) return
|
||||
|
||||
if (errors.length === 1) {
|
||||
showErrorToast(
|
||||
<span className="text-muted-foreground">{errors[0]}</span>,
|
||||
)
|
||||
} else {
|
||||
showErrorToast(
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="font-medium">
|
||||
{formatMessage(dict.errors.filesRejected, {
|
||||
count: errors.length,
|
||||
})}
|
||||
</span>
|
||||
<ul className="text-muted-foreground text-xs list-disc list-inside">
|
||||
{errors.slice(0, 3).map((err) => (
|
||||
<li key={err}>{err}</li>
|
||||
))}
|
||||
{errors.length > 3 && (
|
||||
<li>
|
||||
{formatMessage(dict.errors.andMore, {
|
||||
count: errors.length - 3,
|
||||
})}
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChatInputRef {
|
||||
focus: () => void
|
||||
}
|
||||
|
||||
interface ChatInputProps {
|
||||
input: string
|
||||
status: "submitted" | "streaming" | "ready" | "error"
|
||||
onSubmit: (e: React.FormEvent<HTMLFormElement>) => void
|
||||
onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
|
||||
onStop?: () => void
|
||||
files?: File[]
|
||||
onFileChange?: (files: File[]) => void
|
||||
pdfData?: Map<
|
||||
File,
|
||||
{ text: string; charCount: number; isExtracting: boolean }
|
||||
>
|
||||
urlData?: Map<string, UrlData>
|
||||
onUrlChange?: Dispatch<SetStateAction<Map<string, UrlData>>>
|
||||
|
||||
sessionId?: string
|
||||
error?: Error | null
|
||||
// Model selector props
|
||||
models?: FlattenedModel[]
|
||||
selectedModelId?: string
|
||||
onModelSelect?: (modelId: string | undefined) => void
|
||||
onConfigureModels?: () => void
|
||||
showUnvalidatedModels?: boolean
|
||||
// Focus control props
|
||||
shouldFocus?: boolean
|
||||
onFocused?: () => void
|
||||
}
|
||||
|
||||
export const ChatInput = forwardRef<ChatInputRef, ChatInputProps>(
|
||||
function ChatInput(
|
||||
{
|
||||
input,
|
||||
status,
|
||||
onSubmit,
|
||||
onChange,
|
||||
onStop,
|
||||
files = [],
|
||||
onFileChange = () => {},
|
||||
pdfData = new Map(),
|
||||
urlData,
|
||||
onUrlChange,
|
||||
sessionId,
|
||||
error = null,
|
||||
models = [],
|
||||
selectedModelId,
|
||||
onModelSelect = () => {},
|
||||
onConfigureModels,
|
||||
showUnvalidatedModels = false,
|
||||
shouldFocus = false,
|
||||
onFocused,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const dict = useDictionary()
|
||||
const {
|
||||
chartXML,
|
||||
diagramHistory,
|
||||
saveDiagramToFile,
|
||||
showSaveDialog,
|
||||
setShowSaveDialog,
|
||||
} = useDiagram()
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
// Expose focus method via ref
|
||||
useImperativeHandle(ref, () => ({
|
||||
focus: () => {
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
}))
|
||||
|
||||
// Focus the textarea when shouldFocus becomes true
|
||||
// Use setTimeout to ensure focus happens after drawio iframe settles
|
||||
useEffect(() => {
|
||||
if (shouldFocus) {
|
||||
const timer = setTimeout(() => {
|
||||
textareaRef.current?.focus()
|
||||
onFocused?.()
|
||||
}, 150)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [shouldFocus, onFocused])
|
||||
|
||||
const [showHistory, setShowHistory] = useState(false)
|
||||
const [showUrlDialog, setShowUrlDialog] = useState(false)
|
||||
const [showSaveAsTemplate, setShowSaveAsTemplate] = useState(false)
|
||||
const [isExtractingUrl, setIsExtractingUrl] = useState(false)
|
||||
const [sendShortcut, setSendShortcut] = useState("ctrl-enter")
|
||||
// Allow retry when there's an error (even if status is still "streaming" or "submitted")
|
||||
const isDisabled =
|
||||
(status === "streaming" || status === "submitted") && !error
|
||||
// Block sending until attached files and URLs have their text, otherwise
|
||||
// their content would be silently dropped
|
||||
const isExtractingAttachments =
|
||||
files.some((file) => pdfData.get(file)?.isExtracting) ||
|
||||
Array.from(urlData?.values() ?? []).some((d) => d.isExtracting)
|
||||
|
||||
const adjustTextareaHeight = useCallback(() => {
|
||||
const textarea = textareaRef.current
|
||||
if (textarea) {
|
||||
textarea.style.height = "auto"
|
||||
textarea.style.height = `${Math.min(textarea.scrollHeight, 200)}px`
|
||||
}
|
||||
}, [])
|
||||
// Handle programmatic input changes (e.g., setInput("") after form submission)
|
||||
useEffect(() => {
|
||||
adjustTextareaHeight()
|
||||
}, [input, adjustTextareaHeight])
|
||||
|
||||
// Load send shortcut preference from localStorage and listen for changes
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEYS.sendShortcut)
|
||||
if (stored) setSendShortcut(stored)
|
||||
|
||||
const handleChange = (e: CustomEvent<string>) =>
|
||||
setSendShortcut(e.detail)
|
||||
window.addEventListener(
|
||||
"sendShortcutChange",
|
||||
handleChange as EventListener,
|
||||
)
|
||||
return () =>
|
||||
window.removeEventListener(
|
||||
"sendShortcutChange",
|
||||
handleChange as EventListener,
|
||||
)
|
||||
}, [])
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
onChange(e)
|
||||
adjustTextareaHeight()
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
// Enter that confirms an IME candidate must not send the message
|
||||
if (e.nativeEvent.isComposing || e.keyCode === 229) return
|
||||
|
||||
const shouldSend =
|
||||
sendShortcut === "enter"
|
||||
? e.key === "Enter" &&
|
||||
!e.shiftKey &&
|
||||
!e.ctrlKey &&
|
||||
!e.metaKey
|
||||
: (e.metaKey || e.ctrlKey) && e.key === "Enter"
|
||||
|
||||
if (shouldSend) {
|
||||
e.preventDefault()
|
||||
const form = e.currentTarget.closest("form")
|
||||
if (
|
||||
form &&
|
||||
input.trim() &&
|
||||
!isDisabled &&
|
||||
!isExtractingAttachments
|
||||
) {
|
||||
form.requestSubmit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handlePaste = async (e: React.ClipboardEvent) => {
|
||||
if (isDisabled) return
|
||||
|
||||
const items = e.clipboardData.items
|
||||
const imageItems = Array.from(items).filter((item) =>
|
||||
item.type.startsWith("image/"),
|
||||
)
|
||||
|
||||
if (imageItems.length > 0) {
|
||||
const imageFiles = (
|
||||
await Promise.all(
|
||||
imageItems.map(async (item, index) => {
|
||||
const file = item.getAsFile()
|
||||
if (!file) return null
|
||||
return new File(
|
||||
[file],
|
||||
`pasted-image-${Date.now()}-${index}.${file.type.split("/")[1]}`,
|
||||
{ type: file.type },
|
||||
)
|
||||
}),
|
||||
)
|
||||
).filter((f): f is File => f !== null)
|
||||
|
||||
const { validFiles, errors } = validateFiles(
|
||||
imageFiles,
|
||||
files.length,
|
||||
dict,
|
||||
)
|
||||
showValidationErrors(errors, dict)
|
||||
if (validFiles.length > 0) {
|
||||
onFileChange([...files, ...validFiles])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newFiles = Array.from(e.target.files || [])
|
||||
const { validFiles, errors } = validateFiles(
|
||||
newFiles,
|
||||
files.length,
|
||||
dict,
|
||||
)
|
||||
showValidationErrors(errors, dict)
|
||||
if (validFiles.length > 0) {
|
||||
onFileChange([...files, ...validFiles])
|
||||
}
|
||||
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ""
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveFile = (fileToRemove: File) => {
|
||||
onFileChange(files.filter((file) => file !== fileToRemove))
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ""
|
||||
}
|
||||
}
|
||||
|
||||
const triggerFileInput = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleDragOver = (e: React.DragEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: React.DragEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(false)
|
||||
}
|
||||
|
||||
const handleDrop = (e: React.DragEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(false)
|
||||
|
||||
if (isDisabled) return
|
||||
|
||||
// Let validateFiles show a toast for unsupported types
|
||||
const { validFiles, errors } = validateFiles(
|
||||
Array.from(e.dataTransfer.files),
|
||||
files.length,
|
||||
dict,
|
||||
)
|
||||
showValidationErrors(errors, dict)
|
||||
if (validFiles.length > 0) {
|
||||
onFileChange([...files, ...validFiles])
|
||||
}
|
||||
}
|
||||
|
||||
const handleUrlExtract = async (url: string) => {
|
||||
if (!onUrlChange) return
|
||||
|
||||
setIsExtractingUrl(true)
|
||||
|
||||
// Use functional updates so a removal or send made while extracting
|
||||
// is not overwritten when the request finishes
|
||||
try {
|
||||
onUrlChange((prev) =>
|
||||
new Map(prev).set(url, {
|
||||
url,
|
||||
title: url,
|
||||
content: "",
|
||||
charCount: 0,
|
||||
isExtracting: true,
|
||||
}),
|
||||
)
|
||||
|
||||
const data = await extractUrlContent(url)
|
||||
|
||||
// Skip if the URL was removed while extracting
|
||||
onUrlChange((prev) =>
|
||||
prev.has(url) ? new Map(prev).set(url, data) : prev,
|
||||
)
|
||||
|
||||
setShowUrlDialog(false)
|
||||
} catch (error) {
|
||||
// Remove the URL from the data map on error
|
||||
onUrlChange((prev) => {
|
||||
const next = new Map(prev)
|
||||
next.delete(url)
|
||||
return next
|
||||
})
|
||||
showErrorToast(
|
||||
<span className="text-muted-foreground">
|
||||
{error instanceof Error
|
||||
? error.message
|
||||
: "Failed to extract URL content"}
|
||||
</span>,
|
||||
)
|
||||
} finally {
|
||||
setIsExtractingUrl(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
id="chat-form"
|
||||
onSubmit={onSubmit}
|
||||
className={`w-full transition-all duration-200 ${
|
||||
isDragging
|
||||
? "ring-2 ring-primary ring-offset-2 rounded-2xl"
|
||||
: ""
|
||||
}`}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
{/* File & URL previews */}
|
||||
{(files.length > 0 || (urlData && urlData.size > 0)) && (
|
||||
<div className="mb-3">
|
||||
<FilePreviewList
|
||||
files={files}
|
||||
onRemoveFile={handleRemoveFile}
|
||||
pdfData={pdfData}
|
||||
urlData={urlData}
|
||||
onRemoveUrl={
|
||||
onUrlChange
|
||||
? (url) =>
|
||||
onUrlChange((prev) => {
|
||||
const next = new Map(prev)
|
||||
next.delete(url)
|
||||
return next
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="relative rounded-2xl border border-border bg-background shadow-sm focus-within:ring-2 focus-within:ring-primary/20 focus-within:border-primary/50 transition-all duration-200">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
placeholder={dict.chat.placeholder}
|
||||
disabled={isDisabled}
|
||||
aria-label="Chat input"
|
||||
className="min-h-[60px] max-h-[200px] resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground/60 scrollbar-thin"
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-end gap-1 px-3 py-2 border-t border-border/50">
|
||||
<div className="flex items-center gap-1 overflow-x-hidden">
|
||||
<ButtonWithTooltip
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowHistory(true)}
|
||||
disabled={
|
||||
isDisabled || diagramHistory.length === 0
|
||||
}
|
||||
tooltipContent={dict.chat.diagramHistory}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
</ButtonWithTooltip>
|
||||
|
||||
<ButtonWithTooltip
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowSaveDialog(true)}
|
||||
disabled={
|
||||
isDisabled || !isRealDiagram(chartXML)
|
||||
}
|
||||
tooltipContent={dict.chat.saveDiagram}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
</ButtonWithTooltip>
|
||||
|
||||
<ButtonWithTooltip
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={triggerFileInput}
|
||||
disabled={isDisabled}
|
||||
tooltipContent={dict.chat.uploadFile}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ImageIcon className="h-4 w-4" />
|
||||
</ButtonWithTooltip>
|
||||
|
||||
{onUrlChange && (
|
||||
<ButtonWithTooltip
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowUrlDialog(true)}
|
||||
disabled={isDisabled}
|
||||
tooltipContent={dict.chat.ExtractURL}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Link className="h-4 w-4" />
|
||||
</ButtonWithTooltip>
|
||||
)}
|
||||
|
||||
<ButtonWithTooltip
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowSaveAsTemplate(true)}
|
||||
disabled={isDisabled || !input.trim()}
|
||||
tooltipContent={dict.templates.saveAsTemplate}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<BookmarkPlus className="h-4 w-4" />
|
||||
</ButtonWithTooltip>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
accept="image/png,image/jpeg,image/gif,image/webp,.svg,.pdf,application/pdf,text/*,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"
|
||||
multiple
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
</div>
|
||||
<ModelSelector
|
||||
models={models}
|
||||
selectedModelId={selectedModelId}
|
||||
onSelect={onModelSelect}
|
||||
onConfigure={onConfigureModels}
|
||||
disabled={isDisabled}
|
||||
showUnvalidatedModels={showUnvalidatedModels}
|
||||
/>
|
||||
<div className="w-px h-5 bg-border mx-1" />
|
||||
{(status === "streaming" || status === "submitted") &&
|
||||
onStop ? (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onStop}
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
className="h-8 w-8 p-0 rounded-xl shadow-sm"
|
||||
aria-label={dict.chat.stopGeneration}
|
||||
>
|
||||
<Square className="h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={
|
||||
isDisabled ||
|
||||
isExtractingAttachments ||
|
||||
!input.trim()
|
||||
}
|
||||
size="sm"
|
||||
className="h-8 px-4 rounded-xl font-medium shadow-sm"
|
||||
aria-label={dict.chat.send}
|
||||
>
|
||||
<Send className="h-4 w-4 mr-1.5" />
|
||||
{dict.chat.send}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<HistoryDialog
|
||||
showHistory={showHistory}
|
||||
onToggleHistory={setShowHistory}
|
||||
/>
|
||||
<SaveDialog
|
||||
open={showSaveDialog}
|
||||
onOpenChange={setShowSaveDialog}
|
||||
onSave={(filename, format) =>
|
||||
saveDiagramToFile(
|
||||
filename,
|
||||
format,
|
||||
sessionId,
|
||||
dict.save.savedSuccessfully,
|
||||
)
|
||||
}
|
||||
// Local date as YYYY-MM-DD (toISOString would give UTC)
|
||||
defaultFilename={`diagram-${new Date().toLocaleDateString("sv-SE")}`}
|
||||
/>
|
||||
{onUrlChange && (
|
||||
<UrlInputDialog
|
||||
open={showUrlDialog}
|
||||
onOpenChange={setShowUrlDialog}
|
||||
onSubmit={handleUrlExtract}
|
||||
isExtracting={isExtractingUrl}
|
||||
/>
|
||||
)}
|
||||
<TemplateCreateDialog
|
||||
open={showSaveAsTemplate}
|
||||
onOpenChange={setShowSaveAsTemplate}
|
||||
onSuccess={() => {
|
||||
setShowSaveAsTemplate(false)
|
||||
// Let the template list in the lobby reload
|
||||
window.dispatchEvent(new Event("templatesChanged"))
|
||||
}}
|
||||
initialPrompt={input.trim()}
|
||||
/>
|
||||
</form>
|
||||
)
|
||||
},
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,360 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
MessageSquare,
|
||||
Search,
|
||||
Trash2,
|
||||
X,
|
||||
} from "lucide-react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { TemplatePanel } from "@/components/chat/TemplatePanel"
|
||||
import ExamplePanel from "@/components/chat-example-panel"
|
||||
import Image from "@/components/image-with-basepath"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { STORAGE_KEYS } from "@/lib/storage"
|
||||
import type { Template } from "@/lib/template-storage"
|
||||
|
||||
interface SessionMetadata {
|
||||
id: string
|
||||
title: string
|
||||
updatedAt: number
|
||||
thumbnailDataUrl?: string
|
||||
}
|
||||
|
||||
interface ChatLobbyProps {
|
||||
sessions: SessionMetadata[]
|
||||
onSelectSession: (id: string) => void
|
||||
onDeleteSession?: (id: string) => void
|
||||
setInput: (input: string) => void
|
||||
setFiles: (files: File[]) => void
|
||||
onSendTemplate?: (template: Template) => void
|
||||
currentInput?: string
|
||||
dict: {
|
||||
sessionHistory?: {
|
||||
recentChats?: string
|
||||
searchPlaceholder?: string
|
||||
noResults?: string
|
||||
justNow?: string
|
||||
deleteTitle?: string
|
||||
deleteDescription?: string
|
||||
}
|
||||
templates?: {
|
||||
title?: string
|
||||
myTemplates?: string
|
||||
}
|
||||
examples?: {
|
||||
quickExamples?: string
|
||||
}
|
||||
common: {
|
||||
delete: string
|
||||
cancel: string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to format session date
|
||||
function formatSessionDate(
|
||||
timestamp: number,
|
||||
dict?: { justNow?: string },
|
||||
): string {
|
||||
const date = new Date(timestamp)
|
||||
const now = new Date()
|
||||
const diffMs = now.getTime() - date.getTime()
|
||||
const diffMins = Math.floor(diffMs / (1000 * 60))
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
|
||||
|
||||
if (diffMins < 1) return dict?.justNow || "Just now"
|
||||
if (diffMins < 60) return `${diffMins}m ago`
|
||||
if (diffHours < 24) return `${diffHours}h ago`
|
||||
|
||||
return date.toLocaleDateString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
}
|
||||
|
||||
function getPanelVisibility() {
|
||||
if (typeof window === "undefined")
|
||||
return { recentChats: true, myTemplates: true, quickExamples: true }
|
||||
return {
|
||||
recentChats:
|
||||
localStorage.getItem(STORAGE_KEYS.showRecentChats) !== "false",
|
||||
myTemplates:
|
||||
localStorage.getItem(STORAGE_KEYS.showMyTemplates) !== "false",
|
||||
quickExamples:
|
||||
localStorage.getItem(STORAGE_KEYS.showQuickExamples) !== "false",
|
||||
}
|
||||
}
|
||||
|
||||
export function ChatLobby({
|
||||
sessions,
|
||||
onSelectSession,
|
||||
onDeleteSession,
|
||||
setInput,
|
||||
setFiles,
|
||||
onSendTemplate,
|
||||
currentInput = "",
|
||||
dict,
|
||||
}: ChatLobbyProps) {
|
||||
const [templatesExpanded, setTemplatesExpanded] = useState(true)
|
||||
const [examplesExpanded, setExamplesExpanded] = useState(true)
|
||||
const [panelVisibility, setPanelVisibility] = useState(getPanelVisibility)
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [sessionToDelete, setSessionToDelete] = useState<string | null>(null)
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
|
||||
// Listen for panel visibility changes from settings
|
||||
useEffect(() => {
|
||||
const handler = () => setPanelVisibility(getPanelVisibility())
|
||||
window.addEventListener("panelVisibilityChange", handler)
|
||||
return () =>
|
||||
window.removeEventListener("panelVisibilityChange", handler)
|
||||
}, [])
|
||||
|
||||
const hasHistory = sessions.length > 0
|
||||
|
||||
if (!hasHistory) {
|
||||
if (!panelVisibility.myTemplates && !panelVisibility.quickExamples) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div className="animate-fade-in">
|
||||
{panelVisibility.myTemplates && (
|
||||
<TemplatePanel
|
||||
setInput={setInput}
|
||||
onSendTemplate={onSendTemplate}
|
||||
currentInput={currentInput}
|
||||
/>
|
||||
)}
|
||||
{panelVisibility.quickExamples && (
|
||||
<div className={panelVisibility.myTemplates ? "mt-6" : ""}>
|
||||
<ExamplePanel setInput={setInput} setFiles={setFiles} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Show history + collapsible examples when there are sessions
|
||||
return (
|
||||
<div className="py-6 px-2 animate-fade-in">
|
||||
{/* Recent Chats Section */}
|
||||
{panelVisibility.recentChats && (
|
||||
<div className="mb-6">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wider px-1 mb-3">
|
||||
{dict.sessionHistory?.recentChats || "Recent Chats"}
|
||||
</p>
|
||||
{/* Search Bar */}
|
||||
<div className="relative mb-3">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder={
|
||||
dict.sessionHistory?.searchPlaceholder ||
|
||||
"Search chats..."
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-9 pr-3 py-2 text-sm rounded-lg border border-border/60 bg-background focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary/50 transition-all"
|
||||
/>
|
||||
{searchQuery && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSearchQuery("")}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded hover:bg-muted transition-colors"
|
||||
>
|
||||
<X className="w-3 h-3 text-muted-foreground" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{sessions
|
||||
.filter((session) =>
|
||||
session.title
|
||||
.toLowerCase()
|
||||
.includes(searchQuery.toLowerCase()),
|
||||
)
|
||||
.map((session) => (
|
||||
// biome-ignore lint/a11y/useSemanticElements: Cannot use button - has nested delete button which causes hydration error
|
||||
<div
|
||||
key={session.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className="group w-full flex items-center gap-3 p-3 rounded-xl border border-border/60 bg-card hover:bg-accent/50 hover:border-primary/30 transition-all duration-200 cursor-pointer text-left"
|
||||
onClick={() => onSelectSession(session.id)}
|
||||
onKeyDown={(e) => {
|
||||
// Ignore keys bubbling up from the delete button
|
||||
if (e.target !== e.currentTarget) return
|
||||
if (
|
||||
e.key === "Enter" ||
|
||||
e.key === " "
|
||||
) {
|
||||
e.preventDefault()
|
||||
onSelectSession(session.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{session.thumbnailDataUrl ? (
|
||||
<div className="w-12 h-12 shrink-0 rounded-lg border bg-white overflow-hidden">
|
||||
<Image
|
||||
src={session.thumbnailDataUrl}
|
||||
alt=""
|
||||
width={48}
|
||||
height={48}
|
||||
className="object-contain w-full h-full"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-12 h-12 shrink-0 rounded-lg bg-primary/10 flex items-center justify-center">
|
||||
<MessageSquare className="w-5 h-5 text-primary" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium truncate">
|
||||
{session.title}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{formatSessionDate(
|
||||
session.updatedAt,
|
||||
dict.sessionHistory,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{onDeleteSession && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setSessionToDelete(session.id)
|
||||
setDeleteDialogOpen(true)
|
||||
}}
|
||||
className="p-1.5 rounded-lg opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-all"
|
||||
title={dict.common.delete}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{sessions.filter((s) =>
|
||||
s.title
|
||||
.toLowerCase()
|
||||
.includes(searchQuery.toLowerCase()),
|
||||
).length === 0 &&
|
||||
searchQuery && (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
{dict.sessionHistory?.noResults ||
|
||||
"No chats found"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Collapsible My Templates Section */}
|
||||
{panelVisibility.myTemplates && (
|
||||
<div className="border-t border-border/50 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTemplatesExpanded(!templatesExpanded)}
|
||||
className="w-full flex items-center justify-between px-1 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wider hover:text-foreground transition-colors"
|
||||
>
|
||||
<span>
|
||||
{dict.templates?.myTemplates || "My Templates"}
|
||||
</span>
|
||||
{templatesExpanded ? (
|
||||
<ChevronUp className="w-4 h-4" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
{templatesExpanded && (
|
||||
<div className="mt-2">
|
||||
<TemplatePanel
|
||||
setInput={setInput}
|
||||
onSendTemplate={onSendTemplate}
|
||||
currentInput={currentInput}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Collapsible Quick Examples Section */}
|
||||
{panelVisibility.quickExamples && (
|
||||
<div className="border-t border-border/50 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExamplesExpanded(!examplesExpanded)}
|
||||
className="w-full flex items-center justify-between px-1 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wider hover:text-foreground transition-colors"
|
||||
>
|
||||
<span>
|
||||
{dict.examples?.quickExamples || "Quick Examples"}
|
||||
</span>
|
||||
{examplesExpanded ? (
|
||||
<ChevronUp className="w-4 h-4" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
{examplesExpanded && (
|
||||
<div className="mt-2">
|
||||
<ExamplePanel
|
||||
setInput={setInput}
|
||||
setFiles={setFiles}
|
||||
minimal
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<AlertDialog
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}
|
||||
>
|
||||
<AlertDialogContent className="max-w-sm">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{dict.sessionHistory?.deleteTitle ||
|
||||
"Delete this chat?"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{dict.sessionHistory?.deleteDescription ||
|
||||
"This will permanently delete this chat session and its diagram. This action cannot be undone."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{dict.common.cancel}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
if (sessionToDelete && onDeleteSession) {
|
||||
onDeleteSession(sessionToDelete)
|
||||
}
|
||||
setDeleteDialogOpen(false)
|
||||
setSessionToDelete(null)
|
||||
}}
|
||||
className="border border-red-300 bg-red-50 text-red-700 hover:bg-red-100 hover:border-red-400"
|
||||
>
|
||||
{dict.common.delete}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -41,7 +41,8 @@ import { TemplateEditDialog } from "./TemplateEditDialog"
|
||||
|
||||
interface TemplatePanelProps {
|
||||
setInput: (input: string) => void
|
||||
onSendTemplate?: (template: Template) => void
|
||||
/** Whether it was sent */
|
||||
onSendTemplate?: (template: Template) => Promise<boolean>
|
||||
currentInput?: string
|
||||
}
|
||||
|
||||
@@ -178,16 +179,21 @@ export function TemplatePanel({
|
||||
|
||||
// Actually send the template
|
||||
const sendTemplate = async (template: Template) => {
|
||||
// Increment click count only when actually sending
|
||||
await incrementClickCount(template.id)
|
||||
if (onSendTemplate) {
|
||||
// Increment run count and update lastUsedAt
|
||||
await incrementRunCount(template.id)
|
||||
// Reload to show updated stats
|
||||
loadTemplates()
|
||||
// Call the send callback
|
||||
onSendTemplate(template)
|
||||
// Sent first, while the chat is the one it was clicked in (the
|
||||
// counts wait for storage). A run only when it was sent (not
|
||||
// while a message is still being sent, or attachments read).
|
||||
const sending = onSendTemplate(template)
|
||||
// Increment click count only when actually sending
|
||||
await incrementClickCount(template.id)
|
||||
if (await sending) {
|
||||
// Increment run count and update lastUsedAt
|
||||
await incrementRunCount(template.id)
|
||||
// Reload to show updated stats
|
||||
loadTemplates()
|
||||
}
|
||||
} else {
|
||||
await incrementClickCount(template.id)
|
||||
// Fallback: just fill the input if no send callback provided
|
||||
setInput(template.prompt)
|
||||
}
|
||||
@@ -333,14 +339,6 @@ export function TemplatePanel({
|
||||
if (!loading && templates.length === 0) {
|
||||
return (
|
||||
<div className="py-6 px-2 animate-fade-in">
|
||||
<div className="text-center mb-6">
|
||||
<h2 className="text-lg font-semibold text-foreground mb-2">
|
||||
{dict.templates.title}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground max-w-xs mx-auto">
|
||||
{dict.templates.subtitle}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col items-center justify-center py-8 px-4">
|
||||
<div className="w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mb-4">
|
||||
<FileText className="w-8 h-8 text-primary/60" />
|
||||
|
||||
@@ -1,267 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { Check, ChevronDown, ChevronUp, Copy, Cpu } from "lucide-react"
|
||||
import type { Dispatch, SetStateAction } from "react"
|
||||
import { CodeBlock } from "@/components/code-block"
|
||||
import { isMxCellXmlComplete } from "@/lib/utils"
|
||||
import type { DiagramOperation, ToolPartLike } from "./types"
|
||||
|
||||
interface ToolCallCardProps {
|
||||
part: ToolPartLike
|
||||
expandedTools: Record<string, boolean>
|
||||
setExpandedTools: Dispatch<SetStateAction<Record<string, boolean>>>
|
||||
onCopy: (callId: string, text: string, isToolCall: boolean) => void
|
||||
copiedToolCallId: string | null
|
||||
copyFailedToolCallId: string | null
|
||||
dict: {
|
||||
tools: { complete: string }
|
||||
chat: { copied: string; failedToCopy: string; copyResponse: string }
|
||||
}
|
||||
}
|
||||
|
||||
function OperationsDisplay({ operations }: { operations: DiagramOperation[] }) {
|
||||
// Streamed or invalid input can hold anything: show only what React can
|
||||
// render (an object in place of a string would crash the whole chat)
|
||||
const shown = operations.filter(
|
||||
(op) => typeof (op as { operation?: unknown })?.operation === "string",
|
||||
)
|
||||
const text = (value: unknown) => (typeof value === "string" ? value : "")
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{shown.map((op, index) => (
|
||||
<div
|
||||
key={`${op.operation}-${text(op.cell_id)}-${index}`}
|
||||
className="rounded-lg border border-border/50 overflow-hidden bg-background/50"
|
||||
>
|
||||
<div className="px-3 py-1.5 bg-muted/40 border-b border-border/30 flex items-center gap-2">
|
||||
<span
|
||||
className={`text-[10px] font-medium uppercase tracking-wide ${
|
||||
op.operation === "delete"
|
||||
? "text-red-600"
|
||||
: op.operation === "add"
|
||||
? "text-green-600"
|
||||
: "text-blue-600"
|
||||
}`}
|
||||
>
|
||||
{op.operation}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
cell_id: {text(op.cell_id)}
|
||||
</span>
|
||||
</div>
|
||||
{text(op.new_xml) && (
|
||||
<div className="px-3 py-2">
|
||||
<pre className="text-[11px] font-mono text-foreground/80 bg-muted/30 rounded px-2 py-1.5 overflow-x-auto whitespace-pre-wrap break-all">
|
||||
{text(op.new_xml)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ToolCallCard({
|
||||
part,
|
||||
expandedTools,
|
||||
setExpandedTools,
|
||||
onCopy,
|
||||
copiedToolCallId,
|
||||
copyFailedToolCallId,
|
||||
dict,
|
||||
}: ToolCallCardProps) {
|
||||
const callId = part.toolCallId
|
||||
const { state, input, output, errorText } = part
|
||||
// Default to expanded for all states (user can manually collapse if needed)
|
||||
const isExpanded = expandedTools[callId] ?? true
|
||||
const toolName = part.type?.replace("tool-", "")
|
||||
const isCopied = copiedToolCallId === callId
|
||||
|
||||
const toggleExpanded = () => {
|
||||
setExpandedTools((prev) => ({
|
||||
...prev,
|
||||
[callId]: !isExpanded,
|
||||
}))
|
||||
}
|
||||
|
||||
const getToolDisplayName = (name: string) => {
|
||||
switch (name) {
|
||||
case "display_diagram":
|
||||
return "Generate Diagram"
|
||||
case "edit_diagram":
|
||||
return "Edit Diagram"
|
||||
case "get_shape_library":
|
||||
return "Get Shape Library"
|
||||
default:
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
// Incomplete XML means the output hit the length limit, unless the user
|
||||
// stopped the generation themselves. Without an input the JSON was
|
||||
// broken (the server repairs JSON cut short by the limit).
|
||||
const isTruncated =
|
||||
state === "output-error" &&
|
||||
errorText !== "Stopped by user" &&
|
||||
(toolName === "display_diagram" || toolName === "append_diagram") &&
|
||||
typeof input?.xml === "string" &&
|
||||
!isMxCellXmlComplete(input.xml)
|
||||
|
||||
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) {
|
||||
onCopy(callId, textToCopy, true)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="my-3 rounded-xl border border-border/60 bg-muted/30 overflow-hidden">
|
||||
<div className="flex items-center justify-between px-4 py-3 bg-muted/50">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-6 h-6 rounded-md bg-primary/10 flex items-center justify-center">
|
||||
<Cpu className="w-3.5 h-3.5 text-primary" />
|
||||
</div>
|
||||
<span className="text-sm font-medium text-foreground/80">
|
||||
{getToolDisplayName(toolName)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{state === "input-streaming" && (
|
||||
<div className="h-4 w-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
|
||||
)}
|
||||
{state === "output-available" && (
|
||||
<>
|
||||
<span className="text-xs font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
|
||||
{dict.tools.complete}
|
||||
</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" &&
|
||||
(isTruncated ? (
|
||||
<span className="text-xs font-medium text-yellow-600 bg-yellow-50 px-2 py-0.5 rounded-full">
|
||||
Truncated
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs font-medium text-red-600 bg-red-50 px-2 py-0.5 rounded-full">
|
||||
Error
|
||||
</span>
|
||||
))}
|
||||
{input && Object.keys(input).length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleExpanded}
|
||||
className="p-1 rounded hover:bg-muted transition-colors"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronUp className="w-4 h-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{input && isExpanded && (
|
||||
<div className="px-4 py-3 border-t border-border/40 bg-muted/20">
|
||||
{typeof input === "object" && input.xml ? (
|
||||
state === "input-streaming" ||
|
||||
state === "input-available" ? (
|
||||
<pre
|
||||
className="text-[11px] leading-relaxed overflow-x-auto overflow-y-auto max-h-48 scrollbar-thin break-all whitespace-pre-wrap"
|
||||
style={{
|
||||
fontFamily:
|
||||
"var(--font-mono), ui-monospace, monospace",
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
{input.xml}
|
||||
</pre>
|
||||
) : (
|
||||
<CodeBlock code={input.xml} language="xml" />
|
||||
)
|
||||
) : typeof input === "object" &&
|
||||
input.operations &&
|
||||
Array.isArray(input.operations) ? (
|
||||
<OperationsDisplay operations={input.operations} />
|
||||
) : typeof input === "object" &&
|
||||
Object.keys(input).length > 0 ? (
|
||||
<CodeBlock
|
||||
code={JSON.stringify(input, null, 2)}
|
||||
language="json"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
{/* AI SDK stores tool errors in errorText */}
|
||||
{state === "output-error" && (errorText || output) && (
|
||||
<div
|
||||
className={`px-4 py-3 border-t border-border/40 text-sm whitespace-pre-wrap break-words ${isTruncated ? "text-yellow-600" : "text-red-600"}`}
|
||||
>
|
||||
{isTruncated
|
||||
? "Output truncated due to length limits. Try a simpler request or increase Max Output Tokens in Settings."
|
||||
: (errorText ?? output)}
|
||||
</div>
|
||||
)}
|
||||
{/* Show get_shape_library output on success */}
|
||||
{output &&
|
||||
toolName === "get_shape_library" &&
|
||||
state === "output-available" &&
|
||||
isExpanded && (
|
||||
<div className="px-4 py-3 border-t border-border/40">
|
||||
<div className="text-xs text-muted-foreground mb-2">
|
||||
Library loaded (
|
||||
{typeof output === "string" ? output.length : 0}{" "}
|
||||
chars)
|
||||
</div>
|
||||
<pre className="text-xs bg-muted/50 p-2 rounded-md overflow-auto max-h-32 whitespace-pre-wrap">
|
||||
{typeof output === "string"
|
||||
? output.substring(0, 800) +
|
||||
(output.length > 800 ? "\n..." : "")
|
||||
: String(output)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { MAX_FILES, MAX_FILE_SIZE as MAX_IMAGE_SIZE } from "@/lib/chat-helpers"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { isPdfFile, isTextFile } from "@/lib/pdf-utils"
|
||||
|
||||
// Image formats every supported model provider accepts (SVG is read as text)
|
||||
const SUPPORTED_IMAGE_TYPES = [
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
]
|
||||
|
||||
/** Accept list for the attachment picker */
|
||||
export const ATTACHMENT_ACCEPT =
|
||||
"image/png,image/jpeg,image/gif,image/webp,.svg,.pdf,application/pdf,text/*,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"
|
||||
|
||||
function isValidFileType(file: File): boolean {
|
||||
return (
|
||||
SUPPORTED_IMAGE_TYPES.includes(file.type) ||
|
||||
isPdfFile(file) ||
|
||||
isTextFile(file)
|
||||
)
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
const mb = bytes / 1024 / 1024
|
||||
if (mb < 0.01) return `${(bytes / 1024).toFixed(0)}KB`
|
||||
return `${mb.toFixed(2)}MB`
|
||||
}
|
||||
|
||||
/** Keep the files that can be attached; describe the rest as errors */
|
||||
export function validateFiles(
|
||||
newFiles: File[],
|
||||
existingCount: number,
|
||||
dict: any,
|
||||
): { validFiles: File[]; errors: string[] } {
|
||||
const errors: string[] = []
|
||||
const validFiles: File[] = []
|
||||
const availableSlots = MAX_FILES - existingCount
|
||||
|
||||
if (availableSlots <= 0) {
|
||||
errors.push(formatMessage(dict.errors.maxFiles, { max: MAX_FILES }))
|
||||
return { validFiles, errors }
|
||||
}
|
||||
|
||||
for (const file of newFiles) {
|
||||
if (validFiles.length >= availableSlots) {
|
||||
errors.push(
|
||||
formatMessage(dict.errors.onlyMoreAllowed, {
|
||||
slots: availableSlots,
|
||||
}),
|
||||
)
|
||||
break
|
||||
}
|
||||
if (!isValidFileType(file)) {
|
||||
errors.push(
|
||||
formatMessage(dict.errors.unsupportedType, { name: file.name }),
|
||||
)
|
||||
continue
|
||||
}
|
||||
// PDFs and text files are extracted in the browser, so only images
|
||||
// have a size limit
|
||||
const isExtractedFile = isPdfFile(file) || isTextFile(file)
|
||||
if (!isExtractedFile && file.size > MAX_IMAGE_SIZE) {
|
||||
errors.push(
|
||||
formatMessage(dict.errors.fileExceeds, {
|
||||
name: file.name,
|
||||
size: formatFileSize(file.size),
|
||||
max: MAX_IMAGE_SIZE / 1024 / 1024,
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
validFiles.push(file)
|
||||
}
|
||||
}
|
||||
return { validFiles, errors }
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,190 @@
|
||||
import {
|
||||
ChevronDown,
|
||||
Download,
|
||||
FilePlus,
|
||||
MessageSquareDashed,
|
||||
PanelRightClose,
|
||||
Settings,
|
||||
} from "lucide-react"
|
||||
import { useRef } from "react"
|
||||
import { DevXmlSimulator } from "@/components/dev-xml-simulator"
|
||||
import { BrandMark } from "@/components/workspace/brand-mark"
|
||||
import { IconButton } from "@/components/workspace/icon-button"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { usePanelWidth } from "@/hooks/use-panel-width"
|
||||
import { modKey } from "@/lib/platform"
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
PANEL_MAX_WIDTH,
|
||||
PANEL_MIN_WIDTH,
|
||||
useSettingsStore,
|
||||
} from "@/stores/settings-store"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
import { Composer } from "./composer"
|
||||
import { MessageList } from "./message-list"
|
||||
import { SessionMenu, useSessionTitle } from "./session-menu"
|
||||
import { VersionStrip } from "./version-strip"
|
||||
|
||||
const DEBUG = process.env.NODE_ENV === "development"
|
||||
|
||||
/** Drag handle on the panel's left edge (the panel sits on the right) */
|
||||
function ResizeHandle() {
|
||||
const panelWidth = usePanelWidth()
|
||||
const setPanelWidth = useSettingsStore((s) => s.setPanelWidth)
|
||||
const startRef = useRef<{ x: number; width: number } | null>(null)
|
||||
|
||||
return (
|
||||
// biome-ignore lint/a11y/useSemanticElements: a draggable handle, not a divider line
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-valuenow={panelWidth}
|
||||
aria-valuemin={PANEL_MIN_WIDTH}
|
||||
aria-valuemax={PANEL_MAX_WIDTH}
|
||||
tabIndex={-1}
|
||||
className="absolute top-4 -left-1.5 bottom-4 z-10 w-3 cursor-col-resize after:absolute after:inset-y-0 after:left-1/2 after:w-0.5 after:-translate-x-1/2 after:rounded-full after:bg-foreground/0 after:transition-colors hover:after:bg-foreground/15"
|
||||
onPointerDown={(e) => {
|
||||
e.preventDefault()
|
||||
const panel = e.currentTarget.parentElement
|
||||
startRef.current = {
|
||||
x: e.clientX,
|
||||
width: panel?.getBoundingClientRect().width ?? 384,
|
||||
}
|
||||
e.currentTarget.setPointerCapture(e.pointerId)
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
const start = startRef.current
|
||||
if (!start) return
|
||||
// Dragging left widens the panel
|
||||
setPanelWidth(start.width - (e.clientX - start.x))
|
||||
}}
|
||||
onPointerUp={(e) => {
|
||||
startRef.current = null
|
||||
e.currentTarget.releasePointerCapture(e.pointerId)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyThread() {
|
||||
const dict = useDictionary()
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 px-8 text-center">
|
||||
<MessageSquareDashed className="size-5 text-faint" />
|
||||
<p className="max-w-60 text-[13px] text-muted-foreground">
|
||||
{dict.chat.emptyThread}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The floating chat panel: header, versions, conversation, message box */
|
||||
export function ChatPanel({
|
||||
mobile = false,
|
||||
onOpenFile,
|
||||
}: {
|
||||
mobile?: boolean
|
||||
onOpenFile: () => void
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const engine = useChatEngine()
|
||||
const { loadDiagram, isDrawioReady } = useDiagram()
|
||||
const setSaveDialogOpen = useUiStore((s) => s.setSaveDialogOpen)
|
||||
const title = useSessionTitle()
|
||||
const panelWidth = usePanelWidth()
|
||||
const openSettings = useUiStore((s) => s.openSettings)
|
||||
const setPanelOpen = useUiStore((s) => s.setPanelOpen)
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
"flex flex-col bg-card",
|
||||
mobile
|
||||
? "absolute inset-0"
|
||||
: "absolute top-3 right-3 bottom-3 z-20 rounded-2xl shadow-float animate-panel-in",
|
||||
)}
|
||||
style={mobile ? undefined : { width: panelWidth }}
|
||||
aria-label={dict.nav.aiChat}
|
||||
data-testid="chat-panel"
|
||||
>
|
||||
<header className="flex h-[52px] shrink-0 items-center gap-1 pr-2 pl-3">
|
||||
<BrandMark />
|
||||
<SessionMenu onOpenFile={onOpenFile}>
|
||||
<button
|
||||
type="button"
|
||||
className="ml-1 flex min-w-0 items-center gap-1 rounded-lg px-1.5 py-1 hover:bg-accent"
|
||||
data-testid="session-title"
|
||||
>
|
||||
<span className="truncate text-[15px] font-semibold tracking-[-0.01em]">
|
||||
{title}
|
||||
</span>
|
||||
<ChevronDown className="size-4 shrink-0 text-faint" />
|
||||
</button>
|
||||
</SessionMenu>
|
||||
<div className="ml-auto flex items-center">
|
||||
{isDrawioReady && (
|
||||
<IconButton
|
||||
label={dict.workspace.export}
|
||||
onClick={() => setSaveDialogOpen(true)}
|
||||
data-testid="export-button"
|
||||
>
|
||||
<Download />
|
||||
</IconButton>
|
||||
)}
|
||||
<IconButton
|
||||
label={dict.nav.newChat}
|
||||
onClick={engine.newChat}
|
||||
disabled={engine.isBusy}
|
||||
data-testid="new-chat-button"
|
||||
>
|
||||
<FilePlus />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label={dict.nav.settings}
|
||||
onClick={() => openSettings()}
|
||||
data-testid="settings-button"
|
||||
>
|
||||
<Settings />
|
||||
</IconButton>
|
||||
{!mobile && (
|
||||
<IconButton
|
||||
label={dict.nav.hidePanel}
|
||||
shortcut={`${modKey}B`}
|
||||
onClick={() => setPanelOpen(false)}
|
||||
>
|
||||
<PanelRightClose />
|
||||
</IconButton>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<VersionStrip />
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto scrollbar-thin">
|
||||
{engine.messages.length > 0 ? <MessageList /> : <EmptyThread />}
|
||||
</div>
|
||||
|
||||
{DEBUG && (
|
||||
<DevXmlSimulator
|
||||
setMessages={engine.setMessages as any}
|
||||
onDisplayChart={(xml) => loadDiagram(xml, true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="shrink-0 px-4 pt-1 pb-3">
|
||||
<Composer
|
||||
placeholder={
|
||||
engine.messages.length > 0 &&
|
||||
engine.chatSelection.length === 0
|
||||
? dict.chat.placeholderFollowUp
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!mobile && <ResizeHandle />}
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { ChevronLeft, ChevronRight, RotateCcw } from "lucide-react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { diffDiagrams, isSameDocument } from "@/lib/diagram-diff"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { describeChanges } from "@/lib/version-text"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
import { useVersionsStore } from "@/stores/versions-store"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
import { VersionThumb } from "./tool-activity"
|
||||
|
||||
function Sheet({
|
||||
label,
|
||||
svg,
|
||||
}: {
|
||||
label: string
|
||||
svg: string | null | undefined
|
||||
}) {
|
||||
return (
|
||||
<figure className="flex min-w-0 flex-1 flex-col gap-2">
|
||||
<figcaption className="text-xs font-medium text-muted-foreground">
|
||||
{label}
|
||||
</figcaption>
|
||||
<div className="sheet-light flex aspect-[16/10] items-center justify-center overflow-hidden rounded-xl border border-border bg-white p-2">
|
||||
<VersionThumb svg={svg} className="max-h-full max-w-full" />
|
||||
</div>
|
||||
</figure>
|
||||
)
|
||||
}
|
||||
|
||||
/** A saved version next to the current canvas, with restore */
|
||||
export function CompareDialog() {
|
||||
const dict = useDictionary()
|
||||
const t = dict.versions
|
||||
const engine = useChatEngine()
|
||||
const { getVersionSvg, chartXML } = useDiagram()
|
||||
const versionId = useUiStore((s) => s.compareVersionId)
|
||||
const openCompare = useUiStore((s) => s.openCompare)
|
||||
const closeCompare = useUiStore((s) => s.closeCompare)
|
||||
const versions = useVersionsStore((s) => s.versions)
|
||||
const [currentSvg, setCurrentSvg] = useState<string | null>(null)
|
||||
|
||||
const index = versions.findIndex((v) => v.id === versionId)
|
||||
const version = index >= 0 ? versions[index] : null
|
||||
|
||||
// Whether the canvas is this version, on every page
|
||||
const same = useMemo(
|
||||
() => !version || isSameDocument(version.xml, chartXML),
|
||||
[version, chartXML],
|
||||
)
|
||||
// What the canvas has changed since this version on the page it was
|
||||
// made on (null: nothing there)
|
||||
const changes = useMemo(() => {
|
||||
if (!version || same) return null
|
||||
const { summary } = diffDiagrams(version.xml, chartXML, version.pageId)
|
||||
return Object.values(summary).some((n) => n > 0) ? summary : null
|
||||
}, [version, chartXML, same])
|
||||
|
||||
// The version went away (dropped as the oldest, another chat): the
|
||||
// dialog closes, and nothing waits for its Escape
|
||||
useEffect(() => {
|
||||
if (versionId && !version) closeCompare()
|
||||
}, [versionId, version, closeCompare])
|
||||
|
||||
// Picture of the canvas as it is now, taken again once an answer that
|
||||
// was running is done ("" when none could be made)
|
||||
useEffect(() => {
|
||||
if (!versionId) return
|
||||
let cancelled = false
|
||||
setCurrentSvg(null)
|
||||
getVersionSvg().then((svg) => {
|
||||
if (!cancelled) setCurrentSvg(svg ?? "")
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [versionId, engine.isBusy])
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={!!version}
|
||||
onOpenChange={(open) => !open && closeCompare()}
|
||||
>
|
||||
<DialogContent className="gap-5 sm:max-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t.compareTitle}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{!version
|
||||
? ""
|
||||
: same
|
||||
? t.isOnCanvas
|
||||
: changes
|
||||
? `${formatMessage(t.compareSince, { n: version.number })} ${describeChanges(changes, t)}`
|
||||
: formatMessage(t.differsElsewhere, {
|
||||
n: version.number,
|
||||
})}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{version && (
|
||||
<div className="flex flex-col gap-4 sm:flex-row">
|
||||
<Sheet
|
||||
label={formatMessage(t.versionLabel, {
|
||||
n: version.number,
|
||||
})}
|
||||
svg={version.svg}
|
||||
/>
|
||||
<Sheet label={t.currentCanvas} svg={currentSvg} />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={index <= 0}
|
||||
onClick={() => openCompare(versions[index - 1].id)}
|
||||
className="inline-flex size-8 items-center justify-center rounded-lg border border-border text-muted-foreground hover:text-foreground disabled:opacity-30"
|
||||
aria-label={t.previous}
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={index < 0 || index >= versions.length - 1}
|
||||
onClick={() => openCompare(versions[index + 1].id)}
|
||||
className="inline-flex size-8 items-center justify-center rounded-lg border border-border text-muted-foreground hover:text-foreground disabled:opacity-30"
|
||||
aria-label={t.next}
|
||||
>
|
||||
<ChevronRight className="size-4" />
|
||||
</button>
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
{index + 1} / {versions.length}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!version || same || engine.isBusy}
|
||||
onClick={() => {
|
||||
if (!version) return
|
||||
engine.restoreVersion(version.id)
|
||||
closeCompare()
|
||||
}}
|
||||
className="ml-auto inline-flex h-9 items-center gap-1.5 rounded-lg bg-primary px-3.5 text-[13px] font-medium text-primary-foreground hover:opacity-90 disabled:opacity-40"
|
||||
data-testid="compare-restore"
|
||||
>
|
||||
<RotateCcw className="size-4" />
|
||||
{formatMessage(t.restoreVersion, {
|
||||
n: version?.number ?? 0,
|
||||
})}
|
||||
</button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,550 @@
|
||||
import {
|
||||
ArrowUp,
|
||||
BookMarked,
|
||||
BookmarkPlus,
|
||||
Globe,
|
||||
Paperclip,
|
||||
Plus,
|
||||
Square,
|
||||
SquareDashedMousePointer,
|
||||
X,
|
||||
} from "lucide-react"
|
||||
import type React from "react"
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
import { toast } from "sonner"
|
||||
import { TemplateCreateDialog } from "@/components/chat/TemplateCreateDialog"
|
||||
import { TemplatePanel } from "@/components/chat/TemplatePanel"
|
||||
import { ErrorToast } from "@/components/error-toast"
|
||||
import { FilePreviewList } from "@/components/file-preview-list"
|
||||
import { ModelSelector } from "@/components/model-selector"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover"
|
||||
import { UrlInputDialog } from "@/components/url-input-dialog"
|
||||
import { IconButton } from "@/components/workspace/icon-button"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { modKey } from "@/lib/platform"
|
||||
import { extractUrlContent } from "@/lib/url-utils"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useSettingsStore } from "@/stores/settings-store"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
import { ATTACHMENT_ACCEPT, validateFiles } from "./attachments"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
|
||||
function showErrorToast(message: React.ReactNode) {
|
||||
toast.custom(
|
||||
(t) => (
|
||||
<ErrorToast message={message} onDismiss={() => toast.dismiss(t)} />
|
||||
),
|
||||
{ duration: 5000 },
|
||||
)
|
||||
}
|
||||
|
||||
function showValidationErrors(errors: string[], dict: any) {
|
||||
if (errors.length === 0) return
|
||||
if (errors.length === 1) {
|
||||
showErrorToast(
|
||||
<span className="text-muted-foreground">{errors[0]}</span>,
|
||||
)
|
||||
return
|
||||
}
|
||||
showErrorToast(
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="font-medium">
|
||||
{formatMessage(dict.errors.filesRejected, {
|
||||
count: errors.length,
|
||||
})}
|
||||
</span>
|
||||
<ul className="list-inside list-disc text-xs text-muted-foreground">
|
||||
{errors.slice(0, 3).map((err) => (
|
||||
<li key={err}>{err}</li>
|
||||
))}
|
||||
{errors.length > 3 && (
|
||||
<li>
|
||||
{formatMessage(dict.errors.andMore, {
|
||||
count: errors.length - 3,
|
||||
})}
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>,
|
||||
)
|
||||
}
|
||||
|
||||
function MenuItem({
|
||||
icon,
|
||||
children,
|
||||
onClick,
|
||||
disabled,
|
||||
disabledHint,
|
||||
}: {
|
||||
icon: React.ReactNode
|
||||
children: React.ReactNode
|
||||
onClick: () => void
|
||||
disabled?: boolean
|
||||
/** Why the item can't be used now, shown under it while disabled */
|
||||
disabledHint?: string
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className="group/item flex w-full items-start gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] hover:bg-accent disabled:pointer-events-none [&_svg]:mt-px [&_svg]:size-4 [&_svg]:text-muted-foreground"
|
||||
>
|
||||
<span className="contents group-disabled/item:[&>svg]:opacity-40">
|
||||
{icon}
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block group-disabled/item:opacity-40">
|
||||
{children}
|
||||
</span>
|
||||
{disabled && disabledHint && (
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{disabledHint}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The message box: text, attachments, the selected shapes, the model picker
|
||||
* and send/stop. `variant="hero"` is the large box on the start screen.
|
||||
*/
|
||||
export function Composer({
|
||||
variant = "panel",
|
||||
placeholder,
|
||||
autoFocus = false,
|
||||
}: {
|
||||
variant?: "panel" | "hero"
|
||||
placeholder?: string
|
||||
autoFocus?: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const engine = useChatEngine()
|
||||
const {
|
||||
input,
|
||||
setInput,
|
||||
files,
|
||||
setFiles,
|
||||
pdfData,
|
||||
urlData,
|
||||
setUrlData,
|
||||
isBusy,
|
||||
error,
|
||||
chatSelection,
|
||||
dismissSelection,
|
||||
modelConfig,
|
||||
} = engine
|
||||
const sendShortcut = useSettingsStore((s) => s.sendShortcut)
|
||||
const openSettings = useUiStore((s) => s.openSettings)
|
||||
const focusToken = useUiStore((s) => s.focusComposerToken)
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [addOpen, setAddOpen] = useState(false)
|
||||
const [templatesOpen, setTemplatesOpen] = useState(false)
|
||||
const [showUrlDialog, setShowUrlDialog] = useState(false)
|
||||
const [isExtractingUrl, setIsExtractingUrl] = useState(false)
|
||||
const [saveTemplateOpen, setSaveTemplateOpen] = useState(false)
|
||||
|
||||
const isHero = variant === "hero"
|
||||
// Allow a retry when the last request failed, even mid-stream. While
|
||||
// the chat is being left, what is typed could not be sent.
|
||||
const isDisabled = (isBusy && !error) || engine.isLeaving
|
||||
const canSend =
|
||||
!isDisabled && !engine.isExtractingAttachments && !!input.trim()
|
||||
|
||||
const adjustHeight = useCallback(() => {
|
||||
const textarea = textareaRef.current
|
||||
if (!textarea) return
|
||||
textarea.style.height = "auto"
|
||||
textarea.style.height = `${Math.min(textarea.scrollHeight, 220)}px`
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
adjustHeight()
|
||||
}, [input, adjustHeight])
|
||||
|
||||
// Focus requests from elsewhere (new chat, "ask AI" button, ⌘/)
|
||||
useEffect(() => {
|
||||
if (focusToken === 0 && !autoFocus) return
|
||||
const timer = setTimeout(() => textareaRef.current?.focus(), 60)
|
||||
return () => clearTimeout(timer)
|
||||
}, [focusToken, autoFocus])
|
||||
|
||||
// The chat is left while the user types (browser back): the browser
|
||||
// takes the focus from the input it disables, after this runs. It gets
|
||||
// the focus back once enabled, unless something else took it meanwhile.
|
||||
const refocusRef = useRef(false)
|
||||
const isLeaving = engine.isLeaving
|
||||
useLayoutEffect(() => {
|
||||
if (isDisabled) {
|
||||
if (isLeaving && document.activeElement === textareaRef.current) {
|
||||
refocusRef.current = true
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!refocusRef.current) return
|
||||
refocusRef.current = false
|
||||
if (document.activeElement === document.body) {
|
||||
textareaRef.current?.focus()
|
||||
}
|
||||
}, [isDisabled, isLeaving])
|
||||
|
||||
const addFiles = (newFiles: File[]) => {
|
||||
const { validFiles, errors } = validateFiles(
|
||||
newFiles,
|
||||
files.length,
|
||||
dict,
|
||||
)
|
||||
showValidationErrors(errors, dict)
|
||||
if (validFiles.length > 0) setFiles([...files, ...validFiles])
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
// Enter that confirms an IME candidate must not send the message
|
||||
if (e.nativeEvent.isComposing || e.keyCode === 229) return
|
||||
const shouldSend =
|
||||
sendShortcut === "enter"
|
||||
? e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey
|
||||
: (e.metaKey || e.ctrlKey) && e.key === "Enter"
|
||||
if (shouldSend) {
|
||||
e.preventDefault()
|
||||
if (canSend) engine.submit()
|
||||
}
|
||||
}
|
||||
|
||||
const handlePaste = async (e: React.ClipboardEvent) => {
|
||||
if (isDisabled) return
|
||||
const imageItems = Array.from(e.clipboardData.items).filter((item) =>
|
||||
item.type.startsWith("image/"),
|
||||
)
|
||||
if (imageItems.length === 0) return
|
||||
const imageFiles = imageItems
|
||||
.map((item, index) => {
|
||||
const file = item.getAsFile()
|
||||
if (!file) return null
|
||||
return new File(
|
||||
[file],
|
||||
`pasted-image-${Date.now()}-${index}.${file.type.split("/")[1]}`,
|
||||
{ type: file.type },
|
||||
)
|
||||
})
|
||||
.filter((f): f is File => f !== null)
|
||||
addFiles(imageFiles)
|
||||
}
|
||||
|
||||
const handleUrlExtract = async (url: string) => {
|
||||
setIsExtractingUrl(true)
|
||||
// Functional updates, so a removal or send made while extracting is
|
||||
// not overwritten when the request finishes
|
||||
try {
|
||||
setUrlData((prev) =>
|
||||
new Map(prev).set(url, {
|
||||
url,
|
||||
title: url,
|
||||
content: "",
|
||||
charCount: 0,
|
||||
isExtracting: true,
|
||||
}),
|
||||
)
|
||||
const data = await extractUrlContent(url)
|
||||
setUrlData((prev) =>
|
||||
prev.has(url) ? new Map(prev).set(url, data) : prev,
|
||||
)
|
||||
setShowUrlDialog(false)
|
||||
} catch (err) {
|
||||
setUrlData((prev) => {
|
||||
const next = new Map(prev)
|
||||
next.delete(url)
|
||||
return next
|
||||
})
|
||||
showErrorToast(
|
||||
<span className="text-muted-foreground">
|
||||
{err instanceof Error ? err.message : dict.url.failed}
|
||||
</span>,
|
||||
)
|
||||
} finally {
|
||||
setIsExtractingUrl(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectionLabel =
|
||||
chatSelection.length === 1
|
||||
? formatMessage(dict.selection.one, {
|
||||
label:
|
||||
chatSelection[0].label ||
|
||||
(chatSelection[0].isEdge
|
||||
? dict.selection.connector
|
||||
: dict.selection.shape),
|
||||
})
|
||||
: formatMessage(dict.selection.many, {
|
||||
count: chatSelection.length,
|
||||
})
|
||||
|
||||
const hasChips =
|
||||
chatSelection.length > 0 || files.length > 0 || urlData.size > 0
|
||||
|
||||
return (
|
||||
<form
|
||||
id={isHero ? "hero-chat-form" : "chat-form"}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
if (canSend) engine.submit()
|
||||
}}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
if (!isDisabled) addFiles(Array.from(e.dataTransfer.files))
|
||||
}}
|
||||
className={cn(
|
||||
"group/composer relative w-full rounded-[14px] border border-border bg-card transition-[border-color,box-shadow] duration-150",
|
||||
"focus-within:border-foreground/20 focus-within:shadow-[0_0_0_4px_var(--accent)]",
|
||||
isHero && "rounded-[18px] border-transparent shadow-pop",
|
||||
isDragging &&
|
||||
"border-foreground/30 shadow-[0_0_0_4px_var(--marker-soft)]",
|
||||
)}
|
||||
>
|
||||
{hasChips && (
|
||||
<div className="flex flex-wrap items-center gap-1.5 px-2.5 pt-2.5">
|
||||
{chatSelection.length > 0 && (
|
||||
<span
|
||||
className="inline-flex max-w-full items-center gap-1.5 rounded-lg bg-marker-soft py-1 pr-1 pl-2 text-xs font-medium text-marker-ink"
|
||||
data-testid="selection-chip"
|
||||
>
|
||||
<SquareDashedMousePointer className="size-3.5 shrink-0" />
|
||||
<span className="truncate">{selectionLabel}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={dismissSelection}
|
||||
aria-label={dict.selection.remove}
|
||||
className="rounded p-0.5 hover:bg-black/5 dark:hover:bg-white/10"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
{(files.length > 0 || urlData.size > 0) && (
|
||||
// A short window keeps room for the buttons below
|
||||
<div className="max-h-[min(176px,22vh)] w-full overflow-y-auto scrollbar-thin">
|
||||
<FilePreviewList
|
||||
files={files}
|
||||
onRemoveFile={(file) =>
|
||||
setFiles(files.filter((f) => f !== file))
|
||||
}
|
||||
pdfData={pdfData}
|
||||
urlData={urlData}
|
||||
onRemoveUrl={(url) =>
|
||||
setUrlData((prev) => {
|
||||
const next = new Map(prev)
|
||||
next.delete(url)
|
||||
return next
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
placeholder={
|
||||
placeholder ??
|
||||
(chatSelection.length > 0
|
||||
? dict.selection.placeholder
|
||||
: dict.chat.placeholder)
|
||||
}
|
||||
disabled={isDisabled}
|
||||
aria-label={dict.chat.inputLabel}
|
||||
data-testid="chat-input"
|
||||
rows={isHero ? 3 : 2}
|
||||
className={cn(
|
||||
// A short window keeps room for the buttons below
|
||||
"block max-h-[min(220px,30vh)] w-full resize-none bg-transparent text-foreground outline-none placeholder:text-faint scrollbar-thin disabled:opacity-60",
|
||||
isHero
|
||||
? "min-h-[84px] px-[18px] pt-4 pb-1 text-[15px] leading-relaxed"
|
||||
: "min-h-[52px] px-3.5 pt-3 pb-1 text-sm",
|
||||
)}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-0.5",
|
||||
isHero ? "px-2.5 pt-1 pb-2.5" : "px-1.5 pt-0.5 pb-1.5",
|
||||
)}
|
||||
>
|
||||
<Popover open={addOpen} onOpenChange={setAddOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<IconButton
|
||||
label={dict.chat.attach}
|
||||
tooltipSide="top"
|
||||
disabled={isDisabled}
|
||||
data-testid="composer-add"
|
||||
>
|
||||
<Plus />
|
||||
</IconButton>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
side="top"
|
||||
align="start"
|
||||
className="w-64 p-1"
|
||||
>
|
||||
<MenuItem
|
||||
icon={<Paperclip />}
|
||||
onClick={() => {
|
||||
setAddOpen(false)
|
||||
fileInputRef.current?.click()
|
||||
}}
|
||||
>
|
||||
{dict.chat.uploadFile}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
icon={<Globe />}
|
||||
onClick={() => {
|
||||
setAddOpen(false)
|
||||
setShowUrlDialog(true)
|
||||
}}
|
||||
>
|
||||
{dict.chat.ExtractURL}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
icon={<BookmarkPlus />}
|
||||
disabled={!input.trim()}
|
||||
disabledHint={dict.templates.saveDisabledHint}
|
||||
onClick={() => {
|
||||
setAddOpen(false)
|
||||
setSaveTemplateOpen(true)
|
||||
}}
|
||||
>
|
||||
{dict.templates.saveAsTemplate}
|
||||
</MenuItem>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<IconButton
|
||||
label={dict.templates.myTemplates}
|
||||
tooltipSide="top"
|
||||
disabled={isDisabled}
|
||||
onClick={() => setTemplatesOpen(true)}
|
||||
>
|
||||
<BookMarked />
|
||||
</IconButton>
|
||||
|
||||
<div className="ml-auto flex min-w-0 flex-1 items-center justify-end gap-1">
|
||||
<ModelSelector
|
||||
models={modelConfig.models}
|
||||
selectedModelId={modelConfig.selectedModelId}
|
||||
onSelect={modelConfig.setSelectedModelId}
|
||||
onConfigure={() => openSettings("models")}
|
||||
onAddProvider={() => openSettings("models", "picker")}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
{!isBusy && input.trim() && (
|
||||
<kbd
|
||||
className="hidden shrink-0 font-sans text-[11px] text-faint sm:inline"
|
||||
aria-hidden
|
||||
>
|
||||
{sendShortcut === "enter" ? "↵" : `${modKey}↵`}
|
||||
</kbd>
|
||||
)}
|
||||
{isBusy ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={engine.stop}
|
||||
aria-label={dict.chat.stopGeneration}
|
||||
className="inline-flex size-8 shrink-0 items-center justify-center rounded-[10px] bg-foreground text-background transition-opacity hover:opacity-85"
|
||||
>
|
||||
<Square className="size-3 fill-current" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!canSend}
|
||||
aria-label={dict.chat.send}
|
||||
className="inline-flex size-8 shrink-0 items-center justify-center rounded-[10px] bg-primary text-primary-foreground transition-[opacity,background-color] hover:opacity-90 disabled:bg-muted disabled:text-faint"
|
||||
>
|
||||
<ArrowUp className="size-4 stroke-[2.25]" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept={ATTACHMENT_ACCEPT}
|
||||
data-testid="attachment-input"
|
||||
multiple
|
||||
disabled={isDisabled}
|
||||
onChange={(e) => {
|
||||
addFiles(Array.from(e.target.files || []))
|
||||
e.target.value = ""
|
||||
}}
|
||||
/>
|
||||
|
||||
<UrlInputDialog
|
||||
open={showUrlDialog}
|
||||
onOpenChange={setShowUrlDialog}
|
||||
onSubmit={handleUrlExtract}
|
||||
isExtracting={isExtractingUrl}
|
||||
/>
|
||||
<TemplateCreateDialog
|
||||
open={saveTemplateOpen}
|
||||
onOpenChange={setSaveTemplateOpen}
|
||||
onSuccess={() => setSaveTemplateOpen(false)}
|
||||
initialPrompt={input.trim()}
|
||||
/>
|
||||
<Dialog open={templatesOpen} onOpenChange={setTemplatesOpen}>
|
||||
<DialogContent className="flex max-h-[80vh] flex-col gap-0 p-0 sm:max-w-lg">
|
||||
<DialogHeader className="px-5 pt-5 pb-2">
|
||||
<DialogTitle>{dict.templates.myTemplates}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-3 pb-3 scrollbar-thin">
|
||||
<TemplatePanel
|
||||
setInput={(value) => {
|
||||
setInput(value)
|
||||
setTemplatesOpen(false)
|
||||
}}
|
||||
currentInput={input}
|
||||
onSendTemplate={(template) => {
|
||||
setTemplatesOpen(false)
|
||||
return engine.sendTemplate(template.prompt)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { FileText, FileUp, History, Pencil } from "lucide-react"
|
||||
import type React from "react"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { getAssetUrl } from "@/lib/base-path"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
import { Composer } from "./composer"
|
||||
import { SessionMenu } from "./session-menu"
|
||||
|
||||
interface Example {
|
||||
key: string
|
||||
title: string
|
||||
description: string
|
||||
/** Picture of the result (or of the input, for "replicate" examples) */
|
||||
image?: string
|
||||
prompt: string
|
||||
/** Bundled file sent with the prompt; matches the cached example */
|
||||
file?: { path: string; name: string; type: string }
|
||||
}
|
||||
|
||||
/** Secondary start buttons: outlined, so they read as clickable */
|
||||
const startButtonClass =
|
||||
"inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-card px-3 text-[13px] text-foreground transition-colors hover:bg-accent [&_svg]:text-muted-foreground"
|
||||
|
||||
async function loadExampleFile(file: NonNullable<Example["file"]>) {
|
||||
const response = await fetch(getAssetUrl(file.path))
|
||||
const blob = await response.blob()
|
||||
return new File([blob], file.name, { type: file.type })
|
||||
}
|
||||
|
||||
/** One start-screen example: a small picture over its title */
|
||||
function ExampleTile({
|
||||
onClick,
|
||||
title,
|
||||
description,
|
||||
picture,
|
||||
plain,
|
||||
testId,
|
||||
}: {
|
||||
onClick: () => void
|
||||
title: string
|
||||
/** Shown as the tooltip: the title alone names the example */
|
||||
description: string
|
||||
picture: React.ReactNode
|
||||
/** An icon on a tinted tile instead of a diagram on paper */
|
||||
plain?: boolean
|
||||
testId?: string
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
title={description}
|
||||
className="group/example flex min-w-0 flex-col gap-2 rounded-xl border border-border bg-card p-1.5 pb-2.5 text-left transition-colors hover:border-foreground/25"
|
||||
data-testid={testId}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"flex h-16 w-full items-center justify-center overflow-hidden rounded-lg",
|
||||
plain ? "bg-muted" : "sheet-light bg-white",
|
||||
)}
|
||||
>
|
||||
{picture}
|
||||
</span>
|
||||
<span className="px-1 text-[13px] leading-snug font-medium text-foreground">
|
||||
{title}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Start screen over an empty canvas: one large message box and the cached
|
||||
* examples (they answer instantly without calling a model).
|
||||
*/
|
||||
export function LobbyHero({
|
||||
onDrawYourself,
|
||||
onOpenFile,
|
||||
compact = false,
|
||||
}: {
|
||||
onDrawYourself: () => void
|
||||
onOpenFile: () => void
|
||||
/** Phone layout: no example pictures, tighter spacing */
|
||||
compact?: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const t = dict.lobby
|
||||
const engine = useChatEngine()
|
||||
|
||||
// Prompts and file names must stay as they are: cached responses match them
|
||||
const examples: Example[] = [
|
||||
{
|
||||
key: "paper",
|
||||
title: dict.examples.paperToDiagram,
|
||||
description: dict.examples.paperDescription,
|
||||
image: "/paper_demo.svg",
|
||||
prompt: "Summarize this paper as a diagram",
|
||||
file: {
|
||||
path: "/chain-of-thought.txt",
|
||||
name: "chain-of-thought.txt",
|
||||
type: "text/plain",
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "animated",
|
||||
title: dict.examples.animatedDiagram,
|
||||
description: dict.examples.animatedDescription,
|
||||
image: "/animated_connectors.svg",
|
||||
prompt: "Give me a **animated connector** diagram of transformer's architecture",
|
||||
},
|
||||
{
|
||||
key: "aws",
|
||||
title: dict.examples.awsArchitecture,
|
||||
description: dict.examples.awsDescription,
|
||||
image: "/aws_demo.svg",
|
||||
prompt: "Replicate this in aws style",
|
||||
file: {
|
||||
path: "/architecture.png",
|
||||
name: "architecture.png",
|
||||
type: "image/png",
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "flowchart",
|
||||
title: dict.examples.replicateFlowchart,
|
||||
description: dict.examples.replicateDescription,
|
||||
image: "/example.png",
|
||||
prompt: "Replicate this flowchart.",
|
||||
file: {
|
||||
path: "/example.png",
|
||||
name: "example.png",
|
||||
type: "image/png",
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "cat",
|
||||
title: dict.examples.creativeDrawing,
|
||||
description: dict.examples.creativeDescription,
|
||||
image: "/cat_demo.svg",
|
||||
prompt: "Draw a cat for me",
|
||||
},
|
||||
]
|
||||
|
||||
const pickExample = async (example: Example) => {
|
||||
engine.setInput(example.prompt)
|
||||
if (!example.file) {
|
||||
engine.setFiles([])
|
||||
return
|
||||
}
|
||||
try {
|
||||
engine.setFiles([await loadExampleFile(example.file)])
|
||||
} catch (error) {
|
||||
console.error(dict.errors.failedToLoadExample, error)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"mx-auto w-full",
|
||||
compact ? "max-w-xl px-4 py-8" : "max-w-[720px] px-6 py-10",
|
||||
)}
|
||||
data-testid="lobby-hero"
|
||||
>
|
||||
<h1
|
||||
className={cn(
|
||||
"text-center font-semibold tracking-[-0.025em] text-foreground",
|
||||
compact
|
||||
? "text-[26px] leading-tight"
|
||||
: "text-[34px] leading-[1.15]",
|
||||
)}
|
||||
>
|
||||
{t.title}
|
||||
</h1>
|
||||
<p
|
||||
className={cn(
|
||||
"mx-auto mt-2.5 max-w-[34em] text-center text-muted-foreground",
|
||||
compact ? "mb-5 text-[13px]" : "mb-6 text-[14.5px]",
|
||||
)}
|
||||
>
|
||||
{t.lede}
|
||||
</p>
|
||||
|
||||
<Composer
|
||||
variant="hero"
|
||||
autoFocus={!compact}
|
||||
placeholder={t.placeholder}
|
||||
/>
|
||||
|
||||
{/* Examples: one row of tiles; the ways to bring your own
|
||||
diagram follow as a separate group */}
|
||||
<div
|
||||
className={cn(
|
||||
"mt-5 grid gap-2",
|
||||
compact ? "grid-cols-1" : "grid-cols-5",
|
||||
)}
|
||||
>
|
||||
{examples.map((example) =>
|
||||
compact ? (
|
||||
<button
|
||||
key={example.key}
|
||||
type="button"
|
||||
onClick={() => pickExample(example)}
|
||||
className="flex items-center gap-3 rounded-xl border border-border bg-card px-3 py-2.5 text-left hover:border-foreground/25"
|
||||
>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[13px] font-medium">
|
||||
{example.title}
|
||||
</span>
|
||||
<span className="block truncate text-xs text-muted-foreground">
|
||||
{example.description}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<ExampleTile
|
||||
key={example.key}
|
||||
onClick={() => pickExample(example)}
|
||||
title={example.title}
|
||||
description={example.description}
|
||||
testId={`example-${example.key}`}
|
||||
picture={
|
||||
example.image ? (
|
||||
// biome-ignore lint/performance/noImgElement: static preview
|
||||
<img
|
||||
src={getAssetUrl(example.image)}
|
||||
alt=""
|
||||
className="max-h-14 max-w-[88%] object-contain transition-transform duration-300 group-hover/example:scale-[1.06]"
|
||||
/>
|
||||
) : (
|
||||
<FileText className="size-5 text-muted-foreground" />
|
||||
)
|
||||
}
|
||||
plain={!example.image}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-2.5 text-center text-xs text-faint">
|
||||
{dict.examples.cachedNote}
|
||||
</p>
|
||||
|
||||
{/* Ways to start without an example, as plain buttons */}
|
||||
<div className="mt-6 flex flex-wrap items-center justify-center gap-2">
|
||||
{engine.sessions.length > 0 && (
|
||||
<SessionMenu align="center" onOpenFile={onOpenFile}>
|
||||
<button type="button" className={startButtonClass}>
|
||||
<History className="size-4" />
|
||||
{t.recent}
|
||||
</button>
|
||||
</SessionMenu>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenFile}
|
||||
className={startButtonClass}
|
||||
data-testid="open-file"
|
||||
>
|
||||
<FileUp className="size-4" />
|
||||
{dict.workspace.openFile}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDrawYourself}
|
||||
className={startButtonClass}
|
||||
data-testid="draw-yourself"
|
||||
>
|
||||
<Pencil className="size-4" />
|
||||
{t.drawYourself}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,649 @@
|
||||
import type { UIMessage } from "ai"
|
||||
import {
|
||||
AlertCircle,
|
||||
BookmarkPlus,
|
||||
Check,
|
||||
ChevronDown,
|
||||
Copy,
|
||||
FileCode,
|
||||
FileText,
|
||||
Link,
|
||||
Pencil,
|
||||
RotateCcw,
|
||||
ThumbsDown,
|
||||
ThumbsUp,
|
||||
} from "lucide-react"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import ReactMarkdown from "react-markdown"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
Reasoning,
|
||||
ReasoningContent,
|
||||
ReasoningTrigger,
|
||||
} from "@/components/ai-elements/reasoning"
|
||||
import { Shimmer } from "@/components/ai-elements/shimmer"
|
||||
import { TemplateCreateDialog } from "@/components/chat/TemplateCreateDialog"
|
||||
import type { ToolPartLike } from "@/components/chat/types"
|
||||
import { ValidationCard } from "@/components/chat/ValidationCard"
|
||||
import Image from "@/components/image-with-basepath"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { getApiEndpoint } from "@/lib/base-path"
|
||||
import { useCopy } from "@/lib/clipboard"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
import {
|
||||
getMessageTextContent,
|
||||
getUserOriginalText,
|
||||
splitTextIntoFileSections,
|
||||
type TextSection,
|
||||
} from "./message-text"
|
||||
import { ToolActivity } from "./tool-activity"
|
||||
|
||||
function ActionButton({
|
||||
label,
|
||||
onClick,
|
||||
active,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
onClick: () => void
|
||||
active?: boolean
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
title={label}
|
||||
aria-label={label}
|
||||
className={cn(
|
||||
"inline-flex size-7 items-center justify-center rounded-lg text-faint transition-colors hover:bg-accent hover:text-foreground [&_svg]:size-3.5",
|
||||
active && "text-foreground",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** Copies a message's text, with a short "copied" state */
|
||||
function CopyButton({ text }: { text: string }) {
|
||||
const dict = useDictionary()
|
||||
const { copied, copy } = useCopy(() =>
|
||||
toast.error(dict.chat.failedToCopyDetail),
|
||||
)
|
||||
return (
|
||||
<ActionButton
|
||||
label={copied ? dict.chat.copied : dict.chat.copyResponse}
|
||||
onClick={() => copy(text)}
|
||||
>
|
||||
{copied ? <Check /> : <Copy />}
|
||||
</ActionButton>
|
||||
)
|
||||
}
|
||||
|
||||
function AttachedSection({ section }: { section: TextSection }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const dict = useDictionary()
|
||||
const Icon =
|
||||
section.fileType === "pdf"
|
||||
? FileText
|
||||
: section.fileType === "url"
|
||||
? Link
|
||||
: FileCode
|
||||
const chars =
|
||||
section.charCount && section.charCount >= 1000
|
||||
? `${(section.charCount / 1000).toFixed(1)}k`
|
||||
: section.charCount
|
||||
return (
|
||||
<div className="overflow-hidden rounded-lg border border-border bg-card">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setOpen((v) => !v)
|
||||
}}
|
||||
className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left hover:bg-accent"
|
||||
>
|
||||
<Icon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">
|
||||
{section.filename}
|
||||
</span>
|
||||
<span className="shrink-0 text-[11px] text-faint">
|
||||
{chars} {dict.file.chars}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 text-muted-foreground transition-transform",
|
||||
open && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
{open && (
|
||||
<pre className="max-h-48 overflow-y-auto whitespace-pre-wrap border-t border-border px-2.5 py-2 text-xs text-muted-foreground scrollbar-thin">
|
||||
{section.content}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MessageText({ text }: { text: string }) {
|
||||
const sections = splitTextIntoFileSections(text)
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{sections.map((section, index) =>
|
||||
section.type === "text" ? (
|
||||
<div
|
||||
key={index}
|
||||
className={cn(
|
||||
"prose prose-sm max-w-none break-words text-[14px] leading-relaxed text-foreground [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
|
||||
"prose-p:my-1.5 prose-pre:bg-surface-2 prose-pre:text-foreground prose-code:before:content-none prose-code:after:content-none dark:prose-invert",
|
||||
)}
|
||||
>
|
||||
<ReactMarkdown>{section.content}</ReactMarkdown>
|
||||
</div>
|
||||
) : (
|
||||
<AttachedSection key={index} section={section} />
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function UserMessage({
|
||||
message,
|
||||
index,
|
||||
isLast,
|
||||
}: {
|
||||
message: UIMessage
|
||||
index: number
|
||||
isLast: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const engine = useChatEngine()
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [editText, setEditText] = useState("")
|
||||
const [saveTemplate, setSaveTemplate] = useState(false)
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const text = getMessageTextContent(message)
|
||||
const canEdit = isLast && !engine.isBusy
|
||||
|
||||
useEffect(() => {
|
||||
if (editing) textareaRef.current?.focus()
|
||||
}, [editing])
|
||||
|
||||
const startEdit = () => {
|
||||
if (!canEdit) return
|
||||
setEditText(getUserOriginalText(message))
|
||||
setEditing(true)
|
||||
}
|
||||
const submitEdit = async () => {
|
||||
if (!editText.trim()) return
|
||||
// Kept open, with its text, when it could not go now
|
||||
if (await engine.editMessage(index, editText.trim())) setEditing(false)
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
return (
|
||||
<div className="ml-6 flex flex-col gap-2">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={editText}
|
||||
onChange={(e) => setEditText(e.target.value)}
|
||||
rows={Math.min(editText.split("\n").length + 1, 6)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Escape") setEditing(false)
|
||||
else if (
|
||||
e.key === "Enter" &&
|
||||
(e.metaKey || e.ctrlKey)
|
||||
) {
|
||||
e.preventDefault()
|
||||
submitEdit()
|
||||
}
|
||||
}}
|
||||
className="w-full resize-none rounded-xl border border-foreground/20 bg-card px-3 py-2.5 text-sm outline-none focus:shadow-[0_0_0_4px_var(--accent)]"
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditing(false)}
|
||||
className="h-7 rounded-lg px-3 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{dict.common.cancel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={submitEdit}
|
||||
disabled={!editText.trim()}
|
||||
className="h-7 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground disabled:opacity-40"
|
||||
>
|
||||
{dict.chat.saveAndSubmit}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const images = (message.parts ?? []).filter((p) => p.type === "file") as {
|
||||
url: string
|
||||
}[]
|
||||
|
||||
return (
|
||||
<div className="group/message flex items-start justify-end gap-1">
|
||||
<div className="mt-1 flex shrink-0 items-center transition-opacity [@media(hover:hover)]:opacity-0 group-hover/message:opacity-100 focus-within:opacity-100">
|
||||
{canEdit && (
|
||||
<ActionButton
|
||||
label={dict.chat.editMessage}
|
||||
onClick={startEdit}
|
||||
>
|
||||
<Pencil />
|
||||
</ActionButton>
|
||||
)}
|
||||
<CopyButton text={text} />
|
||||
<ActionButton
|
||||
label={dict.templates.saveAsTemplate}
|
||||
onClick={() => setSaveTemplate(true)}
|
||||
>
|
||||
<BookmarkPlus />
|
||||
</ActionButton>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"min-w-0 max-w-[85%] rounded-2xl rounded-br-md bg-secondary px-3.5 py-2.5",
|
||||
canEdit &&
|
||||
"cursor-pointer transition-colors hover:bg-interactive-active",
|
||||
)}
|
||||
role={canEdit ? "button" : undefined}
|
||||
tabIndex={canEdit ? 0 : undefined}
|
||||
onClick={(e) => {
|
||||
// Not for a link or an attachment's toggle inside, nor
|
||||
// when text was selected to copy it
|
||||
const target = e.target as Element
|
||||
if (target.closest("a, button")) return
|
||||
if (window.getSelection()?.toString()) return
|
||||
startEdit()
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.target !== e.currentTarget) return
|
||||
if (canEdit && (e.key === "Enter" || e.key === " ")) {
|
||||
e.preventDefault()
|
||||
startEdit()
|
||||
}
|
||||
}}
|
||||
title={canEdit ? dict.chat.clickToEdit : undefined}
|
||||
>
|
||||
{images.length > 0 && (
|
||||
<div className="mb-2 flex flex-wrap gap-1.5">
|
||||
{images.map((image, i) => (
|
||||
<Image
|
||||
key={i}
|
||||
src={image.url}
|
||||
width={96}
|
||||
height={72}
|
||||
alt={dict.chat.attachedImage}
|
||||
className="h-[72px] w-24 rounded-lg border border-border bg-white object-cover"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{text && <MessageText text={text} />}
|
||||
</div>
|
||||
{saveTemplate && (
|
||||
<TemplateCreateDialog
|
||||
open
|
||||
onOpenChange={(open) => !open && setSaveTemplate(false)}
|
||||
onSuccess={() => setSaveTemplate(false)}
|
||||
initialPrompt={getUserOriginalText(message)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AssistantMessage({
|
||||
message,
|
||||
index,
|
||||
isLastMessage,
|
||||
isLastAssistant,
|
||||
}: {
|
||||
message: UIMessage
|
||||
index: number
|
||||
isLastMessage: boolean
|
||||
isLastAssistant: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
// The thinking header in the page language
|
||||
const thinkingMessage = (isStreaming: boolean, duration?: number) => {
|
||||
if (isStreaming || duration === 0) {
|
||||
return <Shimmer duration={1}>{dict.reasoning.thinking}</Shimmer>
|
||||
}
|
||||
if (duration === undefined) return <p>{dict.reasoning.thoughtBrief}</p>
|
||||
return (
|
||||
<p>
|
||||
{duration === 1
|
||||
? dict.reasoning.thoughtForOne
|
||||
: dict.reasoning.thoughtFor.replace(
|
||||
"{duration}",
|
||||
String(duration),
|
||||
)}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
const engine = useChatEngine()
|
||||
const [feedback, setFeedback] = useState<"good" | "bad" | null>(null)
|
||||
const isRestored = engine.loadedMessageIdsRef.current.has(message.id)
|
||||
const parts = message.parts ?? []
|
||||
const isCachedExample = parts.some((p: any) =>
|
||||
p.toolCallId?.startsWith("cached-"),
|
||||
)
|
||||
const text = getMessageTextContent(message)
|
||||
|
||||
const submitFeedback = async (value: "good" | "bad") => {
|
||||
if (feedback === value) {
|
||||
setFeedback(null)
|
||||
return
|
||||
}
|
||||
setFeedback(value)
|
||||
try {
|
||||
await fetch(getApiEndpoint("/api/log-feedback"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
messageId: message.id,
|
||||
feedback: value,
|
||||
sessionId: engine.langfuseSessionId,
|
||||
}),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to log feedback:", error)
|
||||
toast.error(dict.errors.failedToRecordFeedback)
|
||||
setFeedback(null)
|
||||
}
|
||||
}
|
||||
|
||||
// Text parts with nothing shown between them render together (a step
|
||||
// boundary of an automatic retry shows nothing); tools render in place
|
||||
const blocks: {
|
||||
kind: "text" | "tool" | "reasoning"
|
||||
index: number
|
||||
texts: string[]
|
||||
}[] = []
|
||||
parts.forEach((part, partIndex) => {
|
||||
if (part.type === "reasoning")
|
||||
blocks.push({ kind: "reasoning", index: partIndex, texts: [] })
|
||||
else if (part.type?.startsWith("tool-"))
|
||||
blocks.push({ kind: "tool", index: partIndex, texts: [] })
|
||||
else if (part.type === "text") {
|
||||
const text = (part as { text: string }).text
|
||||
const last = blocks[blocks.length - 1]
|
||||
if (last?.kind === "text") last.texts.push(text)
|
||||
else blocks.push({ kind: "text", index: partIndex, texts: [text] })
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="group/message space-y-2.5">
|
||||
{blocks.map((block) => {
|
||||
const part = parts[block.index]
|
||||
if (block.kind === "reasoning") {
|
||||
const isStreamingReasoning =
|
||||
engine.status === "streaming" &&
|
||||
isLastMessage &&
|
||||
block.index === parts.length - 1
|
||||
return (
|
||||
<Reasoning
|
||||
key={`r-${block.index}`}
|
||||
className="w-full"
|
||||
isStreaming={isStreamingReasoning}
|
||||
defaultOpen={!isRestored}
|
||||
>
|
||||
<ReasoningTrigger
|
||||
getThinkingMessage={thinkingMessage}
|
||||
/>
|
||||
<ReasoningContent>
|
||||
{(part as { text: string }).text}
|
||||
</ReasoningContent>
|
||||
</Reasoning>
|
||||
)
|
||||
}
|
||||
if (block.kind === "tool") {
|
||||
const toolPart = part as unknown as ToolPartLike
|
||||
const validationState =
|
||||
engine.validationStates[toolPart.toolCallId]
|
||||
return (
|
||||
<div key={`t-${block.index}`} className="space-y-2">
|
||||
<ToolActivity
|
||||
part={toolPart}
|
||||
isLastMessage={isLastMessage}
|
||||
/>
|
||||
{toolPart.type === "tool-display_diagram" &&
|
||||
validationState && (
|
||||
<ValidationCard
|
||||
state={validationState}
|
||||
onImproveWithSuggestions={
|
||||
engine.improveWithSuggestions
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const run = block.texts.join("\n")
|
||||
if (!run.trim()) return null
|
||||
return <MessageText key={`x-${block.index}`} text={run} />
|
||||
})}
|
||||
|
||||
{!(engine.isBusy && isLastMessage) && (
|
||||
<div className="-ml-1.5 flex items-center transition-opacity [@media(hover:hover)]:opacity-0 group-hover/message:opacity-100 focus-within:opacity-100">
|
||||
{text && <CopyButton text={text} />}
|
||||
{isLastAssistant && !isCachedExample && (
|
||||
<ActionButton
|
||||
label={dict.chat.regenerate}
|
||||
onClick={() => engine.regenerate(index)}
|
||||
>
|
||||
<RotateCcw />
|
||||
</ActionButton>
|
||||
)}
|
||||
<ActionButton
|
||||
label={dict.chat.goodResponse}
|
||||
active={feedback === "good"}
|
||||
onClick={() => submitFeedback("good")}
|
||||
>
|
||||
<ThumbsUp
|
||||
className={cn(
|
||||
feedback === "good" && "fill-current",
|
||||
)}
|
||||
/>
|
||||
</ActionButton>
|
||||
<ActionButton
|
||||
label={dict.chat.badResponse}
|
||||
active={feedback === "bad"}
|
||||
onClick={() => submitFeedback("bad")}
|
||||
>
|
||||
<ThumbsDown
|
||||
className={cn(feedback === "bad" && "fill-current")}
|
||||
/>
|
||||
</ActionButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed request: what to do in the text color, the provider's own words
|
||||
* below it, and the action that can fix it first
|
||||
*/
|
||||
function ErrorNotice({
|
||||
text,
|
||||
openModelConfig,
|
||||
onOpenModelConfig,
|
||||
onRetry,
|
||||
}: {
|
||||
text: string
|
||||
openModelConfig: boolean
|
||||
onOpenModelConfig: () => void
|
||||
onRetry?: () => void
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
// Provider errors are "hint\n\nprovider message"
|
||||
const split = text.indexOf("\n\n")
|
||||
const headline = split >= 0 ? text.slice(0, split) : text
|
||||
const detail = split >= 0 ? text.slice(split + 2).trim() : ""
|
||||
const button =
|
||||
"inline-flex h-7 items-center gap-1 rounded-lg px-2.5 text-xs font-medium"
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-xl border border-destructive/25 bg-destructive/5 px-3.5 py-3 text-[13px]"
|
||||
>
|
||||
<div className="flex items-start gap-2.5">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0 text-destructive" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="whitespace-pre-line break-words font-medium text-foreground">
|
||||
{headline}
|
||||
</p>
|
||||
{detail && (
|
||||
<p className="mt-1 whitespace-pre-line break-words text-xs text-muted-foreground">
|
||||
{detail}
|
||||
</p>
|
||||
)}
|
||||
{(openModelConfig || onRetry) && (
|
||||
<div className="mt-2.5 flex flex-wrap gap-2">
|
||||
{openModelConfig && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenModelConfig}
|
||||
className={cn(
|
||||
button,
|
||||
"bg-primary text-primary-foreground hover:opacity-90",
|
||||
)}
|
||||
>
|
||||
{dict.errors.llm.openModelSettings}
|
||||
</button>
|
||||
)}
|
||||
{onRetry && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRetry}
|
||||
className={cn(
|
||||
button,
|
||||
"border border-border bg-card text-foreground hover:bg-accent",
|
||||
)}
|
||||
data-testid="retry-button"
|
||||
>
|
||||
<RotateCcw className="size-3.5" />
|
||||
{dict.chat.retry}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function MessageList() {
|
||||
const dict = useDictionary()
|
||||
const openSettings = useUiStore((s) => s.openSettings)
|
||||
const engine = useChatEngine()
|
||||
const { messages } = engine
|
||||
const endRef = useRef<HTMLDivElement>(null)
|
||||
const prevCountRef = useRef(0)
|
||||
const throttleRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
// Keep the newest message in view; jump instantly on bulk loads
|
||||
useEffect(() => {
|
||||
if (!endRef.current || messages.length === 0) return
|
||||
const prev = prevCountRef.current
|
||||
prevCountRef.current = messages.length
|
||||
if (prev === 0 || messages.length - prev > 1) {
|
||||
endRef.current.scrollIntoView({ behavior: "instant", block: "end" })
|
||||
return
|
||||
}
|
||||
if (!throttleRef.current) {
|
||||
endRef.current.scrollIntoView({ behavior: "smooth", block: "end" })
|
||||
throttleRef.current = setTimeout(() => {
|
||||
throttleRef.current = null
|
||||
endRef.current?.scrollIntoView({
|
||||
behavior: "smooth",
|
||||
block: "end",
|
||||
})
|
||||
}, 150)
|
||||
}
|
||||
}, [messages])
|
||||
|
||||
const lastAssistantIndex = messages
|
||||
.map((m) => m.role)
|
||||
.lastIndexOf("assistant")
|
||||
const lastUserIndex = messages.map((m) => m.role).lastIndexOf("user")
|
||||
|
||||
return (
|
||||
<div className="space-y-4 px-4 pt-4 pb-2">
|
||||
{messages.map((message, index) => {
|
||||
const isRestored = engine.loadedMessageIdsRef.current.has(
|
||||
message.id,
|
||||
)
|
||||
return (
|
||||
<div
|
||||
key={message.id}
|
||||
className={cn(!isRestored && "animate-message-in")}
|
||||
>
|
||||
{message.role === "user" ? (
|
||||
<UserMessage
|
||||
message={message}
|
||||
index={index}
|
||||
isLast={index === lastUserIndex}
|
||||
/>
|
||||
) : message.role === "assistant" ? (
|
||||
<AssistantMessage
|
||||
message={message}
|
||||
index={index}
|
||||
isLastMessage={index === messages.length - 1}
|
||||
isLastAssistant={index === lastAssistantIndex}
|
||||
/>
|
||||
) : (
|
||||
<ErrorNotice
|
||||
text={getMessageTextContent(message)}
|
||||
openModelConfig={
|
||||
!!(
|
||||
message.metadata as
|
||||
| { openModelConfig?: boolean }
|
||||
| undefined
|
||||
)?.openModelConfig
|
||||
}
|
||||
onOpenModelConfig={() => {
|
||||
const { providerId } =
|
||||
(message.metadata as
|
||||
| { providerId?: string }
|
||||
| undefined) ?? {}
|
||||
openSettings(
|
||||
"models",
|
||||
providerId ? { providerId } : "list",
|
||||
)
|
||||
}}
|
||||
onRetry={
|
||||
index === messages.length - 1 &&
|
||||
!engine.isBusy &&
|
||||
lastUserIndex >= 0
|
||||
? engine.retryLastMessage
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{engine.status === "submitted" &&
|
||||
messages[messages.length - 1]?.role === "user" && (
|
||||
<div className="px-1 text-[13px]" aria-live="polite">
|
||||
<Shimmer as="span">{dict.reasoning.thinking}</Shimmer>
|
||||
</div>
|
||||
)}
|
||||
<div ref={endRef} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { UIMessage } from "ai"
|
||||
|
||||
/** A run of plain text, or an attached file / URL whose text was inlined */
|
||||
export interface TextSection {
|
||||
type: "text" | "file" | "url"
|
||||
content: string
|
||||
filename?: string
|
||||
charCount?: number
|
||||
fileType?: "pdf" | "text" | "url"
|
||||
}
|
||||
|
||||
// Matches the [PDF: ...], [File: ...] and [URL: ...] sections appended to the user's text
|
||||
export const APPENDED_FILE_SECTIONS_PATTERN =
|
||||
/\n\n\[(PDF|File|URL):\s*[^\]]+\]\n[\s\S]*$/
|
||||
|
||||
export function splitTextIntoFileSections(text: string): TextSection[] {
|
||||
const sections: TextSection[] = []
|
||||
const filePattern =
|
||||
/\[(PDF|File|URL):\s*([^\]]+)\]\n([\s\S]*?)(?=\n\n\[(PDF|File|URL):|$)/g
|
||||
let lastIndex = 0
|
||||
let match: RegExpExecArray | null
|
||||
|
||||
while ((match = filePattern.exec(text)) !== null) {
|
||||
const beforeText = text.slice(lastIndex, match.index).trim()
|
||||
if (beforeText) sections.push({ type: "text", content: beforeText })
|
||||
|
||||
const sectionType = match[1].toLowerCase()
|
||||
const fileType =
|
||||
sectionType === "pdf"
|
||||
? "pdf"
|
||||
: sectionType === "url"
|
||||
? "url"
|
||||
: "text"
|
||||
const content = match[3].trim()
|
||||
sections.push({
|
||||
type: sectionType === "url" ? "url" : "file",
|
||||
content,
|
||||
filename: match[2].trim(),
|
||||
charCount: content.length,
|
||||
fileType,
|
||||
})
|
||||
lastIndex = match.index + match[0].length
|
||||
}
|
||||
|
||||
const remainingText = text.slice(lastIndex).trim()
|
||||
if (remainingText) sections.push({ type: "text", content: remainingText })
|
||||
if (sections.length === 0) sections.push({ type: "text", content: text })
|
||||
return sections
|
||||
}
|
||||
|
||||
export function getMessageTextContent(message: UIMessage): string {
|
||||
if (!message.parts) return ""
|
||||
return message.parts
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => (part as { text: string }).text)
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/** Only the user's typed text, without appended file content */
|
||||
export function getUserOriginalText(message: UIMessage): string {
|
||||
return getMessageTextContent(message)
|
||||
.replace(APPENDED_FILE_SECTIONS_PATTERN, "")
|
||||
.trim()
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { FileUp, Pencil, Plus, Search, Trash2 } from "lucide-react"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatRelativeTime } from "@/lib/relative-time"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
|
||||
/** Title shown for a session, with the default "New Chat" localized */
|
||||
export function useSessionTitle(): string {
|
||||
const dict = useDictionary()
|
||||
const { currentTitle } = useChatEngine()
|
||||
return !currentTitle || currentTitle === "New Chat"
|
||||
? dict.workspace.untitled
|
||||
: currentTitle
|
||||
}
|
||||
|
||||
/**
|
||||
* Popover listing saved diagrams: rename the current one, switch, delete,
|
||||
* start a new one or open a file.
|
||||
*/
|
||||
export function SessionMenu({
|
||||
children,
|
||||
align = "start",
|
||||
onOpenFile,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
align?: "start" | "center" | "end"
|
||||
onOpenFile: () => void
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const t = dict.sessionHistory
|
||||
const params = useParams<{ lang: string }>()
|
||||
const engine = useChatEngine()
|
||||
const [open, setOpen] = useState(false)
|
||||
const title = useSessionTitle()
|
||||
const [query, setQuery] = useState("")
|
||||
const [renaming, setRenaming] = useState(false)
|
||||
const [draftTitle, setDraftTitle] = useState("")
|
||||
const [toDelete, setToDelete] = useState<string | null>(null)
|
||||
const renameRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setRenaming(false)
|
||||
setQuery("")
|
||||
}
|
||||
}, [open])
|
||||
useEffect(() => {
|
||||
if (renaming) renameRef.current?.select()
|
||||
}, [renaming])
|
||||
|
||||
// The title as the list shows it
|
||||
const shownTitle = (title: string) =>
|
||||
title === "New Chat" ? dict.workspace.untitled : title
|
||||
const sessions = engine.sessions.filter((s) =>
|
||||
shownTitle(s.title).toLowerCase().includes(query.trim().toLowerCase()),
|
||||
)
|
||||
|
||||
const commitRename = async () => {
|
||||
const next = draftTitle.trim()
|
||||
setRenaming(false)
|
||||
if (next && next !== title) await engine.renameSession(next)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>{children}</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align={align}
|
||||
className="flex max-h-[min(560px,80vh)] w-[340px] flex-col overflow-hidden rounded-xl p-0 shadow-pop"
|
||||
>
|
||||
<div className="border-b border-border p-3">
|
||||
{renaming ? (
|
||||
<input
|
||||
ref={renameRef}
|
||||
value={draftTitle}
|
||||
onChange={(e) => setDraftTitle(e.target.value)}
|
||||
onBlur={commitRename}
|
||||
onKeyDown={(e) => {
|
||||
// Enter that picks an IME candidate
|
||||
// (Safari: keyCode 229)
|
||||
if (
|
||||
e.nativeEvent.isComposing ||
|
||||
e.keyCode === 229
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (e.key === "Enter") commitRename()
|
||||
if (e.key === "Escape") setRenaming(false)
|
||||
}}
|
||||
maxLength={100}
|
||||
aria-label={t.rename}
|
||||
className="h-8 w-full rounded-lg border border-foreground/20 bg-card px-2.5 text-[13px] font-medium outline-none"
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setDraftTitle(title)
|
||||
setRenaming(true)
|
||||
}}
|
||||
className="group/rename flex h-8 w-full items-center gap-2 rounded-lg px-2.5 text-left hover:bg-accent"
|
||||
data-testid="rename-session"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">
|
||||
{title}
|
||||
</span>
|
||||
<Pencil className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
</button>
|
||||
)}
|
||||
<div className="mt-2 flex gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={engine.isBusy}
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
engine.newChat()
|
||||
}}
|
||||
className="flex h-8 flex-1 items-center justify-center gap-1.5 rounded-lg bg-primary text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-40"
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
{dict.nav.newChat}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={engine.isBusy}
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
onOpenFile()
|
||||
}}
|
||||
className="flex h-8 flex-1 items-center justify-center gap-1.5 rounded-lg border border-border text-xs text-muted-foreground hover:text-foreground disabled:opacity-40"
|
||||
>
|
||||
<FileUp className="size-3.5" />
|
||||
{dict.workspace.openFile}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{engine.sessions.length > 0 && (
|
||||
<div className="px-3 pt-3">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-faint" />
|
||||
<input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t.searchPlaceholder}
|
||||
className="h-8 w-full rounded-lg bg-muted pr-2.5 pl-8 text-[13px] outline-none placeholder:text-faint"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-1.5 scrollbar-thin">
|
||||
{engine.sessions.length === 0 ? (
|
||||
<p className="px-3 py-6 text-center text-xs text-muted-foreground">
|
||||
{t.empty}
|
||||
</p>
|
||||
) : sessions.length === 0 ? (
|
||||
<p className="px-3 py-6 text-center text-xs text-muted-foreground">
|
||||
{t.noResults}
|
||||
</p>
|
||||
) : (
|
||||
sessions.map((session) => {
|
||||
const isCurrent =
|
||||
session.id === engine.currentSessionId
|
||||
// The answer being written must stay in its
|
||||
// own chat
|
||||
const locked = engine.isBusy && !isCurrent
|
||||
const choose = () => {
|
||||
if (locked) return
|
||||
setOpen(false)
|
||||
if (!isCurrent) {
|
||||
engine.selectSession(session.id)
|
||||
}
|
||||
}
|
||||
return (
|
||||
// biome-ignore lint/a11y/useSemanticElements: contains the delete button
|
||||
<div
|
||||
key={session.id}
|
||||
role="button"
|
||||
tabIndex={locked ? -1 : 0}
|
||||
aria-disabled={locked || undefined}
|
||||
title={locked ? t.busyHint : undefined}
|
||||
onClick={choose}
|
||||
onKeyDown={(e) => {
|
||||
if (e.target !== e.currentTarget)
|
||||
return
|
||||
if (
|
||||
e.key === "Enter" ||
|
||||
e.key === " "
|
||||
) {
|
||||
e.preventDefault()
|
||||
choose()
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
"group/session flex cursor-pointer items-center gap-2.5 rounded-lg p-1.5 hover:bg-accent",
|
||||
isCurrent && "bg-accent",
|
||||
locked &&
|
||||
"cursor-not-allowed opacity-50 hover:bg-transparent",
|
||||
)}
|
||||
>
|
||||
<span className="sheet-light flex h-9 w-12 shrink-0 items-center justify-center overflow-hidden rounded-md border border-border bg-white">
|
||||
{session.thumbnailDataUrl && (
|
||||
// biome-ignore lint/performance/noImgElement: data URL thumbnail
|
||||
<img
|
||||
src={
|
||||
session.thumbnailDataUrl
|
||||
}
|
||||
alt=""
|
||||
className="max-h-8 max-w-11 object-contain"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[13px] text-foreground">
|
||||
{shownTitle(session.title)}
|
||||
</span>
|
||||
<span className="block text-[11px] text-faint">
|
||||
{formatRelativeTime(
|
||||
session.updatedAt,
|
||||
params.lang,
|
||||
t.justNow,
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
isCurrent && engine.isBusy
|
||||
}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setToDelete(session.id)
|
||||
}}
|
||||
aria-label={t.deleteTitle}
|
||||
className="inline-flex size-7 shrink-0 items-center justify-center rounded-md text-faint [@media(hover:hover)]:opacity-0 hover:bg-destructive/10 hover:text-destructive group-hover/session:opacity-100 focus-visible:opacity-100"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<AlertDialog
|
||||
open={!!toDelete}
|
||||
onOpenChange={(o) => !o && setToDelete(null)}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t.deleteTitle}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t.deleteDescription}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{dict.common.cancel}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-white hover:bg-destructive/90"
|
||||
onClick={() => {
|
||||
if (toDelete) engine.deleteSession(toDelete)
|
||||
setToDelete(null)
|
||||
}}
|
||||
>
|
||||
{dict.common.delete}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
import {
|
||||
AlertCircle,
|
||||
Check,
|
||||
ChevronDown,
|
||||
Copy,
|
||||
Library,
|
||||
PenTool,
|
||||
Redo2,
|
||||
RotateCcw,
|
||||
Undo2,
|
||||
} from "lucide-react"
|
||||
import { useState } from "react"
|
||||
import { Shimmer } from "@/components/ai-elements/shimmer"
|
||||
import { CodeBlock } from "@/components/code-block"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { useCopy } from "@/lib/clipboard"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { cn, isMxCellXmlComplete } from "@/lib/utils"
|
||||
import { describeChanges, describeTotals } from "@/lib/version-text"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
import { type DiagramVersion, useVersionsStore } from "@/stores/versions-store"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
import type { DiagramOperation, ToolPartLike } from "./types"
|
||||
|
||||
export function ToolInputDetails({ part }: { part: ToolPartLike }) {
|
||||
const { input, state } = part
|
||||
if (!input || typeof input !== "object") return null
|
||||
if (typeof input.xml === "string" && input.xml) {
|
||||
// Plain text while streaming; highlighting re-runs on every chunk
|
||||
return state === "input-streaming" || state === "input-available" ? (
|
||||
<pre className="max-h-48 overflow-auto whitespace-pre-wrap break-all font-mono text-[11px] leading-relaxed text-muted-foreground scrollbar-thin">
|
||||
{input.xml}
|
||||
</pre>
|
||||
) : (
|
||||
<CodeBlock code={input.xml} language="xml" />
|
||||
)
|
||||
}
|
||||
if (Array.isArray(input.operations)) {
|
||||
// Streamed or invalid input can hold anything: show only what React
|
||||
// can render (an object in place of a string would crash the chat)
|
||||
const shown = (input.operations as DiagramOperation[]).filter(
|
||||
(op) =>
|
||||
typeof (op as { operation?: unknown })?.operation === "string",
|
||||
)
|
||||
const text = (value: unknown) =>
|
||||
typeof value === "string" ? value : ""
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{shown.map((op, index) => (
|
||||
<div
|
||||
key={`${op.operation}-${text(op.cell_id)}-${index}`}
|
||||
className="overflow-hidden rounded-lg border border-border bg-card"
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-border px-2.5 py-1 text-[11px]">
|
||||
<span className="font-medium text-foreground">
|
||||
{op.operation}
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{text(op.cell_id)}
|
||||
</span>
|
||||
</div>
|
||||
{text(op.new_xml) && (
|
||||
<pre className="overflow-x-auto whitespace-pre-wrap break-all px-2.5 py-1.5 font-mono text-[11px] text-muted-foreground">
|
||||
{text(op.new_xml)}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (Object.keys(input).length === 0) return null
|
||||
return <CodeBlock code={JSON.stringify(input, null, 2)} language="json" />
|
||||
}
|
||||
|
||||
function toolText(part: ToolPartLike): string {
|
||||
const { input } = part
|
||||
if (!input || typeof input !== "object") return ""
|
||||
if (typeof input.xml === "string" && input.xml) return input.xml
|
||||
if (Array.isArray(input.operations)) {
|
||||
return JSON.stringify(input.operations, null, 2)
|
||||
}
|
||||
return JSON.stringify(input, null, 2)
|
||||
}
|
||||
|
||||
/** Picture of a version (SVG data URL), or what stands in for it */
|
||||
export function VersionThumb({
|
||||
svg,
|
||||
dimmed,
|
||||
className,
|
||||
}: {
|
||||
/** undefined or null: still being made; "": none could be made */
|
||||
svg: string | null | undefined
|
||||
dimmed?: boolean
|
||||
className?: string
|
||||
}) {
|
||||
const t = useDictionary().versions
|
||||
if (svg) {
|
||||
return (
|
||||
// biome-ignore lint/performance/noImgElement: data URL thumbnail
|
||||
<img
|
||||
src={svg}
|
||||
alt=""
|
||||
className={cn(
|
||||
"object-contain transition-opacity",
|
||||
dimmed && "opacity-40",
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (svg === "") {
|
||||
return <span className="text-xs text-faint">{t.noPreview}</span>
|
||||
}
|
||||
return (
|
||||
<Shimmer as="span" className="text-xs">
|
||||
{t.rendering}
|
||||
</Shimmer>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Card for one diagram version produced by a tool call. The latest shows
|
||||
* its picture; older ones fold into one row (the picture opens Compare).
|
||||
*/
|
||||
function VersionCard({
|
||||
part,
|
||||
version,
|
||||
isLatest,
|
||||
}: {
|
||||
part: ToolPartLike
|
||||
version: DiagramVersion
|
||||
isLatest: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const t = dict.versions
|
||||
const engine = useChatEngine()
|
||||
const undoneVersionId = useVersionsStore((s) => s.undoneVersionId)
|
||||
const onCanvasVersionId = useVersionsStore((s) => s.onCanvasVersionId)
|
||||
const openCompare = useUiStore((s) => s.openCompare)
|
||||
const [showCode, setShowCode] = useState(false)
|
||||
const { copied, copy } = useCopy()
|
||||
|
||||
const isUndone = undoneVersionId === version.id
|
||||
const isOnCanvas = onCanvasVersionId === version.id
|
||||
const isEdit = part.type === "tool-edit_diagram"
|
||||
// Undo/redo belongs to the newest change while it is (or was) on the
|
||||
// canvas; after an older version was restored, this one is restored too
|
||||
const canUndo =
|
||||
isLatest && version.beforeXml !== undefined && (isOnCanvas || isUndone)
|
||||
const title = isUndone ? t.undone : isEdit ? t.edited : t.created
|
||||
const summary = version.fromScratch
|
||||
? describeTotals(version.summary, t)
|
||||
: describeChanges(version.summary, t)
|
||||
const badge = (
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 rounded-md px-1.5 py-0.5 text-[11px] font-semibold tabular-nums",
|
||||
isOnCanvas
|
||||
? "bg-marker-soft text-marker-ink"
|
||||
: "bg-muted text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
v{version.number}
|
||||
</span>
|
||||
)
|
||||
const actionClass =
|
||||
"inline-flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40"
|
||||
const restoreButton = (
|
||||
<button
|
||||
type="button"
|
||||
disabled={engine.isBusy || isOnCanvas}
|
||||
onClick={() => engine.restoreVersion(version.id)}
|
||||
className={actionClass}
|
||||
data-testid="version-restore"
|
||||
>
|
||||
<RotateCcw className="size-3.5" />
|
||||
{formatMessage(t.restoreVersion, { n: version.number })}
|
||||
</button>
|
||||
)
|
||||
|
||||
// What the AI wrote: a text link in the summary line, so the card's
|
||||
// only button is the action (undo or restore)
|
||||
const summaryLine = (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{summary}
|
||||
{/* The link wraps as one unit with its separator */}
|
||||
<span className="whitespace-nowrap">
|
||||
<span aria-hidden> · </span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCode((v) => !v)}
|
||||
className="underline decoration-foreground/30 underline-offset-2 hover:text-foreground hover:decoration-foreground"
|
||||
>
|
||||
{showCode ? t.hideCode : t.showCode}
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
const codePanel = showCode && (
|
||||
<div className="relative border-t border-border bg-surface-1 px-3 py-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(toolText(part))}
|
||||
className="absolute top-2 right-2 z-10 inline-flex size-7 items-center justify-center rounded-lg bg-card text-muted-foreground shadow-float hover:text-foreground"
|
||||
aria-label={dict.chat.copyResponse}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="size-3.5" />
|
||||
) : (
|
||||
<Copy className="size-3.5" />
|
||||
)}
|
||||
</button>
|
||||
<ToolInputDetails part={part} />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!isLatest) {
|
||||
return (
|
||||
<div
|
||||
className="overflow-hidden rounded-xl border border-border bg-card"
|
||||
data-testid="version-card"
|
||||
data-tool-state={part.state}
|
||||
>
|
||||
<div className="flex items-center gap-2.5 p-1.5 pr-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openCompare(version.id)}
|
||||
className="sheet-light flex h-9 w-14 shrink-0 items-center justify-center overflow-hidden rounded-md border border-border bg-white hover:border-foreground/30"
|
||||
aria-label={t.compare}
|
||||
title={t.compare}
|
||||
>
|
||||
<VersionThumb
|
||||
svg={version.svg}
|
||||
className="max-h-8 max-w-[52px]"
|
||||
/>
|
||||
</button>
|
||||
{badge}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[13px] text-foreground">
|
||||
{title}
|
||||
</div>
|
||||
{summaryLine}
|
||||
</div>
|
||||
{restoreButton}
|
||||
</div>
|
||||
{codePanel}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden rounded-xl border border-border bg-card",
|
||||
isOnCanvas && "border-foreground/15",
|
||||
)}
|
||||
data-testid="version-card"
|
||||
data-tool-state={part.state}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openCompare(version.id)}
|
||||
className="group/thumb sheet-light relative flex h-24 w-full items-center justify-center border-b border-border bg-white"
|
||||
aria-label={t.compare}
|
||||
>
|
||||
<VersionThumb
|
||||
svg={version.svg}
|
||||
dimmed={isUndone}
|
||||
className="max-h-20 max-w-[88%]"
|
||||
/>
|
||||
<span className="absolute right-2 bottom-2 rounded-md bg-black/60 px-1.5 py-0.5 text-[11px] text-white opacity-0 transition-opacity group-hover/thumb:opacity-100">
|
||||
{t.compare}
|
||||
</span>
|
||||
</button>
|
||||
{/* Title row with the action; the summary runs under both */}
|
||||
<div className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-2.5 px-3 py-2.5">
|
||||
{badge}
|
||||
<div className="truncate text-[13px] font-medium text-foreground">
|
||||
{title}
|
||||
</div>
|
||||
{canUndo ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={engine.isBusy}
|
||||
onClick={() => engine.undoVersion(version.id)}
|
||||
className={actionClass}
|
||||
data-testid="version-undo"
|
||||
>
|
||||
{isUndone ? (
|
||||
<Redo2 className="size-3.5" />
|
||||
) : (
|
||||
<Undo2 className="size-3.5" />
|
||||
)}
|
||||
{isUndone ? t.redo : t.undo}
|
||||
</button>
|
||||
) : (
|
||||
restoreButton
|
||||
)}
|
||||
<div className="col-span-2 col-start-2 mt-0.5">
|
||||
{summaryLine}
|
||||
</div>
|
||||
</div>
|
||||
{codePanel}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Compact row for tool calls that are running, failed or produced no version */
|
||||
function ToolRow({
|
||||
part,
|
||||
icon,
|
||||
label,
|
||||
tone = "default",
|
||||
detail,
|
||||
}: {
|
||||
part: ToolPartLike
|
||||
icon: React.ReactNode
|
||||
label: React.ReactNode
|
||||
tone?: "default" | "error" | "warning"
|
||||
detail?: string
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const [open, setOpen] = useState(false)
|
||||
const { copied, copy } = useCopy()
|
||||
const hasInput = !!part.input && Object.keys(part.input).length > 0
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden rounded-xl border border-border bg-card",
|
||||
tone === "error" && "border-destructive/25",
|
||||
)}
|
||||
data-testid="tool-row"
|
||||
data-tool-name={part.type?.replace("tool-", "")}
|
||||
data-tool-state={part.state}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
disabled={!hasInput && !detail}
|
||||
className="flex w-full items-center gap-2.5 px-3 py-2.5 text-left"
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex size-7 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground [&_svg]:size-4",
|
||||
tone === "error" &&
|
||||
"bg-destructive/10 text-destructive",
|
||||
tone === "warning" && "bg-marker-soft text-marker-ink",
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] text-foreground">
|
||||
{label}
|
||||
</span>
|
||||
{(hasInput || detail) && (
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"size-4 shrink-0 text-muted-foreground transition-transform",
|
||||
open && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
{open && (
|
||||
<div
|
||||
className={cn(
|
||||
"relative space-y-2 border-t border-border bg-surface-1 px-3 py-2.5",
|
||||
hasInput && "pr-11",
|
||||
)}
|
||||
>
|
||||
{hasInput && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(toolText(part))}
|
||||
className="absolute top-2 right-2 z-10 inline-flex size-7 items-center justify-center rounded-lg bg-card text-muted-foreground shadow-float hover:text-foreground"
|
||||
aria-label={dict.chat.copyResponse}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="size-3.5" />
|
||||
) : (
|
||||
<Copy className="size-3.5" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
{detail && (
|
||||
<p
|
||||
className={cn(
|
||||
"whitespace-pre-wrap break-words text-xs",
|
||||
tone === "error"
|
||||
? "text-destructive"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{detail}
|
||||
</p>
|
||||
)}
|
||||
{hasInput && <ToolInputDetails part={part} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ToolActivity({
|
||||
part,
|
||||
isLastMessage,
|
||||
}: {
|
||||
part: ToolPartLike
|
||||
isLastMessage: boolean
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const t = dict.versions
|
||||
const engine = useChatEngine()
|
||||
const versions = useVersionsStore((s) => s.versions)
|
||||
const toolName = part.type?.replace("tool-", "")
|
||||
const { state, errorText, output } = part
|
||||
|
||||
const versionIndex = versions.findIndex(
|
||||
(v) => v.toolCallId === part.toolCallId,
|
||||
)
|
||||
if (state === "output-available" && versionIndex >= 0) {
|
||||
return (
|
||||
<VersionCard
|
||||
part={part}
|
||||
version={versions[versionIndex]}
|
||||
isLatest={versionIndex === versions.length - 1}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// The answer ended before the call did (stopped, network error)
|
||||
const running = isLastMessage && engine.isBusy
|
||||
|
||||
if (toolName === "get_shape_library" && state !== "output-error") {
|
||||
const isDone = state === "output-available"
|
||||
return (
|
||||
<ToolRow
|
||||
part={part}
|
||||
icon={<Library />}
|
||||
label={
|
||||
isDone ? (
|
||||
t.libraryLoaded
|
||||
) : running ? (
|
||||
<Shimmer as="span">{t.loadingLibrary}</Shimmer>
|
||||
) : (
|
||||
t.stopped
|
||||
)
|
||||
}
|
||||
detail={
|
||||
isDone && typeof output === "string"
|
||||
? `${output.slice(0, 600)}${output.length > 600 ? "…" : ""}`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Stop turns a call still streaming into "Stopped by user" (right
|
||||
// away, or when the answer has ended for one not on screen yet): one
|
||||
// left like this was cut off (a closed connection, an error, a closed
|
||||
// tab)
|
||||
if (state === "input-streaming" || state === "input-available") {
|
||||
const failed = !running && !(isLastMessage && engine.stoppedRef.current)
|
||||
return (
|
||||
<ToolRow
|
||||
part={part}
|
||||
icon={running ? <PenTool /> : <AlertCircle />}
|
||||
tone={failed ? "error" : "default"}
|
||||
label={
|
||||
running ? (
|
||||
<Shimmer as="span">
|
||||
{toolName === "edit_diagram"
|
||||
? t.editing
|
||||
: t.drawing}
|
||||
</Shimmer>
|
||||
) : failed ? (
|
||||
t.failed
|
||||
) : (
|
||||
t.stopped
|
||||
)
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (state === "output-error") {
|
||||
const stopped = errorText === "Stopped by user"
|
||||
// Incomplete XML means the output hit the length limit. Without an
|
||||
// input the JSON was broken (the server repairs JSON cut short by
|
||||
// the limit).
|
||||
const truncated =
|
||||
!stopped &&
|
||||
(toolName === "display_diagram" || toolName === "append_diagram") &&
|
||||
typeof part.input?.xml === "string" &&
|
||||
!isMxCellXmlComplete(part.input.xml)
|
||||
return (
|
||||
<ToolRow
|
||||
part={part}
|
||||
icon={<AlertCircle />}
|
||||
tone={stopped ? "default" : truncated ? "warning" : "error"}
|
||||
label={
|
||||
stopped
|
||||
? t.stopped
|
||||
: truncated
|
||||
? dict.tools.truncated
|
||||
: isLastMessage && engine.isBusy
|
||||
? t.failedRetrying
|
||||
: t.failed
|
||||
}
|
||||
detail={
|
||||
stopped
|
||||
? undefined
|
||||
: truncated
|
||||
? t.truncatedHint
|
||||
: (errorText ??
|
||||
(typeof output === "string" ? output : ""))
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Finished without a version (sessions saved before versions existed)
|
||||
return (
|
||||
<ToolRow
|
||||
part={part}
|
||||
icon={<PenTool />}
|
||||
label={toolName === "edit_diagram" ? t.edited : t.created}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
"use client"
|
||||
|
||||
import type { UIMessage } from "ai"
|
||||
import type { RefObject } from "react"
|
||||
import { useCallback, useEffect, useRef } from "react"
|
||||
import type { DiagramOperation, ToolPartLike } from "@/components/chat/types"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { pageSelectorFor } from "@/lib/diagram-pages"
|
||||
import {
|
||||
convertToLegalXml,
|
||||
extractCompleteMxCells,
|
||||
replaceNodes,
|
||||
} from "@/lib/utils"
|
||||
import {
|
||||
defaultLayerOf,
|
||||
expandCompactCells,
|
||||
} from "@/packages/mcp-server/src/compact-cells.ts"
|
||||
import { applyDiagramOperations } from "@/packages/mcp-server/src/diagram-operations.ts"
|
||||
import { targetPageXml } from "@/packages/mcp-server/src/edit-diagram.ts"
|
||||
import { BLANK_MXFILE } from "@/packages/mcp-server/src/pages.ts"
|
||||
import {
|
||||
addDefaultStyles,
|
||||
applyStyleClasses,
|
||||
edgeIdsOf,
|
||||
readStyleClasses,
|
||||
} from "@/packages/mcp-server/src/style-classes.ts"
|
||||
|
||||
// Helper to extract complete operations from streaming input
|
||||
function getCompleteOperations(
|
||||
operations: DiagramOperation[] | undefined,
|
||||
): DiagramOperation[] {
|
||||
if (!operations || !Array.isArray(operations)) return []
|
||||
return operations.filter(
|
||||
(op) =>
|
||||
op &&
|
||||
typeof op.operation === "string" &&
|
||||
["update", "add", "delete"].includes(op.operation) &&
|
||||
typeof op.cell_id === "string" &&
|
||||
op.cell_id.length > 0 &&
|
||||
(op.operation === "delete" || typeof op.new_xml === "string"),
|
||||
)
|
||||
}
|
||||
|
||||
interface UseDiagramStreamingParams {
|
||||
messages: UIMessage[]
|
||||
processedToolCallsRef: RefObject<Set<string>>
|
||||
editDiagramOriginalXmlRef: RefObject<Map<string, string>>
|
||||
loadedMessageIdsRef: RefObject<Set<string>>
|
||||
// The page the model draws on in this turn; null: the first page
|
||||
turnPageIdRef?: RefObject<string | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws AI tool output onto the canvas while it streams, as a preview that
|
||||
* is not recorded in undo history.
|
||||
*
|
||||
* display_diagram: the complete mxCells written so far. edit_diagram: the
|
||||
* complete operations applied to the diagram from before the call. The tool
|
||||
* handler validates and commits the final result. Runs in the chat engine
|
||||
* so streaming continues while the chat panel is collapsed.
|
||||
*/
|
||||
export function useDiagramStreaming({
|
||||
messages,
|
||||
processedToolCallsRef,
|
||||
editDiagramOriginalXmlRef,
|
||||
loadedMessageIdsRef,
|
||||
turnPageIdRef,
|
||||
}: UseDiagramStreamingParams) {
|
||||
const { chartXML, chartXMLRef, loadDiagram } = useDiagram()
|
||||
const previousXML = useRef<string>("")
|
||||
// Last processed XML per toolCallId, to skip redundant work while streaming
|
||||
const lastProcessedXmlRef = useRef<Map<string, string>>(new Map())
|
||||
|
||||
// Reset when messages become empty (new chat or session switch), so
|
||||
// cached examples work again after starting a new session
|
||||
useEffect(() => {
|
||||
if (messages.length === 0) {
|
||||
previousXML.current = ""
|
||||
lastProcessedXmlRef.current.clear()
|
||||
processedToolCallsRef.current.clear()
|
||||
editDiagramOriginalXmlRef.current.clear()
|
||||
}
|
||||
}, [messages.length, processedToolCallsRef, editDiagramOriginalXmlRef])
|
||||
|
||||
// Streaming preview of display_diagram: draw the complete cells written
|
||||
// so far. The tool handler validates and loads the final diagram.
|
||||
const handleDisplayChart = useCallback(
|
||||
(xml: string) => {
|
||||
// Named styles come before the cells, so the ones written so
|
||||
// far are known by the time their cells stream in
|
||||
const { classes, xml: cellsXml } = readStyleClasses(xml || "")
|
||||
const completeCells = extractCompleteMxCells(cellsXml)
|
||||
if (!completeCells) return
|
||||
const convertedXml = addDefaultStyles(
|
||||
applyStyleClasses(
|
||||
expandCompactCells(convertToLegalXml(completeCells)),
|
||||
classes,
|
||||
),
|
||||
)
|
||||
if (convertedXml === previousXML.current) return
|
||||
|
||||
// Skip this update while the cells written so far don't parse
|
||||
const testDoc = new DOMParser().parseFromString(
|
||||
`<root>${convertedXml}</root>`,
|
||||
"text/xml",
|
||||
)
|
||||
if (testDoc.querySelector("parsererror")) return
|
||||
|
||||
try {
|
||||
// Replace the model's page's cells so other pages stay
|
||||
// intact. An empty canvas gets a default mxfile to put the
|
||||
// cells in.
|
||||
const baseXML = chartXML || BLANK_MXFILE
|
||||
const replacedXML = replaceNodes(
|
||||
baseXML,
|
||||
convertedXml,
|
||||
turnPageIdRef?.current,
|
||||
)
|
||||
previousXML.current = convertedXml
|
||||
loadDiagram(replacedXML, true, "preview")
|
||||
} catch (error) {
|
||||
console.error("Error processing XML:", error)
|
||||
}
|
||||
},
|
||||
[chartXML, loadDiagram],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
// Only the last message can still be streaming
|
||||
const message = messages[messages.length - 1]
|
||||
if (!message?.parts) return
|
||||
|
||||
// Messages restored from a saved session were applied before it was
|
||||
// saved; the saved diagram is authoritative, so don't replay them
|
||||
if (loadedMessageIdsRef.current.has(message.id)) return
|
||||
|
||||
// The diagram without streamed previews, as loaded last: the tool
|
||||
// handler's result of an earlier edit is there before the chartXML
|
||||
// state catches up. Undoing a failed edit's preview below changes it
|
||||
// too, and an edit streaming right after must start from the undone
|
||||
// diagram.
|
||||
let baseXml = chartXMLRef.current
|
||||
|
||||
for (const part of message.parts) {
|
||||
if (
|
||||
part.type !== "tool-display_diagram" &&
|
||||
part.type !== "tool-edit_diagram"
|
||||
) {
|
||||
continue
|
||||
}
|
||||
const { toolCallId, state, input } = part as ToolPartLike
|
||||
|
||||
// Failed or stopped: if the original XML is still stored, the
|
||||
// tool handler never ran (invalid JSON, or the user pressed
|
||||
// stop), so undo the streamed preview here. Invalid JSON leaves
|
||||
// no input, so check this first.
|
||||
if (state === "output-error") {
|
||||
const originalXml =
|
||||
editDiagramOriginalXmlRef.current.get(toolCallId)
|
||||
if (originalXml) {
|
||||
editDiagramOriginalXmlRef.current.delete(toolCallId)
|
||||
loadDiagram(originalXml, true, "revert")
|
||||
baseXml = originalXml
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Input complete, or the tool handler, a stop or an error took
|
||||
// the call already: the tool handler loads the checked diagram.
|
||||
// The messages update at most every 150 ms (useChat throttle in
|
||||
// the chat engine), so they can still show the call streaming
|
||||
// after that.
|
||||
if (
|
||||
state !== "input-streaming" ||
|
||||
processedToolCallsRef.current.has(toolCallId)
|
||||
) {
|
||||
processedToolCallsRef.current.add(toolCallId)
|
||||
lastProcessedXmlRef.current.delete(toolCallId)
|
||||
lastProcessedXmlRef.current.delete(`${toolCallId}-result`)
|
||||
lastProcessedXmlRef.current.delete(`${toolCallId}-ops`)
|
||||
continue
|
||||
}
|
||||
|
||||
if (part.type === "tool-display_diagram") {
|
||||
const xml = input?.xml as string | undefined
|
||||
// Skip if XML hasn't changed since last processing
|
||||
if (!xml || lastProcessedXmlRef.current.get(toolCallId) === xml)
|
||||
continue
|
||||
// Keep the diagram from before the preview, to undo it on a
|
||||
// stop or an error
|
||||
if (!editDiagramOriginalXmlRef.current.has(toolCallId)) {
|
||||
editDiagramOriginalXmlRef.current.set(
|
||||
toolCallId,
|
||||
baseXml || BLANK_MXFILE,
|
||||
)
|
||||
}
|
||||
handleDisplayChart(xml)
|
||||
lastProcessedXmlRef.current.set(toolCallId, xml)
|
||||
continue
|
||||
}
|
||||
|
||||
// edit_diagram: apply operations incrementally for a preview.
|
||||
// editDiagramOriginalXmlRef is shared with the tool handler.
|
||||
if (!input?.operations) continue
|
||||
const completeOps = getCompleteOperations(
|
||||
input.operations as DiagramOperation[],
|
||||
)
|
||||
if (completeOps.length === 0) continue
|
||||
|
||||
// Capture the original XML when streaming starts
|
||||
if (!editDiagramOriginalXmlRef.current.has(toolCallId)) {
|
||||
if (!baseXml) {
|
||||
console.warn(
|
||||
"[edit_diagram streaming] No chart XML available",
|
||||
)
|
||||
continue
|
||||
}
|
||||
editDiagramOriginalXmlRef.current.set(toolCallId, baseXml)
|
||||
}
|
||||
const originalXml =
|
||||
editDiagramOriginalXmlRef.current.get(toolCallId)
|
||||
if (!originalXml) continue
|
||||
|
||||
// The last operation's XML may still be streaming: it applies
|
||||
// once it parses, so compare results, not the number of
|
||||
// operations. Skip if nothing changed since the last preview.
|
||||
const resultKey = `${toolCallId}-result`
|
||||
const opsKey = `${toolCallId}-ops`
|
||||
const ops = JSON.stringify(completeOps)
|
||||
if (lastProcessedXmlRef.current.get(opsKey) === ops) continue
|
||||
lastProcessedXmlRef.current.set(opsKey, ops)
|
||||
try {
|
||||
// The model's page: the edges on it and its first layer,
|
||||
// as editDiagram reads them
|
||||
const selector = pageSelectorFor(
|
||||
originalXml,
|
||||
turnPageIdRef?.current,
|
||||
)
|
||||
const page = targetPageXml(originalXml, selector)
|
||||
const edges = edgeIdsOf(page)
|
||||
const layer = defaultLayerOf(page)
|
||||
const { result } = applyDiagramOperations(
|
||||
originalXml,
|
||||
completeOps.map((op) =>
|
||||
op.new_xml
|
||||
? {
|
||||
...op,
|
||||
new_xml: addDefaultStyles(
|
||||
expandCompactCells(op.new_xml, layer),
|
||||
edges,
|
||||
),
|
||||
}
|
||||
: op,
|
||||
),
|
||||
selector,
|
||||
)
|
||||
if (lastProcessedXmlRef.current.get(resultKey) === result) {
|
||||
continue
|
||||
}
|
||||
// Load the full document so other pages stay intact
|
||||
loadDiagram(result, true, "preview")
|
||||
lastProcessedXmlRef.current.set(resultKey, result)
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
"[edit_diagram streaming] Operation failed:",
|
||||
e instanceof Error ? e.message : e,
|
||||
)
|
||||
}
|
||||
}
|
||||
}, [
|
||||
messages,
|
||||
handleDisplayChart,
|
||||
chartXMLRef,
|
||||
loadDiagram,
|
||||
processedToolCallsRef,
|
||||
editDiagramOriginalXmlRef,
|
||||
loadedMessageIdsRef,
|
||||
])
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import type { RefObject } from "react"
|
||||
import { useEffect, useRef } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { diffDiagrams, isSameDocument } from "@/lib/diagram-diff"
|
||||
import { clearHighlights, highlightCells } from "@/lib/drawio/editor-bridge"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { BLANK_MXFILE } from "@/packages/mcp-server/src/pages.ts"
|
||||
import { useVersionsStore } from "@/stores/versions-store"
|
||||
|
||||
interface UseVersionsParams {
|
||||
/** Index of the user message whose turn is running */
|
||||
currentTurnRef: RefObject<number>
|
||||
isBusy: boolean
|
||||
/** Live busy state, for the restore toast's Undo that runs later */
|
||||
isTurnActive: () => boolean
|
||||
/** Changes when another chat comes on screen */
|
||||
getChatGeneration: () => number
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns every committed AI change into a version (card in the chat), marks
|
||||
* the changed shapes on the canvas, and restores or undoes versions.
|
||||
*/
|
||||
export function useVersions({
|
||||
currentTurnRef,
|
||||
isBusy,
|
||||
isTurnActive,
|
||||
getChatGeneration,
|
||||
}: UseVersionsParams) {
|
||||
const dict = useDictionary()
|
||||
// chartXML changes with hand edits, undo and loads; the ref is the
|
||||
// document on the canvas now
|
||||
const {
|
||||
loadDiagram,
|
||||
getVersionSvg,
|
||||
setCommitHandler,
|
||||
chartXML,
|
||||
chartXMLRef,
|
||||
} = useDiagram()
|
||||
// A restore commits too; that path must not add a version
|
||||
const restoringRef = useRef(false)
|
||||
|
||||
// Registered once: re-registering on every render would leave a gap
|
||||
// (effect cleanups run before the streaming hook commits). The handler
|
||||
// only reads refs and stable functions.
|
||||
useEffect(() => {
|
||||
setCommitHandler(({ beforeXml, afterXml, toolCallId, pageId }) => {
|
||||
if (restoringRef.current) return
|
||||
const { summary, touchedIds, fromScratch } = diffDiagrams(
|
||||
beforeXml,
|
||||
afterXml,
|
||||
pageId,
|
||||
)
|
||||
const id = useVersionsStore.getState().addVersion({
|
||||
xml: afterXml,
|
||||
beforeXml,
|
||||
...(pageId && { pageId }),
|
||||
turnIndex: currentTurnRef.current,
|
||||
toolCallId,
|
||||
summary,
|
||||
fromScratch,
|
||||
})
|
||||
// Mark what changed, unless the whole diagram is new
|
||||
if (!fromScratch) {
|
||||
setTimeout(() => {
|
||||
const marker = getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--marker")
|
||||
.trim()
|
||||
highlightCells(touchedIds, marker || "#ffd84d")
|
||||
}, 60)
|
||||
}
|
||||
// The picture is of the canvas: take it right away, before a
|
||||
// newer version can be on it; once one is, this one gets none
|
||||
// rather than the newer one's
|
||||
const isNewest = () =>
|
||||
useVersionsStore.getState().versions.at(-1)?.id === id
|
||||
setTimeout(async () => {
|
||||
const svg = isNewest() ? await getVersionSvg() : null
|
||||
useVersionsStore
|
||||
.getState()
|
||||
.updateVersion(id, { svg: svg && isNewest() ? svg : "" })
|
||||
}, 0)
|
||||
})
|
||||
return () => setCommitHandler(null)
|
||||
}, [])
|
||||
|
||||
// A version is on the canvas (or its change undone) while the canvas
|
||||
// holds that XML. Hand edits, Ctrl+Z or a new page end it, with an
|
||||
// external draw.io too; Ctrl+Z or redo can also bring the latest version
|
||||
// (or the diagram before it) back. Checked once an answer is done: its
|
||||
// previews change the canvas on the way.
|
||||
useEffect(() => {
|
||||
if (isBusy || isTurnActive() || !chartXML) return
|
||||
const store = useVersionsStore.getState()
|
||||
const id = store.onCanvasVersionId ?? store.undoneVersionId
|
||||
const version = store.versions.find((v) => v.id === id)
|
||||
if (version) {
|
||||
const shown =
|
||||
id === store.onCanvasVersionId
|
||||
? version.xml
|
||||
: version.beforeXml || BLANK_MXFILE
|
||||
if (isSameDocument(shown, chartXML)) return
|
||||
// Its Undo would also take the changes made since away
|
||||
toast.dismiss("version-restored")
|
||||
}
|
||||
const latest = store.versions.at(-1)
|
||||
if (latest && isSameDocument(latest.xml, chartXML)) {
|
||||
store.setOnCanvas(latest.id)
|
||||
} else if (
|
||||
latest?.beforeXml !== undefined &&
|
||||
isSameDocument(latest.beforeXml || BLANK_MXFILE, chartXML)
|
||||
) {
|
||||
store.setUndone(latest.id)
|
||||
} else {
|
||||
store.clearCanvasFlags()
|
||||
}
|
||||
}, [chartXML, isBusy])
|
||||
|
||||
const apply = (xml: string) => {
|
||||
restoringRef.current = true
|
||||
try {
|
||||
loadDiagram(xml, true, "commit")
|
||||
} finally {
|
||||
restoringRef.current = false
|
||||
}
|
||||
clearHighlights()
|
||||
}
|
||||
|
||||
const restoreVersion = (versionId: string) => {
|
||||
if (isTurnActive()) return
|
||||
const store = useVersionsStore.getState()
|
||||
const index = store.versions.findIndex((v) => v.id === versionId)
|
||||
if (index < 0) return
|
||||
// The canvas before the restore, to go back to it: a multi-page
|
||||
// document is loaded in full, which Ctrl+Z cannot undo
|
||||
const before = chartXMLRef.current
|
||||
const wasOnCanvas = store.onCanvasVersionId
|
||||
const wasUndone = store.undoneVersionId
|
||||
const generation = getChatGeneration()
|
||||
apply(store.versions[index].xml)
|
||||
store.setOnCanvas(versionId)
|
||||
toast.success(
|
||||
formatMessage(dict.versions.restoredVersion, {
|
||||
n: store.versions[index].number,
|
||||
}),
|
||||
{
|
||||
id: "version-restored",
|
||||
duration: 8000,
|
||||
action: {
|
||||
label: dict.versions.undoRestore,
|
||||
onClick: () => {
|
||||
// Another chat is on screen, or an answer is
|
||||
// changing the canvas: the old canvas is not theirs
|
||||
if (!before || isTurnActive()) return
|
||||
if (getChatGeneration() !== generation) return
|
||||
apply(before)
|
||||
const now = useVersionsStore.getState()
|
||||
if (wasUndone) now.setUndone(wasUndone)
|
||||
else if (wasOnCanvas) now.setOnCanvas(wasOnCanvas)
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** Undo the change of the latest version, or redo it when undone */
|
||||
const undoVersion = (versionId: string) => {
|
||||
if (isTurnActive()) return
|
||||
const store = useVersionsStore.getState()
|
||||
const version = store.versions.find((v) => v.id === versionId)
|
||||
if (!version) return
|
||||
if (store.undoneVersionId === versionId) {
|
||||
apply(version.xml)
|
||||
store.setOnCanvas(versionId)
|
||||
return
|
||||
}
|
||||
if (version.beforeXml === undefined) return
|
||||
apply(version.beforeXml || BLANK_MXFILE)
|
||||
store.setUndone(versionId)
|
||||
}
|
||||
|
||||
return { restoreVersion, undoVersion }
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useEffect, useRef } from "react"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
import { useVersionsStore } from "@/stores/versions-store"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
|
||||
/** Row of version thumbnails under the panel header; click to compare */
|
||||
export function VersionStrip() {
|
||||
const dict = useDictionary()
|
||||
const versions = useVersionsStore((s) => s.versions)
|
||||
const onCanvasVersionId = useVersionsStore((s) => s.onCanvasVersionId)
|
||||
const openCompare = useUiStore((s) => s.openCompare)
|
||||
const engine = useChatEngine()
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Keep the newest version in view
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current
|
||||
if (el) el.scrollTo({ left: el.scrollWidth, behavior: "smooth" })
|
||||
}, [versions.length])
|
||||
|
||||
// Versions with no card in the chat: saved by older app versions, from
|
||||
// a turn that was retried, or drawn by a call that then failed its
|
||||
// screenshot check (a call still running gets its card when done)
|
||||
const hasCardless = versions.some(
|
||||
(v) =>
|
||||
!v.toolCallId ||
|
||||
!engine.messages.some((m) =>
|
||||
m.parts?.some((p) => {
|
||||
const part = p as { toolCallId?: string; state?: string }
|
||||
return (
|
||||
part.toolCallId === v.toolCallId &&
|
||||
part.state !== "output-error"
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
// One version with a card: the strip adds nothing to it
|
||||
if (versions.length < 2 && !hasCardless) return null
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 border-b border-border px-3.5 pt-1 pb-3">
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{dict.versions.strip}
|
||||
</span>
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="flex min-w-0 flex-1 gap-1.5 overflow-x-auto p-1 scrollbar-thin"
|
||||
>
|
||||
{versions.map((version) => {
|
||||
const isCurrent = version.id === onCanvasVersionId
|
||||
return (
|
||||
<button
|
||||
key={version.id}
|
||||
type="button"
|
||||
onClick={() => openCompare(version.id)}
|
||||
title={`v${version.number}${version.id === onCanvasVersionId ? ` · ${dict.versions.currentCanvas}` : ""}`}
|
||||
className={cn(
|
||||
"sheet-light relative flex h-12 w-[72px] shrink-0 items-center justify-center overflow-hidden rounded-lg border border-border bg-white transition-colors hover:border-foreground/30",
|
||||
// An outline with a gap reads on the white
|
||||
// picture in both themes
|
||||
isCurrent &&
|
||||
"outline-2 outline-offset-2 outline-foreground",
|
||||
)}
|
||||
data-testid="version-thumb"
|
||||
>
|
||||
{version.svg && (
|
||||
// biome-ignore lint/performance/noImgElement: data URL thumbnail
|
||||
<img
|
||||
src={version.svg}
|
||||
alt=""
|
||||
className="max-h-9 max-w-[62px] object-contain"
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"absolute bottom-0.5 left-1 text-[10px] font-medium tabular-nums text-neutral-500",
|
||||
isCurrent &&
|
||||
"font-semibold text-neutral-900",
|
||||
)}
|
||||
>
|
||||
v{version.number}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import Image from "@/components/image-with-basepath"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
|
||||
interface HistoryDialogProps {
|
||||
showHistory: boolean
|
||||
onToggleHistory: (show: boolean) => void
|
||||
}
|
||||
|
||||
export function HistoryDialog({
|
||||
showHistory,
|
||||
onToggleHistory,
|
||||
}: HistoryDialogProps) {
|
||||
const dict = useDictionary()
|
||||
const { loadDiagram: onDisplayChart, diagramHistory } = useDiagram()
|
||||
const [selectedIndex, setSelectedIndex] = useState<number | null>(null)
|
||||
|
||||
const handleClose = () => {
|
||||
setSelectedIndex(null)
|
||||
onToggleHistory(false)
|
||||
}
|
||||
|
||||
const handleConfirmRestore = () => {
|
||||
if (selectedIndex !== null) {
|
||||
// Skip validation for trusted history snapshots
|
||||
onDisplayChart(diagramHistory[selectedIndex].xml, true)
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={showHistory} onOpenChange={onToggleHistory}>
|
||||
<DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto scrollbar-thin">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dict.history.title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{dict.history.description}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{diagramHistory.length === 0 ? (
|
||||
<div className="text-center p-4 text-gray-500">
|
||||
{dict.history.noHistory}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 gap-4 py-4">
|
||||
{diagramHistory.map((item, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`border rounded-md p-2 cursor-pointer hover:border-primary transition-colors ${
|
||||
selectedIndex === index
|
||||
? "border-primary ring-2 ring-primary"
|
||||
: ""
|
||||
}`}
|
||||
onClick={() => setSelectedIndex(index)}
|
||||
>
|
||||
<div className="aspect-video bg-white rounded overflow-hidden flex items-center justify-center">
|
||||
<Image
|
||||
src={item.svg}
|
||||
alt={`${dict.history.version} ${index + 1}`}
|
||||
width={200}
|
||||
height={100}
|
||||
className="object-contain w-full h-full p-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="text-xs text-center mt-1 text-gray-500">
|
||||
{dict.history.version} {index + 1}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
{selectedIndex !== null ? (
|
||||
<>
|
||||
<div className="flex-1 text-sm text-muted-foreground">
|
||||
{formatMessage(dict.history.restoreTo, {
|
||||
version: selectedIndex + 1,
|
||||
})}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setSelectedIndex(null)}
|
||||
>
|
||||
{dict.common.cancel}
|
||||
</Button>
|
||||
<Button onClick={handleConfirmRestore}>
|
||||
{dict.common.confirm}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
{dict.common.close}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
+938
-1077
File diff suppressed because it is too large
Load Diff
+123
-54
@@ -1,11 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
AlertTriangle,
|
||||
Bot,
|
||||
Check,
|
||||
ChevronDown,
|
||||
Monitor,
|
||||
Plus,
|
||||
Server,
|
||||
Settings2,
|
||||
User,
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
ModelSelectorTrigger,
|
||||
} from "@/components/ai-elements/model-selector"
|
||||
import { ButtonWithTooltip } from "@/components/button-with-tooltip"
|
||||
import { ProviderLogo } from "@/components/provider-logo"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import {
|
||||
type FlattenedModel,
|
||||
@@ -38,8 +39,9 @@ interface ModelSelectorProps {
|
||||
selectedModelId: string | undefined
|
||||
onSelect: (modelId: string | undefined) => void
|
||||
onConfigure?: () => void
|
||||
/** Opens the settings on the list of providers to add */
|
||||
onAddProvider?: () => void
|
||||
disabled?: boolean
|
||||
showUnvalidatedModels?: boolean
|
||||
}
|
||||
|
||||
// Group models by providerLabel (handles duplicate providers)
|
||||
@@ -66,32 +68,46 @@ function groupModelsByProvider(
|
||||
return groups
|
||||
}
|
||||
|
||||
/**
|
||||
* The model id without the provider or region prefix that the logo already
|
||||
* shows: "nvidia/nemotron-3-ultra" and "global.anthropic.claude-opus-5-5"
|
||||
* become "nemotron-3-ultra" and "claude-opus-5-5". The full id is in the
|
||||
* tooltip and the list.
|
||||
*/
|
||||
export function shortModelName(id: string): string {
|
||||
const name = id.slice(id.lastIndexOf("/") + 1)
|
||||
const short = name.replace(
|
||||
/^(?:(?:global|us|eu|apac|jp|au|ca|us-gov)\.)?[a-z][a-z0-9-]*\.(?=[a-z])/i,
|
||||
"",
|
||||
)
|
||||
// Ids like "deepseek.r1-v1:0" name the vendor only in the prefix: drop
|
||||
// just the region
|
||||
if (!short || /^[a-z]\d/i.test(short)) {
|
||||
return name.replace(/^(?:global|us|eu|apac|jp|au|ca|us-gov)\./i, "")
|
||||
}
|
||||
return short
|
||||
}
|
||||
|
||||
export function ModelSelector({
|
||||
models,
|
||||
selectedModelId,
|
||||
onSelect,
|
||||
onConfigure,
|
||||
onAddProvider,
|
||||
disabled = false,
|
||||
showUnvalidatedModels = false,
|
||||
}: ModelSelectorProps) {
|
||||
const dict = useDictionary()
|
||||
const [open, setOpen] = useState(false)
|
||||
// Filter models based on showUnvalidatedModels setting
|
||||
const displayModels = useMemo(() => {
|
||||
if (showUnvalidatedModels) {
|
||||
return models
|
||||
}
|
||||
return models.filter((m) => m.validated === true)
|
||||
}, [models, showUnvalidatedModels])
|
||||
|
||||
// Separate server and user models
|
||||
// Separate server and user models. Every user model is listed; one not
|
||||
// tested yet, or that failed its test, says so.
|
||||
const serverModels = useMemo(
|
||||
() => displayModels.filter((m) => m.source === "server"),
|
||||
[displayModels],
|
||||
() => models.filter((m) => m.source === "server"),
|
||||
[models],
|
||||
)
|
||||
const userModels = useMemo(
|
||||
() => displayModels.filter((m) => m.source !== "server"),
|
||||
[displayModels],
|
||||
() => models.filter((m) => m.source !== "server"),
|
||||
[models],
|
||||
)
|
||||
|
||||
// Group each category separately
|
||||
@@ -110,6 +126,17 @@ export function ModelSelector({
|
||||
[models, selectedModelId],
|
||||
)
|
||||
|
||||
// Leaving for the settings: closing, the picker must not give the focus
|
||||
// back to its button, behind the settings dialog
|
||||
const toSettingsRef = useRef(false)
|
||||
const goToSettings = (openSettings: () => void) => {
|
||||
toSettingsRef.current = true
|
||||
setOpen(false)
|
||||
openSettings()
|
||||
}
|
||||
const footerButton =
|
||||
"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm outline-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
|
||||
|
||||
const handleSelect = (value: string) => {
|
||||
if (value === "__server_default__") {
|
||||
onSelect(undefined)
|
||||
@@ -158,8 +185,14 @@ export function ModelSelector({
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className="min-w-0 max-w-48">
|
||||
<ModelSelectorRoot open={open} onOpenChange={setOpen}>
|
||||
<div ref={wrapperRef} className="min-w-0 max-w-44">
|
||||
<ModelSelectorRoot
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (next) toSettingsRef.current = false
|
||||
setOpen(next)
|
||||
}}
|
||||
>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<ButtonWithTooltip
|
||||
tooltipContent={tooltipContent}
|
||||
@@ -167,33 +200,48 @@ export function ModelSelector({
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"h-8 min-w-0 max-w-full shrink overflow-hidden gap-1.5 px-2 transition-[padding,background-color] duration-150 ease-in-out hover:bg-accent",
|
||||
"h-8 min-w-0 max-w-full shrink overflow-hidden gap-1.5 px-2 font-normal text-muted-foreground transition-[padding,background-color] duration-150 ease-in-out hover:bg-accent hover:text-foreground",
|
||||
!showLabel && "px-1.5 justify-center",
|
||||
)}
|
||||
// accessibility: expose label to screen readers
|
||||
aria-label={tooltipContent}
|
||||
data-testid="model-selector"
|
||||
>
|
||||
<Bot className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
|
||||
{selectedModel ? (
|
||||
<ProviderLogo
|
||||
provider={selectedModel.provider}
|
||||
className="size-3.5 flex-shrink-0 opacity-80"
|
||||
/>
|
||||
) : (
|
||||
<Bot className="h-4 w-4 flex-shrink-0" />
|
||||
)}
|
||||
{/* show/hide visible label based on measured width */}
|
||||
{showLabel ? (
|
||||
<span className="min-w-0 truncate text-xs">
|
||||
{selectedModel
|
||||
? selectedModel.modelId
|
||||
: dict.modelConfig.default}
|
||||
? shortModelName(selectedModel.modelId)
|
||||
: dict.modelConfig.serverDefault}
|
||||
</span>
|
||||
) : (
|
||||
// Keep an sr-only label for screen readers when hidden
|
||||
<span className="sr-only">
|
||||
{selectedModel
|
||||
? selectedModel.modelId
|
||||
: dict.modelConfig.default}
|
||||
: dict.modelConfig.serverDefault}
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown className="h-3 w-3 flex-shrink-0 text-muted-foreground" />
|
||||
</ButtonWithTooltip>
|
||||
</ModelSelectorTrigger>
|
||||
|
||||
<ModelSelectorContent title={dict.modelConfig.selectModel}>
|
||||
<ModelSelectorContent
|
||||
title={dict.modelConfig.selectModel}
|
||||
onCloseAutoFocus={(e) => {
|
||||
if (!toSettingsRef.current) return
|
||||
toSettingsRef.current = false
|
||||
e.preventDefault()
|
||||
}}
|
||||
>
|
||||
<ModelSelectorInput
|
||||
placeholder={dict.modelConfig.searchModels}
|
||||
/>
|
||||
@@ -201,10 +249,7 @@ export function ModelSelector({
|
||||
<div className="flex-1 min-h-0 overflow-hidden">
|
||||
<ModelSelectorList className="overflow-y-auto scrollbar-thin">
|
||||
<ModelSelectorEmpty>
|
||||
{displayModels.length === 0 &&
|
||||
models.length > 0
|
||||
? dict.modelConfig.noVerifiedModels
|
||||
: dict.modelConfig.noModelsFound}
|
||||
{dict.modelConfig.noModelsFound}
|
||||
</ModelSelectorEmpty>
|
||||
|
||||
{/* Server Default Option - only show when no server models are configured */}
|
||||
@@ -393,13 +438,22 @@ export function ModelSelector({
|
||||
{model.validated !==
|
||||
true && (
|
||||
<span
|
||||
title={
|
||||
dict
|
||||
.modelConfig
|
||||
.unvalidatedModelWarning
|
||||
}
|
||||
className={cn(
|
||||
"ml-auto shrink-0 pl-2 text-xs",
|
||||
model.validated ===
|
||||
false
|
||||
? "text-destructive"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
<AlertTriangle className="ml-auto h-3 w-3 text-warning" />
|
||||
{model.validated ===
|
||||
false
|
||||
? dict
|
||||
.modelConfig
|
||||
.modelFailed
|
||||
: dict
|
||||
.modelConfig
|
||||
.modelUntested}
|
||||
</span>
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
@@ -412,31 +466,46 @@ export function ModelSelector({
|
||||
)}
|
||||
</ModelSelectorList>
|
||||
</div>
|
||||
{/* Pinned footer: Configure Models... + info text (z-10 above list shadow) */}
|
||||
<div className="relative z-10 shrink-0 border-t bg-background">
|
||||
{onConfigure && (
|
||||
<div className="px-3 py-2">
|
||||
<ModelSelectorItem
|
||||
value="__configure_models__"
|
||||
onSelect={() => {
|
||||
onConfigure()
|
||||
setOpen(false)
|
||||
}}
|
||||
className="flex cursor-pointer items-center gap-2 rounded-sm"
|
||||
{/* Pinned footer: add a provider, configure models
|
||||
(z-10 above list shadow). Buttons, outside the
|
||||
search: reachable with Tab, never filtered out */}
|
||||
{(onAddProvider || onConfigure) && (
|
||||
<div
|
||||
className="relative z-10 shrink-0 space-y-0.5 border-t bg-background px-3 py-2"
|
||||
// The search's Enter would pick the highlighted
|
||||
// model instead of pressing the button
|
||||
onKeyDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
{onAddProvider && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
goToSettings(onAddProvider)
|
||||
}
|
||||
className={footerButton}
|
||||
>
|
||||
<Plus className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate">
|
||||
{dict.modelConfig.addProviderEntry}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
{onConfigure && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
goToSettings(onConfigure)
|
||||
}
|
||||
className={footerButton}
|
||||
>
|
||||
<Settings2 className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<ModelSelectorName>
|
||||
<span className="truncate">
|
||||
{dict.modelConfig.configureModels}
|
||||
</ModelSelectorName>
|
||||
</ModelSelectorItem>
|
||||
</div>
|
||||
)}
|
||||
<div className="px-3 pb-2 text-xs text-muted-foreground">
|
||||
{showUnvalidatedModels
|
||||
? dict.modelConfig.allModelsShown
|
||||
: dict.modelConfig.onlyVerifiedShown}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelectorRoot>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { Key, Link2, Tag } from "lucide-react"
|
||||
import type { ReactNode } from "react"
|
||||
import { ChevronRight, Key, Link2, Tag } from "lucide-react"
|
||||
import { type ReactNode, useState } from "react"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
@@ -13,12 +13,14 @@ import {
|
||||
} from "@/components/ui/select"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { OPTIONS_OPEN } from "@/lib/provider-setup"
|
||||
import {
|
||||
chatRequestUrl,
|
||||
normalizeBaseUrl,
|
||||
PROVIDER_INFO,
|
||||
type ProviderName,
|
||||
} from "@/lib/types/model-config"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
// Logical secret field. The caller owns the actual input — plaintext for the
|
||||
// user dialog, write-only masked for the admin panel — supplied via
|
||||
@@ -30,6 +32,9 @@ export type SecretField =
|
||||
| "awsSecretAccessKey"
|
||||
| "vertexApiKey"
|
||||
|
||||
/** Bedrock signs in with an API key or with an access key pair */
|
||||
export type BedrockAuth = "apiKey" | "accessKey"
|
||||
|
||||
// AWS regions offered for Bedrock (shared by both screens)
|
||||
export const AWS_REGIONS: Array<[string, string]> = [
|
||||
["us-east-1", "N. Virginia"],
|
||||
@@ -53,6 +58,9 @@ interface ProviderCredentialsFieldsProps {
|
||||
name?: string
|
||||
baseUrl?: string
|
||||
awsRegion?: string
|
||||
// Bedrock: also offer an API key (the user dialog; the admin panel
|
||||
// stores access keys only)
|
||||
bedrockApiKey?: boolean
|
||||
disabled?: boolean
|
||||
// Update a plain text field
|
||||
onChange: (field: "name" | "baseUrl" | "awsRegion", value: string) => void
|
||||
@@ -63,6 +71,17 @@ interface ProviderCredentialsFieldsProps {
|
||||
// Extra content after the fields — used for the Bedrock test row and the
|
||||
// EdgeOne test button, which aren't beside a credential input.
|
||||
footer?: ReactNode
|
||||
// The user's settings page: the secrets come first, the display name and
|
||||
// base URL fold under "More options", and Bedrock shows only the way of
|
||||
// signing in that is chosen. Switching it empties the other way's
|
||||
// secrets (clearSecrets), so a request carries one kind of credential.
|
||||
settingsLayout?: boolean
|
||||
clearSecrets?: (fields: SecretField[]) => void
|
||||
// Bedrock credentials filled in, to choose the way of signing in shown
|
||||
bedrockFilled?: { apiKey: boolean; accessKey: boolean }
|
||||
// Bedrock's optional session token input, for temporary access keys
|
||||
// (the admin panel has none)
|
||||
sessionTokenInput?: ReactNode
|
||||
}
|
||||
|
||||
// Display name + per-provider credential inputs, shared by the user
|
||||
@@ -72,10 +91,15 @@ export function ProviderCredentialsFields({
|
||||
name,
|
||||
baseUrl,
|
||||
awsRegion,
|
||||
bedrockApiKey,
|
||||
disabled,
|
||||
onChange,
|
||||
renderSecret,
|
||||
footer,
|
||||
settingsLayout,
|
||||
clearSecrets,
|
||||
bedrockFilled,
|
||||
sessionTokenInput,
|
||||
}: ProviderCredentialsFieldsProps) {
|
||||
const dict = useDictionary()
|
||||
const info = PROVIDER_INFO[provider]
|
||||
@@ -83,35 +107,377 @@ export function ProviderCredentialsFields({
|
||||
example: info.defaultBaseUrl || "https://api.example.com/v1",
|
||||
})
|
||||
const requestUrl = baseUrl ? chatRequestUrl(provider, baseUrl) : null
|
||||
// Open when it holds something the user set, or for a provider whose
|
||||
// base URL usually needs changing or comes with a hint
|
||||
const [optionsOpen, setOptionsOpen] = useState(
|
||||
() =>
|
||||
!!name ||
|
||||
(!!baseUrl && baseUrl !== info.defaultBaseUrl) ||
|
||||
OPTIONS_OPEN.includes(provider),
|
||||
)
|
||||
// Bedrock: the way that is filled in (an API key is used first when both
|
||||
// are, as the server does), else the one shown last, so emptying the
|
||||
// fields to type new keys keeps them on screen
|
||||
const filledAuth: BedrockAuth | null = bedrockFilled?.apiKey
|
||||
? "apiKey"
|
||||
: bedrockFilled?.accessKey
|
||||
? "accessKey"
|
||||
: null
|
||||
const [chosenAuth, setChosenAuth] = useState<BedrockAuth>(
|
||||
filledAuth ?? "apiKey",
|
||||
)
|
||||
if (filledAuth && filledAuth !== chosenAuth) setChosenAuth(filledAuth)
|
||||
const bedrockAuth: BedrockAuth = filledAuth ?? chosenAuth
|
||||
|
||||
const nameField = (
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="provider-name"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Tag className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.displayName}
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-name"
|
||||
value={name ?? ""}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange("name", e.target.value)}
|
||||
placeholder={info.label}
|
||||
className="h-9"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
const regionField = (
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="aws-region"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.awsRegion}
|
||||
</Label>
|
||||
<Select
|
||||
value={awsRegion || ""}
|
||||
disabled={disabled}
|
||||
onValueChange={(v) => onChange("awsRegion", v)}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="aws-region"
|
||||
className="h-9 font-mono text-xs hover:bg-accent"
|
||||
>
|
||||
<SelectValue placeholder={dict.modelConfig.selectRegion} />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-64">
|
||||
{AWS_REGIONS.map(([region, label]) => (
|
||||
<SelectItem key={region} value={region}>
|
||||
{region} ({label})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)
|
||||
const vertexBaseUrlField = (
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="vertex-base-url"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{baseUrlLabel}
|
||||
</Label>
|
||||
<Input
|
||||
id="vertex-base-url"
|
||||
value={baseUrl ?? ""}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange("baseUrl", e.target.value)}
|
||||
placeholder={dict.modelConfig.customEndpoint}
|
||||
className="h-9 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
// API key, with a link to where the provider issues keys
|
||||
const apiKeyField = (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="api-key"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.apiKey}
|
||||
{provider === "ollama" && ` ${dict.modelConfig.optional}`}
|
||||
</Label>
|
||||
{info.apiKeyUrl && (
|
||||
<a
|
||||
href={info.apiKeyUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-primary hover:underline"
|
||||
>
|
||||
{dict.modelConfig.getApiKey}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
{renderSecret({ field: "apiKey", id: "api-key" })}
|
||||
</div>
|
||||
)
|
||||
const baseUrlField = (
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="base-url"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{baseUrlLabel}
|
||||
</Label>
|
||||
<Input
|
||||
id="base-url"
|
||||
value={baseUrl ?? ""}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange("baseUrl", e.target.value)}
|
||||
// Drop a pasted endpoint path such as /chat/completions
|
||||
onBlur={(e) => {
|
||||
const normalized = normalizeBaseUrl(e.target.value)
|
||||
if (normalized !== e.target.value) {
|
||||
onChange("baseUrl", normalized)
|
||||
}
|
||||
}}
|
||||
placeholder={
|
||||
info.defaultBaseUrl || dict.modelConfig.customEndpoint
|
||||
}
|
||||
className="h-9 rounded-xl font-mono text-xs"
|
||||
/>
|
||||
{requestUrl && (
|
||||
<p className="text-xs text-muted-foreground font-mono break-all">
|
||||
{formatMessage(dict.modelConfig.requestUrl, {
|
||||
url: requestUrl,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
{provider === "minimax" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.modelConfig.minimaxBaseUrlHint}
|
||||
</p>
|
||||
)}
|
||||
{provider === "mimo" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.modelConfig.mimoBaseUrlHint}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
// EdgeOne needs no credentials — the caller supplies just a test button
|
||||
if (provider === "edgeone") {
|
||||
return <div className="space-y-5">{footer}</div>
|
||||
}
|
||||
|
||||
if (settingsLayout) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{provider === "bedrock" ? (
|
||||
<>
|
||||
{/* Buttons, not radios: arrow keys would empty
|
||||
secrets without a deliberate press */}
|
||||
<fieldset
|
||||
aria-label={dict.modelConfig.awsCredentials}
|
||||
className="inline-flex rounded-lg bg-muted p-0.5"
|
||||
>
|
||||
{(["apiKey", "accessKey"] as const).map((auth) => (
|
||||
<button
|
||||
key={auth}
|
||||
type="button"
|
||||
aria-pressed={bedrockAuth === auth}
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
if (bedrockAuth === auth) return
|
||||
setChosenAuth(auth)
|
||||
clearSecrets?.(
|
||||
auth === "apiKey"
|
||||
? [
|
||||
"awsAccessKeyId",
|
||||
"awsSecretAccessKey",
|
||||
]
|
||||
: ["apiKey"],
|
||||
)
|
||||
}}
|
||||
className={cn(
|
||||
"inline-flex h-7 items-center rounded-md px-2.5 text-xs text-muted-foreground transition-colors",
|
||||
bedrockAuth === auth &&
|
||||
"bg-card font-medium text-foreground shadow-float",
|
||||
)}
|
||||
>
|
||||
{auth === "apiKey"
|
||||
? dict.modelConfig.bedrockAuthApiKey
|
||||
: dict.modelConfig.bedrockAuthAccessKey}
|
||||
</button>
|
||||
))}
|
||||
</fieldset>
|
||||
{/* Both kinds kept (saved before the choice): the
|
||||
access keys sit unused behind the API key */}
|
||||
{bedrockFilled?.apiKey && bedrockFilled.accessKey && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.modelConfig.bedrockBothSaved}{" "}
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
clearSecrets?.([
|
||||
"awsAccessKeyId",
|
||||
"awsSecretAccessKey",
|
||||
])
|
||||
// This note goes away with the keys
|
||||
document
|
||||
.getElementById("bedrock-api-key")
|
||||
?.focus()
|
||||
}}
|
||||
className="font-medium text-foreground underline underline-offset-2"
|
||||
>
|
||||
{dict.modelConfig.removeAccessKeys}
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{bedrockAuth === "apiKey" ? (
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="bedrock-api-key"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.bedrockApiKey}
|
||||
</Label>
|
||||
{renderSecret({
|
||||
field: "apiKey",
|
||||
id: "bedrock-api-key",
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="aws-access-key-id"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.awsAccessKeyId}
|
||||
</Label>
|
||||
{renderSecret({
|
||||
field: "awsAccessKeyId",
|
||||
id: "aws-access-key-id",
|
||||
})}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="aws-secret-access-key"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.awsSecretAccessKey}
|
||||
</Label>
|
||||
{renderSecret({
|
||||
field: "awsSecretAccessKey",
|
||||
id: "aws-secret-access-key",
|
||||
})}
|
||||
</div>
|
||||
{sessionTokenInput && (
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="aws-session-token"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.awsSessionToken}
|
||||
</Label>
|
||||
{sessionTokenInput}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{
|
||||
dict.modelConfig
|
||||
.awsSessionTokenHint
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{regionField}
|
||||
</>
|
||||
) : provider === "vertexai" ? (
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="vertex-api-key"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.apiKey}
|
||||
</Label>
|
||||
{renderSecret({
|
||||
field: "vertexApiKey",
|
||||
id: "vertex-api-key",
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
apiKeyField
|
||||
)}
|
||||
<div className="space-y-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOptionsOpen(!optionsOpen)}
|
||||
aria-expanded={optionsOpen}
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn(
|
||||
"size-3.5 transition-transform",
|
||||
optionsOpen && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
{provider === "bedrock"
|
||||
? dict.modelConfig.moreOptionsName
|
||||
: dict.modelConfig.moreOptions}
|
||||
</button>
|
||||
{optionsOpen && (
|
||||
<>
|
||||
{provider !== "bedrock" &&
|
||||
(provider === "vertexai"
|
||||
? vertexBaseUrlField
|
||||
: baseUrlField)}
|
||||
{nameField}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{footer}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* Display Name */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="provider-name"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Tag className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.displayName}
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-name"
|
||||
value={name ?? ""}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange("name", e.target.value)}
|
||||
placeholder={info.label}
|
||||
className="h-9"
|
||||
/>
|
||||
</div>
|
||||
{nameField}
|
||||
|
||||
{provider === "bedrock" ? (
|
||||
<>
|
||||
{/* Bedrock API key: used instead of the access keys */}
|
||||
{bedrockApiKey && (
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="bedrock-api-key"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.bedrockApiKey}
|
||||
</Label>
|
||||
{renderSecret({
|
||||
field: "apiKey",
|
||||
id: "bedrock-api-key",
|
||||
})}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.modelConfig.bedrockApiKeyHint}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AWS Access Key ID */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
@@ -142,37 +508,7 @@ export function ProviderCredentialsFields({
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* AWS Region */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="aws-region"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.awsRegion}
|
||||
</Label>
|
||||
<Select
|
||||
value={awsRegion || ""}
|
||||
disabled={disabled}
|
||||
onValueChange={(v) => onChange("awsRegion", v)}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="aws-region"
|
||||
className="h-9 font-mono text-xs hover:bg-accent"
|
||||
>
|
||||
<SelectValue
|
||||
placeholder={dict.modelConfig.selectRegion}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-64">
|
||||
{AWS_REGIONS.map(([region, label]) => (
|
||||
<SelectItem key={region} value={region}>
|
||||
{region} ({label})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{regionField}
|
||||
</>
|
||||
) : provider === "vertexai" ? (
|
||||
<>
|
||||
@@ -191,104 +527,12 @@ export function ProviderCredentialsFields({
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Base URL (optional) */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="vertex-base-url"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{baseUrlLabel}
|
||||
</Label>
|
||||
<Input
|
||||
id="vertex-base-url"
|
||||
value={baseUrl ?? ""}
|
||||
disabled={disabled}
|
||||
onChange={(e) =>
|
||||
onChange("baseUrl", e.target.value)
|
||||
}
|
||||
placeholder={dict.modelConfig.customEndpoint}
|
||||
className="h-9 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
{vertexBaseUrlField}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* API Key, with a link to where the provider issues keys */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="api-key"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{dict.modelConfig.apiKey}
|
||||
{provider === "ollama" &&
|
||||
` ${dict.modelConfig.optional}`}
|
||||
</Label>
|
||||
{info.apiKeyUrl && (
|
||||
<a
|
||||
href={info.apiKeyUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-primary hover:underline"
|
||||
>
|
||||
{dict.modelConfig.getApiKey}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
{renderSecret({ field: "apiKey", id: "api-key" })}
|
||||
</div>
|
||||
|
||||
{/* Base URL */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="base-url"
|
||||
className="text-xs font-medium flex items-center gap-1.5"
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
{baseUrlLabel}
|
||||
</Label>
|
||||
<Input
|
||||
id="base-url"
|
||||
value={baseUrl ?? ""}
|
||||
disabled={disabled}
|
||||
onChange={(e) =>
|
||||
onChange("baseUrl", e.target.value)
|
||||
}
|
||||
// Drop a pasted endpoint path such as /chat/completions
|
||||
onBlur={(e) => {
|
||||
const normalized = normalizeBaseUrl(
|
||||
e.target.value,
|
||||
)
|
||||
if (normalized !== e.target.value) {
|
||||
onChange("baseUrl", normalized)
|
||||
}
|
||||
}}
|
||||
placeholder={
|
||||
info.defaultBaseUrl ||
|
||||
dict.modelConfig.customEndpoint
|
||||
}
|
||||
className="h-9 rounded-xl font-mono text-xs"
|
||||
/>
|
||||
{requestUrl && (
|
||||
<p className="text-xs text-muted-foreground font-mono break-all">
|
||||
{formatMessage(dict.modelConfig.requestUrl, {
|
||||
url: requestUrl,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
{provider === "minimax" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.modelConfig.minimaxBaseUrlHint}
|
||||
</p>
|
||||
)}
|
||||
{provider === "mimo" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.modelConfig.mimoBaseUrlHint}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{apiKeyField}
|
||||
{baseUrlField}
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -85,18 +85,6 @@ export function QuotaLimitToast({
|
||||
{/* Message */}
|
||||
<div className="text-sm text-muted-foreground leading-relaxed mb-4 space-y-2">
|
||||
<p>{quotaMessage}</p>
|
||||
{!isSelfHosted && (
|
||||
<p
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: formatMessage(
|
||||
dict.quota.doubaoSponsorship,
|
||||
{
|
||||
link: "https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio",
|
||||
},
|
||||
),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<p
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: tipHtml,
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
|
||||
interface ResetWarningModalProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onClear: () => void
|
||||
}
|
||||
|
||||
export function ResetWarningModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
onClear,
|
||||
}: ResetWarningModalProps) {
|
||||
const dict = useDictionary()
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dict.dialogs.clearTitle}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{dict.dialogs.clearDescription}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
{dict.common.cancel}
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={onClear}>
|
||||
{dict.dialogs.clearEverything}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
+54
-41
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -10,15 +10,8 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export type ExportFormat = "drawio" | "png" | "svg" | "xmlsvg"
|
||||
|
||||
@@ -39,10 +32,12 @@ export function SaveDialog({
|
||||
const [filename, setFilename] = useState(defaultFilename)
|
||||
const [format, setFormat] = useState<ExportFormat>("drawio")
|
||||
|
||||
// The default name each time the dialog opens; a chat title that comes
|
||||
// while it is open (the chat is saved meanwhile) keeps what was typed
|
||||
const wasOpenRef = useRef(false)
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setFilename(defaultFilename)
|
||||
}
|
||||
if (open && !wasOpenRef.current) setFilename(defaultFilename)
|
||||
wasOpenRef.current = open
|
||||
}, [open, defaultFilename])
|
||||
|
||||
const handleSave = () => {
|
||||
@@ -52,6 +47,8 @@ export function SaveDialog({
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
// Enter that picks an IME candidate (Safari: keyCode 229)
|
||||
if (e.nativeEvent.isComposing || e.keyCode === 229) return
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
handleSave()
|
||||
@@ -62,21 +59,25 @@ export function SaveDialog({
|
||||
{
|
||||
value: "drawio" as const,
|
||||
label: dict.save.formats.drawio,
|
||||
hint: dict.save.hints.drawio,
|
||||
extension: ".drawio",
|
||||
},
|
||||
{
|
||||
value: "png" as const,
|
||||
label: dict.save.formats.png,
|
||||
hint: dict.save.hints.png,
|
||||
extension: ".png",
|
||||
},
|
||||
{
|
||||
value: "svg" as const,
|
||||
label: dict.save.formats.svg,
|
||||
hint: dict.save.hints.svg,
|
||||
extension: ".svg",
|
||||
},
|
||||
{
|
||||
value: "xmlsvg" as const,
|
||||
label: dict.save.formats.xmlsvg,
|
||||
hint: dict.save.hints.xmlsvg,
|
||||
extension: ".drawio.svg",
|
||||
},
|
||||
]
|
||||
@@ -85,7 +86,7 @@ export function SaveDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dict.save.title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
@@ -93,44 +94,54 @@ export function SaveDialog({
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">
|
||||
{dict.save.format}
|
||||
</label>
|
||||
<Select
|
||||
value={format}
|
||||
onValueChange={(v) => setFormat(v as ExportFormat)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{FORMAT_OPTIONS.map((opt) => (
|
||||
<SelectItem
|
||||
key={opt.value}
|
||||
value={opt.value}
|
||||
>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label={dict.save.format}
|
||||
className="grid grid-cols-2 gap-2"
|
||||
>
|
||||
{FORMAT_OPTIONS.map((opt) => (
|
||||
// biome-ignore lint/a11y/useSemanticElements: styled radio tile
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={format === opt.value}
|
||||
onClick={() => setFormat(opt.value)}
|
||||
className={cn(
|
||||
"rounded-lg border border-border p-3 text-left transition-colors hover:border-foreground/30",
|
||||
format === opt.value &&
|
||||
"border-foreground bg-accent",
|
||||
)}
|
||||
>
|
||||
<span className="block text-[13px] font-medium text-foreground">
|
||||
{opt.label}
|
||||
</span>
|
||||
<span className="mt-0.5 block text-xs text-muted-foreground">
|
||||
{opt.hint}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">
|
||||
<label
|
||||
htmlFor="export-filename"
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
{dict.save.filename}
|
||||
</label>
|
||||
<div className="flex items-stretch">
|
||||
<Input
|
||||
{/* One field: the name, then its extension */}
|
||||
<div className="flex h-9 items-center overflow-hidden rounded-md border border-input focus-within:ring-2 focus-within:ring-ring/40">
|
||||
<input
|
||||
id="export-filename"
|
||||
value={filename}
|
||||
onChange={(e) => setFilename(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={dict.save.filenamePlaceholder}
|
||||
autoFocus
|
||||
onFocus={(e) => e.target.select()}
|
||||
className="rounded-r-none border-r-0 focus-visible:z-10"
|
||||
className="h-full min-w-0 flex-1 bg-transparent px-3 text-sm outline-none"
|
||||
/>
|
||||
<span className="inline-flex items-center px-3 rounded-r-md border border-l-0 border-input bg-muted text-sm text-muted-foreground font-mono">
|
||||
<span className="shrink-0 pr-3 text-sm text-muted-foreground">
|
||||
{currentFormat?.extension || ".drawio"}
|
||||
</span>
|
||||
</div>
|
||||
@@ -143,7 +154,9 @@ export function SaveDialog({
|
||||
>
|
||||
{dict.common.cancel}
|
||||
</Button>
|
||||
<Button onClick={handleSave}>{dict.common.save}</Button>
|
||||
<Button onClick={handleSave}>
|
||||
{dict.workspace.export}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
+522
-629
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,144 @@
|
||||
import { ChevronRight, Search } from "lucide-react"
|
||||
import { useState } from "react"
|
||||
import { ProviderLogo } from "@/components/provider-logo"
|
||||
import { SettingsHeader } from "@/components/settings/settings-header"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { filterProviderGroups, PROVIDER_NOTE_KEYS } from "@/lib/provider-setup"
|
||||
import { PROVIDER_INFO, type ProviderName } from "@/lib/types/model-config"
|
||||
|
||||
/** Every provider in groups, with a search; picking one adds it */
|
||||
export function ProviderPicker({
|
||||
added,
|
||||
onPick,
|
||||
onBack,
|
||||
}: {
|
||||
/** Provider types the user has already added */
|
||||
added: ProviderName[]
|
||||
onPick: (provider: ProviderName) => void
|
||||
onBack: () => void
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const t = dict.modelConfig
|
||||
const [query, setQuery] = useState("")
|
||||
const groups = filterProviderGroups(query)
|
||||
const groupLabels: Record<string, string> = {
|
||||
vendors: t.groupVendors,
|
||||
aggregators: t.groupAggregators,
|
||||
cloud: t.groupCloud,
|
||||
selfHosted: t.groupSelfHosted,
|
||||
}
|
||||
const notes = t as Record<string, string>
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<SettingsHeader>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBack}
|
||||
className="rounded text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t.models}
|
||||
</button>
|
||||
<ChevronRight className="size-3.5 text-muted-foreground/60" />
|
||||
<h2
|
||||
className="font-semibold outline-none"
|
||||
tabIndex={-1}
|
||||
data-page-title
|
||||
>
|
||||
{t.addProvider}
|
||||
</h2>
|
||||
</SettingsHeader>
|
||||
<div className="px-6 pb-3">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<input
|
||||
// The page is opened to search it
|
||||
autoFocus
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
// Enter that confirms an IME candidate picks nothing
|
||||
if (
|
||||
e.nativeEvent.isComposing ||
|
||||
e.keyCode === 229
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Enter picks the first match
|
||||
const first = groups[0]?.providers[0]
|
||||
if (e.key === "Enter" && query.trim() && first) {
|
||||
e.preventDefault()
|
||||
onPick(first)
|
||||
}
|
||||
}}
|
||||
placeholder={t.searchProviders}
|
||||
aria-label={t.searchProviders}
|
||||
className="h-10 w-full rounded-xl border border-border bg-background pr-3 pl-9 text-[13px] outline-none placeholder:text-muted-foreground focus-visible:border-foreground/40 focus-visible:ring-2 focus-visible:ring-ring/20"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="px-6 pb-6">
|
||||
{groups.length === 0 && (
|
||||
<p className="py-8 text-center text-[13px] text-muted-foreground">
|
||||
{t.noProvidersFound}
|
||||
</p>
|
||||
)}
|
||||
{groups.map((group) => (
|
||||
<section key={group.id} className="mb-3.5">
|
||||
<h3 className="mb-1.5 text-[11px] font-medium text-muted-foreground">
|
||||
{groupLabels[group.id]}
|
||||
</h3>
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(148px,1fr))] gap-2">
|
||||
{group.providers.map((provider) => {
|
||||
const noteKey = PROVIDER_NOTE_KEYS[provider]
|
||||
const note = [
|
||||
noteKey && notes[noteKey],
|
||||
added.includes(provider) && t.added,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")
|
||||
return (
|
||||
<button
|
||||
key={provider}
|
||||
type="button"
|
||||
onClick={() => onPick(provider)}
|
||||
data-testid={`pick-provider-${provider}`}
|
||||
className="flex h-[46px] min-w-0 items-center gap-2.5 rounded-xl border border-border px-3 text-left transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<ProviderLogo
|
||||
provider={provider}
|
||||
className="shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 leading-tight">
|
||||
<span
|
||||
className="block truncate text-[12.5px] font-medium"
|
||||
title={
|
||||
PROVIDER_INFO[provider]
|
||||
.label
|
||||
}
|
||||
>
|
||||
{
|
||||
PROVIDER_INFO[provider]
|
||||
.label
|
||||
}
|
||||
</span>
|
||||
{note && (
|
||||
<span className="block truncate text-[11px] text-muted-foreground">
|
||||
{note}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import {
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
ChevronRight,
|
||||
CircleDashed,
|
||||
CircleDotDashed,
|
||||
Lock,
|
||||
Plus,
|
||||
Server,
|
||||
} from "lucide-react"
|
||||
import { shortModelName } from "@/components/model-selector"
|
||||
import { ProviderLogo } from "@/components/provider-logo"
|
||||
import { SettingsHeader } from "@/components/settings/settings-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { POPULAR_PROVIDERS, providerStatus } from "@/lib/provider-setup"
|
||||
import {
|
||||
type FlattenedModel,
|
||||
PROVIDER_INFO,
|
||||
type ProviderConfig,
|
||||
type ProviderName,
|
||||
} from "@/lib/types/model-config"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function InUse() {
|
||||
const dict = useDictionary()
|
||||
return (
|
||||
<span className="rounded bg-primary px-1.5 py-0.5 text-[11px] font-medium text-primary-foreground">
|
||||
{dict.modelConfig.inUse}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The models tab's first page: the user's providers and the server's models */
|
||||
export function ProvidersList({
|
||||
providers,
|
||||
serverModels,
|
||||
selectedModelId,
|
||||
onOpen,
|
||||
onAdd,
|
||||
onBrowse,
|
||||
}: {
|
||||
providers: ProviderConfig[]
|
||||
serverModels: FlattenedModel[]
|
||||
selectedModelId: string | undefined
|
||||
onOpen: (providerId: string) => void
|
||||
onAdd: (provider: ProviderName) => void
|
||||
/** Shows every provider to pick from */
|
||||
onBrowse: () => void
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const t = dict.modelConfig
|
||||
const userProviderInUse = providers.find((p) =>
|
||||
p.models.some((m) => m.id === selectedModelId),
|
||||
)
|
||||
// No model chosen is the server's default model
|
||||
const serverInUse =
|
||||
!selectedModelId || serverModels.some((m) => m.id === selectedModelId)
|
||||
|
||||
const names = serverModels
|
||||
.slice(0, 3)
|
||||
.map((m) => shortModelName(m.modelId))
|
||||
.join(t.listSeparator)
|
||||
const serverCard = (serverModels.length > 0 || serverInUse) && (
|
||||
<div className="flex items-center gap-3 rounded-xl border border-border-subtle bg-surface-1 px-4 py-3">
|
||||
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-border-subtle bg-surface-0">
|
||||
<Server className="size-4 text-muted-foreground" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 text-[13px] font-medium">
|
||||
{t.serverModelsTitle}
|
||||
{serverInUse && <InUse />}
|
||||
</div>
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
{serverModels.length > 0
|
||||
? formatMessage(
|
||||
serverModels.length === 1
|
||||
? t.serverModelsSummaryOne
|
||||
: t.serverModelsSummaryOther,
|
||||
{
|
||||
count: serverModels.length,
|
||||
names:
|
||||
serverModels.length > 3
|
||||
? `${names}…`
|
||||
: names,
|
||||
},
|
||||
)
|
||||
: t.serverDefaultSummary}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const statusText = (p: ProviderConfig) => {
|
||||
const status = providerStatus(p)
|
||||
switch (status.kind) {
|
||||
case "error":
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-destructive">
|
||||
<AlertCircle className="size-3.5" />
|
||||
{formatMessage(t.statusError, { count: status.count })}
|
||||
</span>
|
||||
)
|
||||
case "incomplete":
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-amber-700 dark:text-amber-400">
|
||||
<CircleDotDashed className="size-3.5" />
|
||||
{t.statusIncomplete}
|
||||
</span>
|
||||
)
|
||||
case "untested":
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-muted-foreground">
|
||||
<CircleDashed className="size-3.5" />
|
||||
{formatMessage(t.statusUntested, {
|
||||
count: status.count,
|
||||
})}
|
||||
</span>
|
||||
)
|
||||
case "ok":
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-success">
|
||||
<CheckCircle2 className="size-3.5" />
|
||||
{formatMessage(t.statusOk, { count: status.count })}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<SettingsHeader>
|
||||
<h2
|
||||
className="font-semibold outline-none"
|
||||
tabIndex={-1}
|
||||
data-page-title
|
||||
>
|
||||
{t.models}
|
||||
</h2>
|
||||
</SettingsHeader>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="space-y-6 px-6 pb-6">
|
||||
{providers.length === 0 ? (
|
||||
<>
|
||||
{serverCard}
|
||||
<section className="space-y-3">
|
||||
<div>
|
||||
<h3 className="text-[13px] font-semibold">
|
||||
{t.useOwnKey}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t.useOwnKeyHint}
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(170px,1fr))] gap-2.5">
|
||||
{POPULAR_PROVIDERS.map((provider) => (
|
||||
<button
|
||||
key={provider}
|
||||
type="button"
|
||||
onClick={() => onAdd(provider)}
|
||||
data-testid={`pick-provider-${provider}`}
|
||||
className="flex h-14 items-center gap-3 rounded-xl border border-border px-4 text-left text-[13px] font-medium transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-surface-2">
|
||||
<ProviderLogo
|
||||
provider={provider}
|
||||
/>
|
||||
</span>
|
||||
<span className="truncate">
|
||||
{PROVIDER_INFO[provider].label}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBrowse}
|
||||
className="flex items-center gap-1 text-[13px] font-medium hover:underline"
|
||||
>
|
||||
{formatMessage(t.viewAllProviders, {
|
||||
count: Object.keys(PROVIDER_INFO)
|
||||
.length,
|
||||
})}
|
||||
<ChevronRight className="size-3.5" />
|
||||
</button>
|
||||
</section>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<section className="space-y-2.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-[13px] font-semibold">
|
||||
{t.myProviders}
|
||||
</h3>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onBrowse}
|
||||
className="h-8 gap-1.5 rounded-lg text-xs"
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
{t.addProvider}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="divide-y divide-border-subtle rounded-xl border border-border">
|
||||
{providers.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => onOpen(p.id)}
|
||||
data-testid={`provider-row-${p.id}`}
|
||||
className={cn(
|
||||
"flex min-h-[60px] w-full items-center gap-3 px-4 py-2.5 text-left transition-colors first:rounded-t-xl last:rounded-b-xl",
|
||||
"hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
)}
|
||||
>
|
||||
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-surface-2">
|
||||
<ProviderLogo
|
||||
provider={p.provider}
|
||||
/>
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-center gap-2 text-[13px] font-medium">
|
||||
<span className="truncate">
|
||||
{p.name ||
|
||||
PROVIDER_INFO[
|
||||
p.provider
|
||||
].label}
|
||||
</span>
|
||||
{userProviderInUse?.id ===
|
||||
p.id && <InUse />}
|
||||
</span>
|
||||
<span className="block truncate font-mono text-xs text-muted-foreground">
|
||||
{p.models.length > 0 ? (
|
||||
p.models
|
||||
.map(
|
||||
(m) =>
|
||||
m.modelId,
|
||||
)
|
||||
.join(
|
||||
t.listSeparator,
|
||||
)
|
||||
) : (
|
||||
<span className="font-sans">
|
||||
{t.noModelsYet}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="shrink-0 text-xs">
|
||||
{statusText(p)}
|
||||
</span>
|
||||
<ChevronRight className="size-4 shrink-0 text-muted-foreground/60" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
{serverCard}
|
||||
</>
|
||||
)}
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Lock className="size-3.5 shrink-0" />
|
||||
{t.keysStayLocal}
|
||||
</p>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/** A settings page's title row; the dialog's close button sits at its end */
|
||||
export function SettingsHeader({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<header className="flex h-14 shrink-0 items-center gap-1.5 pr-14 pl-6 text-[15px]">
|
||||
{children}
|
||||
</header>
|
||||
)
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { GripVerticalIcon } from "lucide-react"
|
||||
import * as ResizablePrimitive from "react-resizable-panels"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ResizablePanelGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) {
|
||||
return (
|
||||
<ResizablePrimitive.PanelGroup
|
||||
data-slot="resizable-panel-group"
|
||||
className={cn(
|
||||
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ResizablePanel({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
|
||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
|
||||
}
|
||||
|
||||
function ResizableHandle({
|
||||
withHandle,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
|
||||
withHandle?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ResizablePrimitive.PanelResizeHandle
|
||||
data-slot="resizable-handle"
|
||||
className={cn(
|
||||
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{withHandle && (
|
||||
<div className="bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border">
|
||||
<GripVerticalIcon className="size-2.5" />
|
||||
</div>
|
||||
)}
|
||||
</ResizablePrimitive.PanelResizeHandle>
|
||||
)
|
||||
}
|
||||
|
||||
export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import { Toaster } from "sonner"
|
||||
import { useSettingsStore } from "@/stores/settings-store"
|
||||
|
||||
/** The single toast container, mounted once at the root */
|
||||
export function AppToaster() {
|
||||
const isDark = useSettingsStore((s) => s.isDark)
|
||||
return (
|
||||
<Toaster
|
||||
position="bottom-center"
|
||||
// Show stacked toasts in full, so a later one never covers the
|
||||
// button of an earlier one (e.g. "Continue without saving")
|
||||
expand
|
||||
theme={isDark ? "dark" : "light"}
|
||||
offset={{ bottom: 20 }}
|
||||
mobileOffset={{ bottom: 72 }}
|
||||
toastOptions={{
|
||||
duration: 2500,
|
||||
style: { maxWidth: "480px" },
|
||||
classNames: {
|
||||
toast: "!rounded-xl !border-border !bg-card !text-foreground !shadow-pop",
|
||||
description: "!text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
"use client"
|
||||
|
||||
import { getAssetUrl } from "@/lib/base-path"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
/** The app icon in a rounded tile; the white variant is used in dark mode */
|
||||
export function BrandMark({ className }: { className?: string }) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"relative inline-flex size-7 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-card",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* biome-ignore lint/performance/noImgElement: tiny static icon */}
|
||||
<img
|
||||
src={getAssetUrl("/favicon-192x192.png")}
|
||||
alt=""
|
||||
className="size-full object-contain dark:hidden"
|
||||
/>
|
||||
{/* biome-ignore lint/performance/noImgElement: tiny static icon */}
|
||||
<img
|
||||
src={getAssetUrl("/favicon-white.svg")}
|
||||
alt=""
|
||||
className="hidden size-5 object-contain dark:block"
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
import { forwardRef } from "react"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface IconButtonProps extends React.ComponentProps<"button"> {
|
||||
label: string
|
||||
/** Shown next to the label in the tooltip, e.g. "⌘B" */
|
||||
shortcut?: string
|
||||
active?: boolean
|
||||
tooltipSide?: "top" | "bottom" | "left" | "right"
|
||||
size?: "sm" | "md"
|
||||
}
|
||||
|
||||
/** Square icon button with a tooltip; the tooltip text is also its label */
|
||||
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||
function IconButton(
|
||||
{
|
||||
label,
|
||||
shortcut,
|
||||
active = false,
|
||||
tooltipSide = "bottom",
|
||||
size = "md",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
ref={ref}
|
||||
type="button"
|
||||
aria-label={label}
|
||||
aria-pressed={active || undefined}
|
||||
className={cn(
|
||||
"inline-flex shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors",
|
||||
"hover:bg-accent hover:text-foreground",
|
||||
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",
|
||||
"disabled:pointer-events-none disabled:opacity-35",
|
||||
"[&_svg]:size-4 [&_svg]:stroke-[1.75]",
|
||||
size === "md" ? "size-8" : "size-7",
|
||||
// A tinted tile: solid ink is for the main action
|
||||
active &&
|
||||
"bg-interactive-active text-foreground hover:bg-interactive-active [&_svg]:stroke-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side={tooltipSide}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{label}
|
||||
{shortcut && (
|
||||
<kbd className="font-sans text-[11px] opacity-60">
|
||||
{shortcut}
|
||||
</kbd>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
/** Thin vertical divider between toolbar groups */
|
||||
export function ToolbarDivider() {
|
||||
return <span className="mx-1 h-5 w-px shrink-0 bg-border" aria-hidden />
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
"use client"
|
||||
|
||||
import { MessageSquare, PanelRightOpen, Settings, Shapes } from "lucide-react"
|
||||
import { usePathname, useRouter } from "next/navigation"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { CanvasStage } from "@/components/canvas/canvas-stage"
|
||||
import {
|
||||
ChatEngineProvider,
|
||||
useChatEngine,
|
||||
} from "@/components/chat/chat-engine"
|
||||
import { ChatPanel } from "@/components/chat/chat-panel"
|
||||
import { CompareDialog } from "@/components/chat/compare-dialog"
|
||||
import { LobbyHero } from "@/components/chat/lobby-hero"
|
||||
import { SaveDialog } from "@/components/save-dialog"
|
||||
import { SettingsDialog } from "@/components/settings-dialog"
|
||||
import { BrandMark } from "@/components/workspace/brand-mark"
|
||||
import { IconButton } from "@/components/workspace/icon-button"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { usePanelWidth } from "@/hooks/use-panel-width"
|
||||
import { setAppShortcutHandler } from "@/lib/drawio/editor-bridge"
|
||||
import { i18n, type Locale } from "@/lib/i18n/config"
|
||||
import { modKey } from "@/lib/platform"
|
||||
import { STORAGE_KEYS } from "@/lib/storage"
|
||||
import { cn, isRealDiagram } from "@/lib/utils"
|
||||
import { useSettingsStore } from "@/stores/settings-store"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
import { useVersionsStore } from "@/stores/versions-store"
|
||||
|
||||
/** File types the "Open .drawio file" picker accepts */
|
||||
const DIAGRAM_FILE_ACCEPT = ".drawio,.xml,.svg,application/xml,image/svg+xml"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
// Gap between the floating panel and the window edge
|
||||
const PANEL_GAP = 12
|
||||
|
||||
function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = useState(false)
|
||||
useEffect(() => {
|
||||
const query = window.matchMedia(
|
||||
`(max-width: ${MOBILE_BREAKPOINT - 1}px)`,
|
||||
)
|
||||
const update = () => setIsMobile(query.matches)
|
||||
update()
|
||||
query.addEventListener("change", update)
|
||||
return () => query.removeEventListener("change", update)
|
||||
}, [])
|
||||
return isMobile
|
||||
}
|
||||
|
||||
/** Restore the language picked last time (the URL may say otherwise) */
|
||||
function useSavedLocale() {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
useEffect(() => {
|
||||
const saved = localStorage.getItem(STORAGE_KEYS.locale)
|
||||
if (!saved || !i18n.locales.includes(saved as Locale)) return
|
||||
const parts = pathname.split("/").filter(Boolean)
|
||||
if (parts[0] === saved) return
|
||||
parts[0] = saved
|
||||
const { search, hash } = window.location
|
||||
router.replace(`/${parts.join("/")}${search}${hash}`)
|
||||
}, [])
|
||||
}
|
||||
|
||||
/** The diagram's title as a file name, or diagram-YYYY-MM-DD without one */
|
||||
export function exportFilename(title: string | null): string {
|
||||
const name = (title && title !== "New Chat" ? title : "")
|
||||
.replace(/[\\/:*?"<>|]+/g, "-")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.slice(0, 80)
|
||||
// Local date (toISOString would give UTC)
|
||||
return name || `diagram-${new Date().toLocaleDateString("sv-SE")}`
|
||||
}
|
||||
|
||||
/** App name and settings button above the start screen */
|
||||
function StartBar({
|
||||
className,
|
||||
nameClassName,
|
||||
}: {
|
||||
className: string
|
||||
nameClassName: string
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const openSettings = useUiStore((s) => s.openSettings)
|
||||
return (
|
||||
<div className={className}>
|
||||
<BrandMark className="size-6" />
|
||||
<span
|
||||
className={cn(
|
||||
"text-[13px] font-semibold tracking-[-0.01em]",
|
||||
nameClassName,
|
||||
)}
|
||||
>
|
||||
Next AI Draw.io
|
||||
</span>
|
||||
<IconButton
|
||||
label={dict.nav.settings}
|
||||
onClick={() => openSettings()}
|
||||
data-testid="settings-button"
|
||||
>
|
||||
<Settings />
|
||||
</IconButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The whole editor: canvas, chat panel, dialogs */
|
||||
export function Workspace() {
|
||||
const hydrate = useSettingsStore((s) => s.hydrate)
|
||||
useEffect(() => {
|
||||
hydrate()
|
||||
}, [hydrate])
|
||||
useSavedLocale()
|
||||
|
||||
return (
|
||||
<ChatEngineProvider>
|
||||
<WorkspaceLayout />
|
||||
</ChatEngineProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function WorkspaceLayout() {
|
||||
const dict = useDictionary()
|
||||
const engine = useChatEngine()
|
||||
const { chartXML, saveDiagramToFile } = useDiagram()
|
||||
const isMobile = useIsMobile()
|
||||
const panelWidth = usePanelWidth()
|
||||
const {
|
||||
panelOpen,
|
||||
togglePanel,
|
||||
setPanelOpen,
|
||||
mobileView,
|
||||
setMobileView,
|
||||
focusComposer,
|
||||
saveDialogOpen,
|
||||
setSaveDialogOpen,
|
||||
} = useUiStore()
|
||||
const heroDismissed = useUiStore((s) => s.heroDismissed)
|
||||
const setHeroDismissed = useUiStore((s) => s.setHeroDismissed)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Start screen: nothing said and nothing drawn yet. A new chat brings
|
||||
// it back, an opened file or saved chat puts it away (the chat engine).
|
||||
const showHero =
|
||||
engine.isRestored &&
|
||||
engine.messages.length === 0 &&
|
||||
!engine.isResending &&
|
||||
!isRealDiagram(chartXML) &&
|
||||
!heroDismissed
|
||||
|
||||
// Phones: show the canvas while the AI draws and when a new version
|
||||
// lands, so the result is visible; the chat tab gets a dot meanwhile
|
||||
const isBusy = engine.isBusy
|
||||
const versionCount = useVersionsStore((s) => s.versions.length)
|
||||
const [chatUnread, setChatUnread] = useState(false)
|
||||
const lastVersionCountRef = useRef(versionCount)
|
||||
useEffect(() => {
|
||||
if (isMobile && isBusy) setMobileView("canvas")
|
||||
}, [isMobile, isBusy, setMobileView])
|
||||
useEffect(() => {
|
||||
const grew = versionCount > lastVersionCountRef.current
|
||||
lastVersionCountRef.current = versionCount
|
||||
if (isMobile && grew && engine.isRestored) {
|
||||
setMobileView("canvas")
|
||||
setChatUnread(true)
|
||||
}
|
||||
}, [versionCount, isMobile, engine.isRestored, setMobileView])
|
||||
useEffect(() => {
|
||||
if (mobileView === "chat") setChatUnread(false)
|
||||
}, [mobileView])
|
||||
|
||||
// ⌘B toggles the panel; ⌘/ asks the AI about the selection
|
||||
useEffect(() => {
|
||||
const handle = (event: KeyboardEvent) => {
|
||||
if (!(event.metaKey || event.ctrlKey)) return false
|
||||
// ⌘⇧B stays with the browser (Chrome's bookmarks bar)
|
||||
if (!event.shiftKey && (event.key === "b" || event.key === "B")) {
|
||||
if (isMobile) return false
|
||||
togglePanel()
|
||||
return true
|
||||
}
|
||||
if (event.key === "/") {
|
||||
setHeroDismissed(true)
|
||||
focusComposer()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (handle(event)) event.preventDefault()
|
||||
}
|
||||
// draw.io takes focus when it (re)loads, e.g. after a language
|
||||
// switch; Escape typed there must still close our dialogs.
|
||||
// ⌘B stays with draw.io in the canvas (bold, and ⇧ for to back).
|
||||
const handleInFrame = (event: KeyboardEvent) => {
|
||||
if (event.key === "b" || event.key === "B") return false
|
||||
if (event.key === "Escape") {
|
||||
const ui = useUiStore.getState()
|
||||
if (
|
||||
ui.settingsOpen ||
|
||||
ui.compareVersionId ||
|
||||
ui.saveDialogOpen
|
||||
) {
|
||||
ui.setSettingsOpen(false)
|
||||
ui.closeCompare()
|
||||
ui.setSaveDialogOpen(false)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return handle(event)
|
||||
}
|
||||
window.addEventListener("keydown", onKeyDown)
|
||||
setAppShortcutHandler(handleInFrame)
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown)
|
||||
setAppShortcutHandler(null)
|
||||
}
|
||||
}, [isMobile, togglePanel, focusComposer])
|
||||
|
||||
const openFile = () => fileInputRef.current?.click()
|
||||
const dismissHero = () => {
|
||||
setHeroDismissed(true)
|
||||
setPanelOpen(true)
|
||||
}
|
||||
|
||||
const panelVisible = !isMobile && !showHero && panelOpen
|
||||
// The canvas edge slides with the panel as it opens or closes; a window
|
||||
// resize or a dragged panel edge moves it at once. Set in the render
|
||||
// that changes the edge, so the transition applies to that change.
|
||||
const [sliding, setSliding] = useState(false)
|
||||
const [lastPanelVisible, setLastPanelVisible] = useState(panelVisible)
|
||||
if (lastPanelVisible !== panelVisible) {
|
||||
setLastPanelVisible(panelVisible)
|
||||
setSliding(true)
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!sliding) return
|
||||
const timer = setTimeout(() => setSliding(false), 400)
|
||||
return () => clearTimeout(timer)
|
||||
}, [sliding])
|
||||
// The panel floats on the right; the canvas ends where it begins
|
||||
const canvasRight = panelVisible ? panelWidth + PANEL_GAP * 2 : 0
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 overflow-hidden bg-canvas"
|
||||
data-testid="workspace"
|
||||
>
|
||||
{/* One canvas for both layouts: a new one would reload draw.io
|
||||
and lose its undo history */}
|
||||
<div className="absolute inset-0 flex flex-col">
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<CanvasStage
|
||||
className={
|
||||
isMobile
|
||||
? cn(
|
||||
"inset-0",
|
||||
mobileView !== "canvas" && "invisible",
|
||||
)
|
||||
: cn(
|
||||
"inset-y-0 left-0",
|
||||
sliding &&
|
||||
"transition-[right] duration-300 ease-[var(--ease-out)]",
|
||||
)
|
||||
}
|
||||
style={isMobile ? undefined : { right: canvasRight }}
|
||||
hideOverlays={!isMobile && showHero}
|
||||
/>
|
||||
{isMobile ? (
|
||||
mobileView === "chat" &&
|
||||
(showHero ? (
|
||||
<div className="absolute inset-0 overflow-y-auto bg-canvas">
|
||||
<StartBar
|
||||
className="flex items-center gap-2 px-4 pt-3"
|
||||
nameClassName="mr-auto"
|
||||
/>
|
||||
<LobbyHero
|
||||
compact
|
||||
onOpenFile={openFile}
|
||||
onDrawYourself={() => {
|
||||
setHeroDismissed(true)
|
||||
setMobileView("canvas")
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<ChatPanel mobile onOpenFile={openFile} />
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
{panelVisible && (
|
||||
<ChatPanel onOpenFile={openFile} />
|
||||
)}
|
||||
|
||||
{/* Below draw.io's toolbar (50 px), whose
|
||||
right-hand buttons it would cover */}
|
||||
{!showHero && !panelOpen && (
|
||||
<div className="absolute top-[60px] right-3 z-20 flex items-center gap-1 rounded-xl bg-card p-1 shadow-float animate-fade-in">
|
||||
<BrandMark className="mx-0.5 size-6" />
|
||||
<IconButton
|
||||
label={dict.nav.showPanel}
|
||||
shortcut={`${modKey}B`}
|
||||
onClick={() => setPanelOpen(true)}
|
||||
data-testid="show-panel"
|
||||
>
|
||||
<PanelRightOpen />
|
||||
</IconButton>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showHero && (
|
||||
<>
|
||||
<div className="absolute inset-0 z-10 overflow-y-auto bg-canvas">
|
||||
<div className="flex min-h-full items-center">
|
||||
<LobbyHero
|
||||
onOpenFile={openFile}
|
||||
onDrawYourself={dismissHero}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<StartBar
|
||||
className="absolute top-3 left-3 z-20 flex items-center gap-1.5 rounded-xl bg-card py-1 pr-1 pl-1.5 shadow-float"
|
||||
nameClassName="pr-1"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{isMobile && (
|
||||
<nav className="flex shrink-0 items-center justify-center gap-1 border-t border-border bg-card px-3 pt-1.5 pb-[max(6px,env(safe-area-inset-bottom))]">
|
||||
{(
|
||||
[
|
||||
{
|
||||
view: "canvas",
|
||||
label: dict.workspace.mobileCanvas,
|
||||
icon: <Shapes />,
|
||||
},
|
||||
{
|
||||
view: "chat",
|
||||
label: dict.workspace.mobileChat,
|
||||
icon: <MessageSquare />,
|
||||
},
|
||||
] as const
|
||||
).map((item) => (
|
||||
<button
|
||||
key={item.view}
|
||||
type="button"
|
||||
onClick={() => setMobileView(item.view)}
|
||||
aria-pressed={mobileView === item.view}
|
||||
className={cn(
|
||||
"flex h-10 flex-1 items-center justify-center gap-2 rounded-xl text-[13px] text-muted-foreground [&_svg]:size-4",
|
||||
mobileView === item.view &&
|
||||
"bg-accent font-medium text-foreground",
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
{item.label}
|
||||
{item.view === "chat" &&
|
||||
(isBusy || chatUnread) &&
|
||||
mobileView !== "chat" && (
|
||||
<span className="size-1.5 rounded-full bg-marker" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept={DIAGRAM_FILE_ACCEPT}
|
||||
className="hidden"
|
||||
onChange={(event) => {
|
||||
// The opened diagram hides the start screen; a file
|
||||
// that is not one leaves it
|
||||
const file = event.target.files?.[0]
|
||||
if (file) engine.openDiagramFile(file)
|
||||
event.target.value = ""
|
||||
}}
|
||||
/>
|
||||
|
||||
<SettingsDialog />
|
||||
<CompareDialog />
|
||||
<SaveDialog
|
||||
open={saveDialogOpen}
|
||||
onOpenChange={setSaveDialogOpen}
|
||||
onSave={(filename, format) =>
|
||||
saveDiagramToFile(
|
||||
filename,
|
||||
format,
|
||||
engine.langfuseSessionId,
|
||||
dict.save.savedSuccessfully,
|
||||
)
|
||||
}
|
||||
defaultFilename={exportFilename(engine.currentTitle)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+192
-86
@@ -1,36 +1,85 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
import { createContext, useCallback, useContext, useRef, useState } from "react"
|
||||
import type { DrawIoEmbedRef, EventExport } from "react-drawio"
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
import { toast } from "sonner"
|
||||
import type {
|
||||
DrawioExportEvent,
|
||||
DrawioFrameHandle,
|
||||
} from "@/components/canvas/drawio-frame"
|
||||
import type { ExportFormat } from "@/components/save-dialog"
|
||||
import { getApiEndpoint } from "@/lib/base-path"
|
||||
import { withPageDefaults } from "@/lib/drawio/drawio-config"
|
||||
import {
|
||||
canReplaceDiagram,
|
||||
commitDiagram,
|
||||
previewDiagram,
|
||||
resetPreview,
|
||||
revertPreview,
|
||||
selectPage,
|
||||
} from "@/lib/drawio/editor-bridge"
|
||||
import {
|
||||
BLANK_MXFILE,
|
||||
normalizeToMxfile,
|
||||
} from "@/packages/mcp-server/src/pages.ts"
|
||||
import { validateAndFixXml } from "@/packages/mcp-server/src/xml-validation.ts"
|
||||
import { useCanvasStore } from "@/stores/canvas-store"
|
||||
import { extractDiagramXML, isRealDiagram } from "../lib/utils"
|
||||
|
||||
/**
|
||||
* How a diagram reaches the canvas:
|
||||
* - load: replace the whole document and reset undo (sessions, new chat)
|
||||
* - preview: streaming AI output, not recorded in undo history
|
||||
* - commit: final AI result, one undo step; reported to commit listeners
|
||||
* - revert: drop the streaming preview and go back to the given diagram
|
||||
*
|
||||
* preview/commit/revert go through the draw.io editor when it is reachable
|
||||
* (same origin); otherwise they fall back to a full load.
|
||||
*/
|
||||
export type LoadMode = "load" | "preview" | "commit" | "revert"
|
||||
|
||||
/** The document without where its view was scrolled to (dx, dy) */
|
||||
function withoutView(xml: string): string {
|
||||
return xml.replace(/<mxGraphModel\b[^>]*>/g, (tag) =>
|
||||
tag.replace(/\s(?:dx|dy)="[^"]*"/g, ""),
|
||||
)
|
||||
}
|
||||
|
||||
export interface DiagramCommit {
|
||||
beforeXml: string
|
||||
afterXml: string
|
||||
toolCallId?: string
|
||||
/** The page the change was made on; null or absent: the first page */
|
||||
pageId?: string | null
|
||||
}
|
||||
|
||||
interface DiagramContextType {
|
||||
chartXML: string
|
||||
// chartXML right away, before the re-render (loadDiagram sets both)
|
||||
chartXMLRef: React.MutableRefObject<string>
|
||||
latestSvg: string
|
||||
diagramHistory: { svg: string; xml: string }[]
|
||||
setDiagramHistory: (history: { svg: string; xml: string }[]) => void
|
||||
loadDiagram: (chart: string, skipValidation?: boolean) => string | null
|
||||
// Both return the export's tag (empty when draw.io is not there yet)
|
||||
loadDiagram: (
|
||||
chart: string,
|
||||
skipValidation?: boolean,
|
||||
mode?: LoadMode,
|
||||
meta?: { toolCallId?: string; pageId?: string | null },
|
||||
) => string | null
|
||||
// Returns the export's tag (empty when draw.io is not there yet)
|
||||
handleExport: () => string
|
||||
handleExportWithoutHistory: () => string
|
||||
// Pending exports by tag; a history or plain export's resolver gets the
|
||||
// first page's XML
|
||||
// Pending exports by tag; a plain export's resolver gets the XML of the
|
||||
// page on screen
|
||||
exportResolversRef: React.MutableRefObject<
|
||||
Record<string, (data: string, xml?: string) => void>
|
||||
>
|
||||
drawioRef: React.MutableRefObject<DrawIoEmbedRef | null>
|
||||
handleDiagramExport: (data: EventExport) => void
|
||||
drawioRef: React.MutableRefObject<DrawioFrameHandle | null>
|
||||
handleDiagramExport: (data: DrawioExportEvent) => void
|
||||
handleDiagramAutoSave: (data: { xml?: string }) => void
|
||||
clearDiagram: () => void
|
||||
saveDiagramToFile: (
|
||||
@@ -40,12 +89,17 @@ interface DiagramContextType {
|
||||
successMessage?: string,
|
||||
) => void
|
||||
getThumbnailSvg: () => Promise<string | null>
|
||||
getVersionSvg: () => Promise<string | null>
|
||||
captureValidationPng: () => Promise<string | null>
|
||||
isDrawioReady: boolean
|
||||
onDrawioLoad: () => void
|
||||
resetDrawioReady: () => void
|
||||
showSaveDialog: boolean
|
||||
setShowSaveDialog: (show: boolean) => void
|
||||
/** Register the handler told about every committed AI change */
|
||||
setCommitHandler: (
|
||||
handler: ((commit: DiagramCommit) => void) | null,
|
||||
) => void
|
||||
/** A new user turn starts: forget the streaming base */
|
||||
startTurn: () => void
|
||||
}
|
||||
|
||||
const DiagramContext = createContext<DiagramContextType | undefined>(undefined)
|
||||
@@ -54,41 +108,72 @@ const DiagramContext = createContext<DiagramContextType | undefined>(undefined)
|
||||
// echoes the request back in the export event, so each result reaches its
|
||||
// own caller. Tags end in a request number, so a late result never answers
|
||||
// a newer request.
|
||||
type ExportTag = "thumbnail" | "validation"
|
||||
type ExportTag = "thumbnail" | "validation" | "version"
|
||||
|
||||
export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
const [chartXML, setChartXML] = useState<string>("")
|
||||
const [latestSvg, setLatestSvg] = useState<string>("")
|
||||
const [diagramHistory, setDiagramHistory] = useState<
|
||||
{ svg: string; xml: string }[]
|
||||
>([])
|
||||
const [isDrawioReady, setIsDrawioReady] = useState(false)
|
||||
const [showSaveDialog, setShowSaveDialog] = useState(false)
|
||||
const hasCalledOnLoadRef = useRef(false)
|
||||
const drawioRef = useRef<DrawIoEmbedRef | null>(null)
|
||||
const mountedRef = useRef(true)
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
const drawioRef = useRef<DrawioFrameHandle | null>(null)
|
||||
// Pending exports, keyed by their export tag
|
||||
const exportResolversRef = useRef<
|
||||
Record<string, (data: string, xml?: string) => void>
|
||||
>({})
|
||||
// Pending history exports: the document each one was asked for
|
||||
const historyXmlRef = useRef(new Map<string, string>())
|
||||
const exportSeqRef = useRef(0)
|
||||
// Track latest chartXML for restoration after remount
|
||||
const chartXMLRef = useRef<string>("")
|
||||
// Diagram before the current AI change started streaming
|
||||
const turnBaseRef = useRef<string | null>(null)
|
||||
// Full loads sent that draw.io has not reported done yet
|
||||
const pendingLoadsRef = useRef(0)
|
||||
const commitHandlerRef = useRef<((commit: DiagramCommit) => void) | null>(
|
||||
null,
|
||||
)
|
||||
|
||||
// The page to show again once a full load is done: draw.io shows the
|
||||
// first page of a loaded document
|
||||
const pageAfterLoadRef = useRef<string | null>(null)
|
||||
|
||||
// Sends a full load. draw.io runs it when its message arrives, and then
|
||||
// reports "load": until then the editor shows the diagram from before,
|
||||
// so later changes go the same way and keep their order
|
||||
const fullLoad = (xml: string) => {
|
||||
if (!drawioRef.current) return
|
||||
const pageId = useCanvasStore.getState().currentPageId
|
||||
pageAfterLoadRef.current =
|
||||
pageId && xml.includes(`id="${pageId}"`) ? pageId : null
|
||||
pendingLoadsRef.current++
|
||||
drawioRef.current.load({ xml })
|
||||
}
|
||||
|
||||
const onDrawioLoad = () => {
|
||||
pendingLoadsRef.current = Math.max(0, pendingLoadsRef.current - 1)
|
||||
// Back to the page the user was on
|
||||
const pageId = pageAfterLoadRef.current
|
||||
pageAfterLoadRef.current = null
|
||||
if (pageId) selectPage(pageId)
|
||||
// Only set ready state once to prevent infinite loops
|
||||
if (hasCalledOnLoadRef.current) return
|
||||
hasCalledOnLoadRef.current = true
|
||||
setIsDrawioReady(true)
|
||||
// Restore diagram after remount (e.g., theme/UI change)
|
||||
if (drawioRef.current && isRealDiagram(chartXMLRef.current)) {
|
||||
drawioRef.current.load({ xml: chartXMLRef.current })
|
||||
}
|
||||
// draw.io's first load: loads sent before it went nowhere
|
||||
pendingLoadsRef.current = 0
|
||||
// Restore diagram after remount (e.g., theme/UI change), or a file
|
||||
// opened while draw.io loaded (its page settings count too)
|
||||
if (chartXMLRef.current) fullLoad(chartXMLRef.current)
|
||||
}
|
||||
|
||||
const resetDrawioReady = () => {
|
||||
hasCalledOnLoadRef.current = false
|
||||
pendingLoadsRef.current = 0
|
||||
setIsDrawioReady(false)
|
||||
}
|
||||
|
||||
@@ -101,20 +186,7 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
const handleExport = () => {
|
||||
if (!drawioRef.current) return ""
|
||||
// Save this export to history, with the document shown now:
|
||||
// chartXML can change before the result comes back
|
||||
const tag = `history-${++exportSeqRef.current}`
|
||||
historyXmlRef.current.set(tag, chartXMLRef.current)
|
||||
drawioRef.current.exportDiagram({
|
||||
format: "xmlsvg",
|
||||
message: tag,
|
||||
})
|
||||
return tag
|
||||
}
|
||||
|
||||
const handleExportWithoutHistory = () => {
|
||||
if (!drawioRef.current) return ""
|
||||
// Export without saving to history (for edit_diagram fetching current state)
|
||||
// Export of the current state (for the chat and edit_diagram)
|
||||
const tag = `fetch-${++exportSeqRef.current}`
|
||||
drawioRef.current.exportDiagram({
|
||||
format: "xmlsvg",
|
||||
@@ -128,7 +200,7 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
// expected occasionally.
|
||||
// (Reads refs only, so it keeps one identity)
|
||||
const requestTaggedExport = useCallback(
|
||||
(tag: ExportTag, format: "xmlsvg" | "png", timeoutMs: number) =>
|
||||
(tag: ExportTag, format: "xmlsvg" | "svg" | "png", timeoutMs: number) =>
|
||||
new Promise<string | null>((resolve) => {
|
||||
const id = `${tag}-${++exportSeqRef.current}`
|
||||
const finish = (value: string | null) => {
|
||||
@@ -162,6 +234,13 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
return null
|
||||
}, [requestTaggedExport])
|
||||
|
||||
// Plain SVG (no embedded diagram data) for version cards
|
||||
const getVersionSvg = async (): Promise<string | null> => {
|
||||
if (!drawioRef.current) return null
|
||||
const svgData = await requestTaggedExport("version", "svg", 4000)
|
||||
return svgData?.startsWith("data:image/svg") ? svgData : null
|
||||
}
|
||||
|
||||
// Capture current diagram as PNG for VLM validation
|
||||
const captureValidationPng = async (): Promise<string | null> => {
|
||||
if (!drawioRef.current) return null
|
||||
@@ -176,7 +255,12 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
const loadDiagram = (
|
||||
chart: string,
|
||||
skipValidation?: boolean,
|
||||
mode: LoadMode = "load",
|
||||
meta?: { toolCallId?: string; pageId?: string | null },
|
||||
): string | null => {
|
||||
// The editor bridge is shared: a page that is gone (another language
|
||||
// mounted a new one) must not change the new page's canvas
|
||||
if (!mountedRef.current) return null
|
||||
let xmlToLoad = chart
|
||||
|
||||
// Validate XML structure before loading (unless skipped for internal
|
||||
@@ -201,23 +285,61 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
xmlToLoad = withPageDefaults(xmlToLoad)
|
||||
|
||||
const previousXml = chartXMLRef.current
|
||||
if (mode === "preview" && turnBaseRef.current === null) {
|
||||
turnBaseRef.current = previousXml
|
||||
}
|
||||
const beforeXml = turnBaseRef.current ?? previousXml
|
||||
if (mode !== "preview") turnBaseRef.current = null
|
||||
|
||||
// Keep chartXML in sync even when diagrams are injected (e.g., display_diagram tool)
|
||||
updateChartXML(xmlToLoad)
|
||||
|
||||
if (drawioRef.current) {
|
||||
drawioRef.current.load({
|
||||
xml: xmlToLoad,
|
||||
let applied = false
|
||||
if (
|
||||
mode !== "load" &&
|
||||
pendingLoadsRef.current === 0 &&
|
||||
canReplaceDiagram(xmlToLoad)
|
||||
) {
|
||||
try {
|
||||
if (mode === "preview") previewDiagram(xmlToLoad)
|
||||
else if (mode === "commit") commitDiagram(xmlToLoad)
|
||||
else revertPreview(xmlToLoad)
|
||||
applied = true
|
||||
} catch (error) {
|
||||
console.warn("[loadDiagram] Editor update failed:", error)
|
||||
}
|
||||
}
|
||||
if (!applied) {
|
||||
// A full load replaces any preview, and its base is stale now
|
||||
resetPreview()
|
||||
fullLoad(xmlToLoad)
|
||||
}
|
||||
|
||||
if (mode === "commit") {
|
||||
commitHandlerRef.current?.({
|
||||
beforeXml,
|
||||
afterXml: xmlToLoad,
|
||||
toolCallId: meta?.toolCallId,
|
||||
pageId: meta?.pageId,
|
||||
})
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const handleDiagramExport = (data: EventExport) => {
|
||||
// Thumbnail, validation PNG and file save exports go only to their
|
||||
// own caller
|
||||
const startTurn = () => {
|
||||
turnBaseRef.current = null
|
||||
resetPreview()
|
||||
}
|
||||
|
||||
const handleDiagramExport = (data: DrawioExportEvent) => {
|
||||
// Thumbnail, version, validation PNG and file save exports go only
|
||||
// to their own caller
|
||||
const tag = data.message?.message
|
||||
if (/^(thumbnail|validation|save)-/.test(tag ?? "")) {
|
||||
if (/^(thumbnail|validation|version|save)-/.test(tag ?? "")) {
|
||||
exportResolversRef.current[tag as string]?.(data.data, data.xml)
|
||||
return
|
||||
}
|
||||
@@ -226,32 +348,14 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
// data.xml from xmlsvg exports has compressed <diagram> payloads that
|
||||
// would break edit_diagram/display_diagram. Autosave keeps chartXML
|
||||
// up to date with the full uncompressed multi-page document (#879).
|
||||
const extractedXML = extractDiagramXML(data.data)
|
||||
// The chat gets the page the user is viewing (the first one with
|
||||
// an external draw.io, which cannot tell us)
|
||||
const extractedXML = extractDiagramXML(
|
||||
data.data,
|
||||
useCanvasStore.getState().currentPageId,
|
||||
)
|
||||
setLatestSvg(data.data)
|
||||
|
||||
// Only add to history if this was a user-initiated export
|
||||
// Limit to 20 entries to prevent memory leaks during long sessions
|
||||
const MAX_HISTORY_SIZE = 20
|
||||
const askedXml =
|
||||
tag !== undefined ? historyXmlRef.current.get(tag) : undefined
|
||||
if (askedXml !== undefined) {
|
||||
historyXmlRef.current.delete(tag as string)
|
||||
// Store the full multi-page document (extractedXML is only the
|
||||
// first page), so restoring a version keeps every page
|
||||
const historyXml = askedXml || extractedXML
|
||||
setDiagramHistory((prev) => {
|
||||
const newHistory = [
|
||||
...prev,
|
||||
{
|
||||
svg: data.data,
|
||||
xml: historyXml,
|
||||
},
|
||||
]
|
||||
// Keep only the last MAX_HISTORY_SIZE entries (circular buffer)
|
||||
return newHistory.slice(-MAX_HISTORY_SIZE)
|
||||
})
|
||||
}
|
||||
|
||||
// The chat's own export (onFetchChart), not another one in flight
|
||||
const resolve =
|
||||
tag !== undefined ? exportResolversRef.current[tag] : undefined
|
||||
@@ -261,15 +365,17 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
// react-drawio registers this callback once per iframe mount, so it must
|
||||
// The frame registers this callback once per iframe mount, so it must
|
||||
// read refs: state captured in its closure would stay stale after a remount
|
||||
const handleDiagramAutoSave = (data: { xml?: string }) => {
|
||||
if (!data?.xml) return
|
||||
// Don't overwrite a pending restore - if we have a real diagram but
|
||||
// Don't overwrite a pending restore - if we have a diagram but
|
||||
// DrawIO hasn't loaded yet, it means we're waiting to restore
|
||||
if (!hasCalledOnLoadRef.current && isRealDiagram(chartXMLRef.current)) {
|
||||
return
|
||||
}
|
||||
if (!hasCalledOnLoadRef.current && chartXMLRef.current) return
|
||||
// Only the view moved, or draw.io saved what it just loaded: nothing
|
||||
// changed, and a save would put a chat that was only opened first
|
||||
// in the list
|
||||
if (withoutView(data.xml) === withoutView(chartXMLRef.current)) return
|
||||
updateChartXML(data.xml)
|
||||
}
|
||||
|
||||
@@ -278,7 +384,6 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
// Skip validation for trusted internal template (loadDiagram also sets chartXML)
|
||||
loadDiagram(emptyDiagram, true)
|
||||
setLatestSvg("")
|
||||
setDiagramHistory([])
|
||||
}
|
||||
|
||||
const saveDiagramToFile = (
|
||||
@@ -361,10 +466,7 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
// Show success toast after download is initiated
|
||||
if (successMessage) {
|
||||
toast.success(successMessage, {
|
||||
position: "bottom-left",
|
||||
duration: 2500,
|
||||
})
|
||||
toast.success(successMessage, { duration: 2500 })
|
||||
}
|
||||
|
||||
// Delay URL revocation to ensure download completes
|
||||
@@ -397,17 +499,20 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
const setCommitHandler = (
|
||||
handler: ((commit: DiagramCommit) => void) | null,
|
||||
) => {
|
||||
commitHandlerRef.current = handler
|
||||
}
|
||||
|
||||
return (
|
||||
<DiagramContext.Provider
|
||||
value={{
|
||||
chartXML,
|
||||
chartXMLRef,
|
||||
latestSvg,
|
||||
diagramHistory,
|
||||
setDiagramHistory,
|
||||
loadDiagram,
|
||||
handleExport,
|
||||
handleExportWithoutHistory,
|
||||
exportResolversRef,
|
||||
drawioRef,
|
||||
handleDiagramExport,
|
||||
@@ -415,12 +520,13 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
clearDiagram,
|
||||
saveDiagramToFile,
|
||||
getThumbnailSvg,
|
||||
getVersionSvg,
|
||||
captureValidationPng,
|
||||
isDrawioReady,
|
||||
onDrawioLoad,
|
||||
resetDrawioReady,
|
||||
showSaveDialog,
|
||||
setShowSaveDialog,
|
||||
setCommitHandler,
|
||||
startTurn,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
+4
-8
@@ -1,14 +1,11 @@
|
||||
services:
|
||||
drawio:
|
||||
image: jgraph/drawio:latest
|
||||
ports: ["8080:8080"]
|
||||
next-ai-draw-io:
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
- NEXT_PUBLIC_DRAWIO_BASE_URL=http://localhost:8080
|
||||
# Uncomment below for subdirectory deployment
|
||||
# - NEXT_PUBLIC_BASE_PATH=/nextaidrawio
|
||||
# draw.io is bundled into the image (public/drawio), no separate container needed
|
||||
# Uncomment below for subdirectory deployment
|
||||
# args:
|
||||
# - NEXT_PUBLIC_BASE_PATH=/nextaidrawio
|
||||
ports: ["3000:3000"]
|
||||
env_file: .env
|
||||
volumes:
|
||||
@@ -17,4 +14,3 @@ services:
|
||||
# environment:
|
||||
# # For subdirectory deployment, uncomment and set your path:
|
||||
# NEXT_PUBLIC_BASE_PATH: /nextaidrawio
|
||||
depends_on: [drawio]
|
||||
|
||||
+4
-2
@@ -18,9 +18,11 @@
|
||||
|
||||
**问题**: 内网环境提示"找不到 embed.diagrams.net 的服务器 IP 地址"
|
||||
|
||||
**关键点**: `NEXT_PUBLIC_*` 环境变量是**构建时**变量,会被打包到 JS 代码中,**运行时设置无效**!
|
||||
**关键点**: 应用现在自带一份 draw.io,从 `/drawio` 提供,浏览器不再需要访问 `embed.diagrams.net`。如果仍然看到这个错误,说明镜像是用 `NEXT_PUBLIC_DRAWIO_BASE_URL=https://embed.diagrams.net`(旧版 Dockerfile 的默认值)构建的,去掉这个构建参数重新构建即可。详见[离线部署](./offline-deployment.md)。
|
||||
|
||||
**解决方案**: 必须在构建时通过 `args` 传入:
|
||||
`NEXT_PUBLIC_*` 环境变量是**构建时**变量,会被打包到 JS 代码中,**运行时设置无效**!
|
||||
|
||||
**如果仍想使用单独的 draw.io 服务器**,在构建时通过 `args` 传入:
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml
|
||||
|
||||
+77
-181
@@ -1,106 +1,98 @@
|
||||
# Next AI Draw.io
|
||||
|
||||
<div align="center">
|
||||
|
||||
**AI驱动的图表创建工具 - 对话、绘制、可视化**
|
||||
# Next AI Draw.io
|
||||
|
||||
**和 AI 对话,画出并修改 draw.io 图表。**
|
||||
|
||||
[English](../../README.md) | 中文 | [日本語](../ja/README_JA.md)
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
[](https://nextjs.org/)
|
||||
[](https://react.dev/)
|
||||
[](https://github.com/sponsors/DayuanJiang)
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
[**在线体验**](https://next-ai-drawio.jiang.jp/) · [**桌面应用**](https://github.com/DayuanJiang/next-ai-draw-io/releases) · [**MCP 服务器**](#在-ai-代理里使用mcp)
|
||||
|
||||
</div>
|
||||
|
||||
一个集成了AI功能的Next.js网页应用,与draw.io图表无缝结合。通过自然语言命令和AI辅助可视化来创建、修改和增强图表。
|
||||
https://github.com/user-attachments/assets/66b9f12f-219f-4d62-acc0-0725e6850eec
|
||||
|
||||
> 注:感谢 <img src="https://raw.githubusercontent.com/DayuanJiang/next-ai-draw-io/main/public/doubao-color.png" alt="" height="20" /> [字节跳动豆包](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio) 的赞助支持,本项目的 Demo 现已接入强大的 glm-4.7 模型!
|
||||
用一句话描述想要的图,AI 就在真正的 draw.io 画布上把它画出来。你可以像编辑任何 draw.io 文件一样手动修改,也可以选中几个图形、告诉 AI 要改什么。AI 的每次修改都是一个版本,可以对比、恢复或撤销;结果可以导出为 `.drawio`、`.png` 或 `.svg`。
|
||||
|
||||
<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio" target="_blank"><img src="../../public/volcengine-invite.png" alt="火山引擎方舟 Coding Plan" width="300" /></a>
|
||||
提供网页版、Windows / macOS / Linux 桌面版,以及供 Claude Code、Cursor、VS Code 等 AI 代理调用的 MCP 服务器。
|
||||
|
||||
https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
|
||||
## 亮点
|
||||
|
||||
## 目录
|
||||
- [Next AI Draw.io](#next-ai-drawio)
|
||||
- [目录](#目录)
|
||||
- [示例](#示例)
|
||||
- [功能特性](#功能特性)
|
||||
- [MCP服务器](#mcp服务器)
|
||||
- [Claude Code CLI](#claude-code-cli)
|
||||
- [快速开始](#快速开始)
|
||||
- [在线试用](#在线试用)
|
||||
- [桌面应用](#桌面应用)
|
||||
- [使用Docker运行](#使用docker运行)
|
||||
- [安装](#安装)
|
||||
- [部署](#部署)
|
||||
- [部署到腾讯云EdgeOne Pages](#部署到腾讯云edgeone-pages)
|
||||
- [部署到Vercel](#部署到vercel)
|
||||
- [部署到Cloudflare Workers](#部署到cloudflare-workers)
|
||||
- [多提供商支持](#多提供商支持)
|
||||
- [工作原理](#工作原理)
|
||||
- [支持与联系](#支持与联系)
|
||||
- [常见问题](#常见问题)
|
||||
- [Star历史](#star历史)
|
||||
**画**
|
||||
|
||||
- 一句话生成架构图、流程图、时序图等,内置 AWS、Azure、GCP、Kubernetes 等图标库
|
||||
- 连接线可以带流动动画
|
||||
- 上传截图或手绘图,让 AI 照着画;上传 PDF、Markdown、代码等文本文件,从内容生成图
|
||||
|
||||
**改**
|
||||
|
||||
- 用对话修改:改动流式呈现,刚改过的图形在画布上高亮
|
||||
- 选中图形提问:在画布上选中几个图形,AI 只改这几个
|
||||
- 版本与撤销:每次 AI 修改都是一张带缩略图的版本卡片,可以和画布对比、恢复、撤销;画布上按 Ctrl+Z 也能一步撤回 AI 的修改
|
||||
- 它就是普通的 draw.io:双击改名、拖动、调样式、多页,随时导出 `.drawio`、`.png`、`.svg`、`.drawio.svg`
|
||||
|
||||
**用**
|
||||
|
||||
- 支持 24 家模型服务商,可以在浏览器里填自己的 API Key,Key 只保存在本地
|
||||
- 支持推理的模型会显示思考过程
|
||||
- 深色模式;界面有英文、简体中文、繁体中文、日文
|
||||
|
||||
## 示例
|
||||
|
||||
以下是一些示例提示词及其生成的图表:
|
||||
|
||||
<div align="center">
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td colspan="2" valign="top" align="center">
|
||||
<strong>动画Transformer连接器</strong><br />
|
||||
<p><strong>Prompt:</strong> Give me a **animated connector** diagram of transformer's architecture.</p>
|
||||
<img src="../../public/animated_connectors.svg" alt="带动画连接器的Transformer架构" width="480" />
|
||||
<strong>带动画连接线的 Transformer 架构</strong><br />
|
||||
<p><strong>Prompt:</strong> Give me a <strong>animated connector</strong> diagram of transformer's architecture.</p>
|
||||
<img src="../../public/animated_connectors.svg" alt="带动画连接线的 Transformer 架构" width="440" />
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<strong>RAG技术图</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate a RAG architecture diagram for **chat application**. Use connected diagram for data ingestion</p>
|
||||
<img src="../../public/rag_prod.svg" alt="RAG架构图" width="480" />
|
||||
<strong>RAG 架构图</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate a RAG architecture diagram for <strong>chat application</strong>. Use connected diagram for data ingestion</p>
|
||||
<img src="../../public/rag_prod.svg" alt="RAG 架构图" width="400" />
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<strong>React和AWS认证流程</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate authentication process using React with **AWS**. Use Serverless architecture.</p>
|
||||
<img src="../../public/auth.svg" alt="认证架构图" width="480" />
|
||||
<strong>React 加 AWS 的认证流程</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate authentication process using React with <strong>AWS</strong>. Use Serverless architecture.</p>
|
||||
<img src="../../public/auth.svg" alt="认证架构图" width="400" />
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<strong>开放式创新</strong><br />
|
||||
<strong>开放式创新模型</strong><br />
|
||||
<p><strong>Prompt:</strong> Create visualization of Henry Chesbrough's Open Innovation model.</p>
|
||||
<img src="../../public/inno.svg" alt="开放式创新图" width="480" />
|
||||
<img src="../../public/inno.svg" alt="开放式创新图" width="400" />
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<strong>猫咪素描</strong><br />
|
||||
<p><strong>Prompt:</strong> Draw a cute cat for me.</p>
|
||||
<img src="../../public/cat_demo.svg" alt="猫咪绘图" width="240" />
|
||||
<img src="../../public/cat_demo.svg" alt="猫咪绘图" width="200" />
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
## 功能特性
|
||||
## 使用方式
|
||||
|
||||
- **LLM驱动的图表创建**:利用大语言模型通过自然语言命令直接创建和操作draw.io图表
|
||||
- **基于图像的图表复制**:上传现有图表或图像,让AI自动复制和增强
|
||||
- **PDF和文本文件上传**:上传PDF文档和文本文件,提取内容并从现有文档生成图表
|
||||
- **AI推理过程显示**:查看支持模型的AI思考过程(OpenAI o1/o3、Gemini、Claude等)
|
||||
- **图表历史记录**:全面的版本控制,跟踪所有更改,允许您查看和恢复AI编辑前的图表版本
|
||||
- **交互式聊天界面**:与AI实时对话来完善您的图表
|
||||
- **云架构图支持**:专门支持生成云架构图(AWS、GCP、Azure)
|
||||
- **动画连接器**:在图表元素之间创建动态动画连接器,实现更好的可视化效果
|
||||
### 在线体验
|
||||
|
||||
## MCP服务器
|
||||
打开 [next-ai-drawio.jiang.jp](https://next-ai-drawio.jiang.jp/) 即可使用,无需安装。演示站有用量限制;点击聊天面板里的设置图标,填入自己的服务商和 API Key 就不受限制。Key 只保存在浏览器本地,不会上传到服务器。
|
||||
|
||||
通过MCP(模型上下文协议)在Claude Desktop、Cursor和VS Code等AI代理中使用Next AI Draw.io。
|
||||
### 桌面应用
|
||||
|
||||
在 [Releases 页面](https://github.com/DayuanJiang/next-ai-draw-io/releases) 下载 Windows、macOS 或 Linux 安装包。
|
||||
|
||||
### 在 AI 代理里使用(MCP)
|
||||
|
||||
通过 MCP(Model Context Protocol,让 AI 代理调用外部工具的协议),Claude Desktop、Cursor、VS Code 等都能直接画 draw.io 图。在客户端的 MCP 配置里加上:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -113,157 +105,61 @@ https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
|
||||
}
|
||||
```
|
||||
|
||||
### Claude Code CLI
|
||||
Claude Code 用一行命令:
|
||||
|
||||
```bash
|
||||
claude mcp add drawio -- npx @next-ai-drawio/mcp-server@latest
|
||||
```
|
||||
|
||||
然后让Claude创建图表:
|
||||
> "创建一个展示用户认证流程的流程图,包含登录、MFA和会话管理"
|
||||
然后对 AI 说"画一个用户认证流程图,包含登录、MFA 和会话管理",图会实时出现在浏览器里。MCP 服务器包含网页版的大部分画图能力:
|
||||
|
||||
图表会实时显示在浏览器中!
|
||||
- 同一套画图规则和图标库(AWS、Azure、GCP、Kubernetes 等)
|
||||
- 截图工具,AI 可以看一眼画好的图并自行修正
|
||||
- 版本历史、多页图表,下载为 `.drawio`、`.png`、`.svg` 或 `.drawio.svg`
|
||||
- 自动保存到 `~/.next-ai-drawio/`,重启后接着画
|
||||
|
||||
MCP服务器包含网页版的大部分画图功能:
|
||||
VS Code、Cursor 等客户端的配置见 [MCP 服务器 README](../../packages/mcp-server/README.md)。
|
||||
|
||||
- 与网页版相同的画图规则和形状库(AWS、Azure、GCP、Kubernetes等)
|
||||
- 截图工具,AI可以查看画好的图并自行修正
|
||||
- 版本历史、多页图表,以及下载为`.drawio`、`.png`、`.svg`或`.drawio.svg`格式
|
||||
- 自动保存到`~/.next-ai-drawio/`,重启后可以接着画
|
||||
## 自己部署
|
||||
|
||||
详情请参阅[MCP服务器README](../../packages/mcp-server/README.md),了解VS Code、Cursor等客户端配置。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 在线试用
|
||||
|
||||
无需安装!直接在我们的演示站点试用:
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
> **使用自己的 API Key**:您可以使用自己的 API Key 来绕过演示站点的用量限制。点击聊天面板中的设置图标即可配置您的 Provider 和 API Key。您的 Key 仅保存在浏览器本地,不会被存储在服务器上。
|
||||
|
||||
### 桌面应用
|
||||
|
||||
从 [Releases 页面](https://github.com/DayuanJiang/next-ai-draw-io/releases) 下载适用于您平台的原生桌面应用:
|
||||
|
||||
支持的平台:Windows、macOS、Linux。
|
||||
|
||||
### 使用Docker运行
|
||||
|
||||
[查看 Docker 指南](./docker.md)
|
||||
|
||||
### 安装
|
||||
|
||||
1. 克隆仓库:
|
||||
### 本地运行
|
||||
|
||||
```bash
|
||||
git clone https://github.com/DayuanJiang/next-ai-draw-io
|
||||
cd next-ai-draw-io
|
||||
npm install
|
||||
cp env.example .env.local
|
||||
```
|
||||
|
||||
详细设置说明请参阅[提供商配置指南](./ai-providers.md)。
|
||||
|
||||
2. 运行开发服务器:
|
||||
|
||||
```bash
|
||||
cp env.example .env.local # 填入服务商和 API Key,见下文"模型与服务商"
|
||||
npm run dev
|
||||
```
|
||||
|
||||
3. 在浏览器中打开 [http://localhost:6002](http://localhost:6002) 查看应用。
|
||||
打开 [http://localhost:6002](http://localhost:6002)。
|
||||
|
||||
## 部署
|
||||
### 一键部署
|
||||
|
||||
### 部署到腾讯云EdgeOne Pages
|
||||
| 平台 | 方式 |
|
||||
| --- | --- |
|
||||
| 腾讯云 EdgeOne Pages | [](https://console.cloud.tencent.com/edgeone/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io) 部署后还能获得[每日免费的 DeepSeek 模型额度](https://edgeone.cloud.tencent.com/pages/document/169925463311781888) |
|
||||
| Vercel | [](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io) 记得在 Vercel 控制台里设置和 `.env.local` 相同的环境变量 |
|
||||
| Cloudflare Workers | [Cloudflare 部署指南](./cloudflare-deploy.md) |
|
||||
| Docker | [Docker 指南](./docker.md) |
|
||||
| 离线或内网 | [离线部署说明](./offline-deployment.md) |
|
||||
|
||||
您可以通过[腾讯云EdgeOne Pages](https://pages.edgeone.ai/zh)一键部署。
|
||||
### 模型与服务商
|
||||
|
||||
直接点击此按钮一键部署:
|
||||
[](https://console.cloud.tencent.com/edgeone/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
支持 AWS Bedrock(默认)、OpenAI、Anthropic、Google AI、Google Vertex AI、Azure OpenAI、Ollama、OpenRouter、AIHubMix、DeepSeek、SiliconFlow、SGLang、Vercel AI Gateway、腾讯云 EdgeOne、字节跳动豆包、ModelScope、智谱 GLM、通义千问、七牛云、Kimi、MiniMax、Novita、小米 MiMo、Atlas Cloud 共 24 家。各家的环境变量和注意事项见[服务商配置指南](./ai-providers.md)。
|
||||
|
||||
查看[腾讯云EdgeOne Pages文档](https://pages.edgeone.ai/zh/document/product-introduction)了解更多详情。
|
||||
**选哪个模型**:这项任务要生成格式严格的长文本(draw.io XML),请选能力较强的模型,小模型容易画出错误的图。
|
||||
|
||||
同时,通过腾讯云EdgeOne Pages部署,也会获得[每日免费的DeepSeek模型额度](https://edgeone.cloud.tencent.com/pages/document/169925463311781888)。
|
||||
**多模型与管理面板**:在 `AI_MODEL` 里用逗号列出多个模型 ID,或用 `AI_MODELS_CONFIG` 环境变量 / `ai-models.json` 文件配置多家服务商的模型,所有用户无需自带 Key 即可使用。设置 `ADMIN_PASSWORD` 后访问 `/admin`,可以在网页里管理模型、访问码、功能开关、可观测性和配额,见[管理面板指南](./admin-panel.md)。
|
||||
|
||||
### 部署到Vercel
|
||||
## 支持
|
||||
|
||||
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
- 问题和建议:提交 [GitHub Issue](https://github.com/DayuanJiang/next-ai-draw-io/issues),或发邮件到 me[at]jiang.jp
|
||||
- 常见问题:[FAQ](./FAQ.md)
|
||||
- 如果这个项目对你有用,欢迎[赞助](https://github.com/sponsors/DayuanJiang),帮助我维持演示站点的运行
|
||||
|
||||
部署Next.js应用最简单的方式是使用Next.js创建者提供的[Vercel平台](https://vercel.com/new)。请确保在Vercel控制台中**设置环境变量**,就像您在本地 `.env.local` 文件中所做的那样。
|
||||
|
||||
查看[Next.js部署文档](https://nextjs.org/docs/app/building-your-application/deploying)了解更多详情。
|
||||
|
||||
### 部署到Cloudflare Workers
|
||||
|
||||
[查看 Cloudflare 部署指南](./cloudflare-deploy.md)
|
||||
|
||||
|
||||
## 多提供商支持
|
||||
|
||||
- [字节跳动豆包](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio)
|
||||
- AWS Bedrock(默认)
|
||||
- OpenAI
|
||||
- Anthropic
|
||||
- Google AI
|
||||
- Google Vertex AI
|
||||
- Azure OpenAI
|
||||
- Ollama
|
||||
- OpenRouter
|
||||
- AIHubMix
|
||||
- DeepSeek
|
||||
- SiliconFlow
|
||||
- ModelScope
|
||||
- SGLang
|
||||
- Vercel AI Gateway
|
||||
|
||||
除AWS Bedrock和OpenRouter外,所有提供商都支持自定义端点。
|
||||
|
||||
📖 **[详细的提供商配置指南](./ai-providers.md)** - 查看各提供商的设置说明。
|
||||
|
||||
### 服务端多模型配置
|
||||
|
||||
管理员可以配置多个服务端模型,让所有用户无需提供个人 API Key 即可使用。通过 `AI_MODELS_CONFIG` 环境变量(JSON 字符串)或 `ai-models.json` 文件配置。如果只需要单 provider 下的多个模型,也可以直接在 `AI_MODEL` 中用逗号分隔模型 ID。
|
||||
|
||||
**模型要求**:此任务需要强大的模型能力,因为它涉及生成具有严格格式约束的长文本(draw.io XML)。推荐使用 Claude Sonnet 4.5、GPT-5.1、Gemini 3 Pro 和 DeepSeek V3.2/R1。
|
||||
|
||||
注意:`claude` 系列已在带有 AWS、Azure、GCP 等云架构 Logo 的 draw.io 图表上进行训练,因此如果您想创建云架构图,这是最佳选择。
|
||||
|
||||
### 管理面板
|
||||
|
||||
设置 `ADMIN_PASSWORD` 环境变量并访问 `/admin`,即可在 Web 面板中管理服务端设置(模型、访问码、功能开关、可观测性、配额),无需手动编辑 `.env`。
|
||||
|
||||
📖 **[管理面板指南](./admin-panel.md)** — 启用方法、优先级规则和注意事项。
|
||||
|
||||
|
||||
## 工作原理
|
||||
|
||||
本应用使用以下技术:
|
||||
|
||||
- **Next.js**:用于前端框架和路由
|
||||
- **Vercel AI SDK**(`ai` + `@ai-sdk/*`):用于流式AI响应和多提供商支持
|
||||
- **react-drawio**:用于图表表示和操作
|
||||
|
||||
图表以XML格式表示,可在draw.io中渲染。AI处理您的命令并相应地生成或修改此XML。
|
||||
|
||||
|
||||
## 支持与联系
|
||||
|
||||
**特别感谢[字节跳动豆包](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio)赞助演示站点的 API Token 使用!** 注册火山引擎 ARK 平台即可获得50万免费Token!
|
||||
|
||||
如果您觉得这个项目有用,请考虑[赞助](https://github.com/sponsors/DayuanJiang)来帮助我托管在线演示站点!
|
||||
|
||||
如需支持或咨询,请在GitHub仓库上提交issue或联系维护者:
|
||||
|
||||
- 邮箱:me[at]jiang.jp
|
||||
|
||||
## 常见问题
|
||||
|
||||
请参阅 [FAQ](./FAQ.md) 了解常见问题和解决方案。
|
||||
|
||||
## Star历史
|
||||
<div align="center">
|
||||
|
||||
[](https://www.star-history.com/#DayuanJiang/next-ai-draw-io&type=date&legend=top-left)
|
||||
|
||||
---
|
||||
</div>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
## 可配置内容
|
||||
|
||||
1. **Models(模型)** — 添加提供商及其 API Key 和模型列表,交互与应用内的模型设置相同。保存后这些模型成为所有用户可用的服务端模型,并在请求时与环境中的 `AI_MODELS_CONFIG` / `ai-models.json` 合并(面板不会修改这些环境文件)。
|
||||
1. **Models(模型)** — 添加提供商及其 API Key 和模型列表,凭据输入框与应用内的模型设置相同。保存后这些模型成为所有用户可用的服务端模型,并在请求时与环境中的 `AI_MODELS_CONFIG` / `ai-models.json` 合并(面板不会修改这些环境文件)。
|
||||
2. **其余区块** — 访问码、生成参数、功能开关、可观测性和配额。保存的设置会写入 `data/settings.json` 并立即生效,无需重启(少数设置如 Langfuse 和 DynamoDB 标记为"需要重启")。
|
||||
|
||||
## 优先级
|
||||
|
||||
@@ -13,8 +13,6 @@
|
||||
|
||||
### 豆包 (字节跳动火山引擎)
|
||||
|
||||
> **免费 Token**:在 [火山引擎 ARK 平台](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio) 注册,即可获得所有模型 50 万免费 Token!
|
||||
|
||||
```bash
|
||||
DOUBAO_API_KEY=your_api_key
|
||||
AI_MODEL=doubao-seed-1-8-251215 # 或其他豆包模型
|
||||
@@ -46,6 +44,8 @@ AI_MODEL=gpt-4o
|
||||
OPENAI_BASE_URL=https://your-custom-endpoint/v1
|
||||
```
|
||||
|
||||
LM Studio 等本地 OpenAI 兼容服务也用同样的方式:把 base URL 设为 `http://localhost:1234/v1`(LM Studio 的默认端口),API 密钥填任意非空值即可,例如 `lm-studio`。在上面的环境变量或模型设置里配置都可以。
|
||||
|
||||
### AIHubMix
|
||||
|
||||
AIHubMix 通过单个 API Key 聚合 Claude、GPT、Gemini、DeepSeek 等模型。
|
||||
|
||||
@@ -1,13 +1,29 @@
|
||||
# 离线部署
|
||||
|
||||
通过自托管 draw.io 来替代 `embed.diagrams.net`,从而离线部署 Next AI Draw.io。
|
||||
|
||||
**注意:** `NEXT_PUBLIC_DRAWIO_BASE_URL` 是一个**构建时**变量。修改它需要重新构建 Docker 镜像。
|
||||
Next AI Draw.io 自带一份 draw.io。`npm run build`(包括 Docker 构建)会把 draw.io 的发布包下载到 `public/drawio`,只下载一次,应用从 `/drawio` 提供它。使用时浏览器不会访问 `embed.diagrams.net`,所以只要构建时能联网,应用就能在离线网络或内网里使用。
|
||||
|
||||
## Docker Compose 设置
|
||||
|
||||
1. 克隆仓库并在 `.env` 文件中定义 API 密钥。
|
||||
2. 创建 `docker-compose.yml`:
|
||||
2. 运行 `docker compose up -d`(使用仓库里的 `docker-compose.yml`)。
|
||||
3. 打开 `http://localhost:3000`。
|
||||
|
||||
不需要单独的 draw.io 容器。
|
||||
|
||||
## 构建机器不能联网时
|
||||
|
||||
构建会从 [draw.io 发布页](https://github.com/jgraph/drawio/releases) 下载 `draw.war`(约 50 MB)。如果构建机器访问不了 GitHub:
|
||||
|
||||
- 在另一台机器上下载 `scripts/fetch-drawio.mjs` 里写明的那个版本的 `draw.war`,解压到 `public/drawio`(删掉 `WEB-INF` 和 `META-INF`),再把版本号(例如 `v32.0.2`)写进 `public/drawio/.version`。构建时就会使用这份副本。
|
||||
- 或者在能联网的机器上构建镜像,再拷到离线网络里。
|
||||
|
||||
## 来自其他网站的图片
|
||||
|
||||
自带的 draw.io 只有静态文件,没有 draw.io 的图片代理(`/drawio/proxy`)。用网址插入的其他网站的图片能在画布上显示,但导出的 PNG、SVG 和版本缩略图里不会有它,因为 draw.io 要通过这个代理去取这类图片。这类图片请改用文件插入,draw.io 会把它保存在图里。
|
||||
|
||||
## 使用单独的 draw.io 服务器(可选)
|
||||
|
||||
仍然可以用构建时变量 `NEXT_PUBLIC_DRAWIO_BASE_URL` 让应用使用别处的 draw.io,比如 `jgraph/drawio` 镜像:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
@@ -24,9 +40,7 @@ services:
|
||||
depends_on: [drawio]
|
||||
```
|
||||
|
||||
3. 运行 `docker compose up -d` 并打开 `http://localhost:3000`。
|
||||
|
||||
## 配置与重要警告
|
||||
使用外部 draw.io 时,应用改用 draw.io 自己的工具栏,以下功能不可用:标出 AI 改了哪些图形、针对选中的图形提问、应用自己的画布工具栏、用 Ctrl+Z 撤回 AI 的修改。浏览器不允许页面控制来自其他域名的编辑器。
|
||||
|
||||
**`NEXT_PUBLIC_DRAWIO_BASE_URL` 必须是用户浏览器可访问的地址。**
|
||||
|
||||
|
||||
+4
-2
@@ -18,9 +18,11 @@
|
||||
|
||||
**Problem**: Intranet environment shows "Cannot find server IP address for embed.diagrams.net"
|
||||
|
||||
**Key Point**: `NEXT_PUBLIC_*` environment variables are **build-time** variables, they get bundled into JS code. **Runtime settings don't work!**
|
||||
**Key Point**: The app now ships with its own copy of draw.io, served from `/drawio`, so the browser no longer needs `embed.diagrams.net`. If you still see this error, the image was built with `NEXT_PUBLIC_DRAWIO_BASE_URL=https://embed.diagrams.net` (the old Dockerfile default). Rebuild without that build argument. See [Offline Deployment](./offline-deployment.md).
|
||||
|
||||
**Solution**: Must pass via `args` at build time:
|
||||
`NEXT_PUBLIC_*` environment variables are **build-time** variables, they get bundled into JS code. **Runtime settings don't work!**
|
||||
|
||||
**To keep a separate draw.io server instead**, pass it via `args` at build time:
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml
|
||||
|
||||
@@ -9,7 +9,7 @@ Instead of hand-editing `.env`, you can manage server settings in a web admin pa
|
||||
|
||||
## What you can configure
|
||||
|
||||
1. **Models** — add providers with their API keys and model lists, using the same UI as the in-app model settings. Saved models become server-side models available to all users, merged with any `AI_MODELS_CONFIG` / `ai-models.json` from your environment at request time (the panel does not modify those env files).
|
||||
1. **Models** — add providers with their API keys and model lists; the credential fields are the same as in the in-app model settings. Saved models become server-side models available to all users, merged with any `AI_MODELS_CONFIG` / `ai-models.json` from your environment at request time (the panel does not modify those env files).
|
||||
2. **Other sections** — access codes, generation parameters, features, observability, and quota. Saved settings are written to `data/settings.json` and apply immediately — no restart needed (a few settings such as Langfuse and DynamoDB are marked "Restart Required").
|
||||
|
||||
## Precedence
|
||||
|
||||
@@ -13,8 +13,6 @@ This guide explains how to configure different AI model providers for next-ai-dr
|
||||
|
||||
### Doubao (ByteDance Volcengine)
|
||||
|
||||
> **Free tokens**: Register on the [Volcengine ARK platform](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio) to get 500K free tokens for all models!
|
||||
|
||||
```bash
|
||||
DOUBAO_API_KEY=your_api_key
|
||||
AI_MODEL=doubao-seed-1-8-251215 # or other Doubao model
|
||||
@@ -61,6 +59,8 @@ Optional custom endpoint (for OpenAI-compatible services):
|
||||
OPENAI_BASE_URL=https://your-custom-endpoint/v1
|
||||
```
|
||||
|
||||
LM Studio and other local OpenAI-compatible servers work the same way: set the base URL to `http://localhost:1234/v1` (LM Studio's default port) and use any non-empty API key, such as `lm-studio`. This works both in the environment variables above and in the model settings.
|
||||
|
||||
### AIHubMix
|
||||
|
||||
AIHubMix provides access to Claude, GPT, Gemini, DeepSeek, and other models through a single API key.
|
||||
|
||||
@@ -1,13 +1,29 @@
|
||||
# Offline Deployment
|
||||
|
||||
Deploy Next AI Draw.io offline by self-hosting draw.io to replace `embed.diagrams.net`.
|
||||
|
||||
**Note:** `NEXT_PUBLIC_DRAWIO_BASE_URL` is a **build-time** variable. Changing it requires rebuilding the Docker image.
|
||||
Next AI Draw.io ships with its own copy of draw.io. `npm run build` (and the Docker build) downloads the draw.io release into `public/drawio` once, and the app serves it from `/drawio`. In use, the browser never contacts `embed.diagrams.net`, so the app works on an offline or intranet network as long as the build had internet access.
|
||||
|
||||
## Docker Compose Setup
|
||||
|
||||
1. Clone the repository and define API keys in `.env`.
|
||||
2. Create `docker-compose.yml`:
|
||||
2. Run `docker compose up -d` (it uses the `docker-compose.yml` in the repository).
|
||||
3. Open `http://localhost:3000`.
|
||||
|
||||
No separate draw.io container is needed.
|
||||
|
||||
## Building Without Internet Access
|
||||
|
||||
The build downloads `draw.war` (about 50 MB) from the [draw.io releases](https://github.com/jgraph/drawio/releases). If the build machine cannot reach GitHub:
|
||||
|
||||
- On another machine, download `draw.war` for the version in `scripts/fetch-drawio.mjs`, unzip it into `public/drawio` (delete `WEB-INF` and `META-INF`), and write the version, for example `v32.0.2`, into `public/drawio/.version`. The build then uses this copy.
|
||||
- Or build the image on a machine with internet access and transfer it to the offline network.
|
||||
|
||||
## Images From Other Websites
|
||||
|
||||
The bundled draw.io is static files only, without draw.io's image proxy (`/drawio/proxy`). An image inserted by its web address from another site shows on the canvas, but exports (PNG, SVG) and version thumbnails leave it out, because draw.io fetches such images through that proxy. Insert these images from a file instead: draw.io then stores them inside the diagram.
|
||||
|
||||
## Using a Separate draw.io Server (Optional)
|
||||
|
||||
You can still point the app at another draw.io, such as the `jgraph/drawio` image, with the build-time variable `NEXT_PUBLIC_DRAWIO_BASE_URL`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
@@ -24,9 +40,7 @@ services:
|
||||
depends_on: [drawio]
|
||||
```
|
||||
|
||||
3. Run `docker compose up -d` and open `http://localhost:3000`.
|
||||
|
||||
## Configuration & Critical Warning
|
||||
With an external draw.io the app uses draw.io's own toolbar, and these features are off: highlighting what the AI changed, asking about selected shapes, the app's canvas toolbar, and undoing AI changes with Ctrl+Z. Browsers do not let a page control an editor served from a different origin.
|
||||
|
||||
**The `NEXT_PUBLIC_DRAWIO_BASE_URL` must be accessible from the user's browser.**
|
||||
|
||||
|
||||
+4
-2
@@ -18,9 +18,11 @@
|
||||
|
||||
**問題**: イントラネット環境で「embed.diagrams.netのサーバーIPアドレスが見つかりません」と表示される
|
||||
|
||||
**重要**: `NEXT_PUBLIC_*` 環境変数は**ビルド時**変数であり、JSコードにバンドルされます。**実行時の設定は無効です!**
|
||||
**重要**: アプリには draw.io のコピーが同梱され、`/drawio` から配信されるため、ブラウザは `embed.diagrams.net` にアクセスしなくなりました。それでもこのエラーが出る場合は、イメージが `NEXT_PUBLIC_DRAWIO_BASE_URL=https://embed.diagrams.net`(以前の Dockerfile の既定値)でビルドされています。このビルド引数を外して再ビルドしてください。詳しくは[オフラインデプロイ](./offline-deployment.md)を参照してください。
|
||||
|
||||
**解決策**: ビルド時に `args` で渡す必要があります:
|
||||
`NEXT_PUBLIC_*` 環境変数は**ビルド時**変数であり、JSコードにバンドルされます。**実行時の設定は無効です!**
|
||||
|
||||
**別の draw.io サーバーを使い続ける場合**は、ビルド時に `args` で渡します:
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml
|
||||
|
||||
+78
-181
@@ -1,104 +1,98 @@
|
||||
# Next AI Draw.io
|
||||
|
||||
<div align="center">
|
||||
|
||||
**AI搭載のダイアグラム作成ツール - チャット、描画、可視化**
|
||||
# Next AI Draw.io
|
||||
|
||||
**AI とチャットしながら draw.io のダイアグラムを描き、直す。**
|
||||
|
||||
[English](../../README.md) | [中文](../cn/README_CN.md) | 日本語
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
[](https://nextjs.org/)
|
||||
[](https://react.dev/)
|
||||
[](https://github.com/sponsors/DayuanJiang)
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
[**オンラインデモ**](https://next-ai-drawio.jiang.jp/) · [**デスクトップアプリ**](https://github.com/DayuanJiang/next-ai-draw-io/releases) · [**MCP サーバー**](#ai-エージェントから使うmcp)
|
||||
|
||||
</div>
|
||||
|
||||
AI機能とdraw.ioダイアグラムを統合したNext.jsウェブアプリケーションです。自然言語コマンドとAI支援の可視化により、ダイアグラムを作成、修正、強化できます。
|
||||
https://github.com/user-attachments/assets/66b9f12f-219f-4d62-acc0-0725e6850eec
|
||||
|
||||
> 注:<img src="https://raw.githubusercontent.com/DayuanJiang/next-ai-draw-io/main/public/doubao-color.png" alt="" height="20" /> [ByteDance Doubao](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio) のご支援により、デモサイトに強力な glm-4.7 モデルを導入しました!
|
||||
欲しいダイアグラムを一文で伝えると、AI が本物の draw.io キャンバスに描きます。普通の draw.io ファイルと同じように手で直すことも、図形をいくつか選んで AI に変更を頼むこともできます。AI の変更はすべてバージョンとして残り、比較・復元・取り消しができます。結果は `.drawio`、`.png`、`.svg` で書き出せます。
|
||||
|
||||
https://github.com/user-attachments/assets/b2eef5f3-b335-4e71-a755-dc2e80931979
|
||||
Web アプリ、Windows / macOS / Linux 向けデスクトップアプリ、そして Claude Code、Cursor、VS Code などの AI エージェントから呼び出せる MCP サーバーとして使えます。
|
||||
|
||||
## 目次
|
||||
- [Next AI Draw.io](#next-ai-drawio)
|
||||
- [目次](#目次)
|
||||
- [例](#例)
|
||||
- [機能](#機能)
|
||||
- [MCPサーバー](#mcpサーバー)
|
||||
- [Claude Code CLI](#claude-code-cli)
|
||||
- [はじめに](#はじめに)
|
||||
- [オンラインで試す](#オンラインで試す)
|
||||
- [デスクトップアプリケーション](#デスクトップアプリケーション)
|
||||
- [Dockerで実行](#dockerで実行)
|
||||
- [インストール](#インストール)
|
||||
- [デプロイ](#デプロイ)
|
||||
- [EdgeOne Pagesへのデプロイ](#edgeone-pagesへのデプロイ)
|
||||
- [Vercelへのデプロイ](#vercelへのデプロイ)
|
||||
- [Cloudflare Workersへのデプロイ](#cloudflare-workersへのデプロイ)
|
||||
- [マルチプロバイダーサポート](#マルチプロバイダーサポート)
|
||||
- [仕組み](#仕組み)
|
||||
- [サポート&お問い合わせ](#サポートお問い合わせ)
|
||||
- [よくある質問](#よくある質問)
|
||||
- [スター履歴](#スター履歴)
|
||||
## 特長
|
||||
|
||||
**描く**
|
||||
|
||||
- アーキテクチャ図、フローチャート、シーケンス図などを一文から生成。AWS、Azure、GCP、Kubernetes のアイコンライブラリを内蔵
|
||||
- コネクタに流れるアニメーションを付けられる
|
||||
- スクリーンショットや手描きの図をアップロードすると AI が描き直す。PDF、Markdown、コードなどのテキストファイルからも内容を図にできる
|
||||
|
||||
**直す**
|
||||
|
||||
- チャットで修正:変更はストリーミングでキャンバスに反映され、AI が変更した図形はハイライト表示
|
||||
- 選択して頼む:キャンバスで図形を選ぶと、AI はその図形だけを変更
|
||||
- バージョンと取り消し:AI の変更ごとにサムネイル付きのバージョンカードが残り、キャンバスと比較・復元・取り消しができる。キャンバス上の Ctrl+Z でも AI の変更を一度で戻せる
|
||||
- ただの draw.io ダイアグラム:ダブルクリックで名前を変え、ドラッグし、スタイルを変え、複数ページを使い、いつでも `.drawio`、`.png`、`.svg`、`.drawio.svg` に書き出せる
|
||||
|
||||
**使う**
|
||||
|
||||
- 24 のモデルプロバイダーに対応。自分の API キーをブラウザに入力でき、キーは端末内にだけ保存される
|
||||
- 推論するモデルは思考過程を表示
|
||||
- ダークモード。UI は英語、簡体字中国語、繁体字中国語、日本語に対応
|
||||
|
||||
## 例
|
||||
|
||||
以下はいくつかのプロンプト例と生成されたダイアグラムです:
|
||||
|
||||
<div align="center">
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td colspan="2" valign="top" align="center">
|
||||
<strong>アニメーションTransformerコネクタ</strong><br />
|
||||
<p><strong>Prompt:</strong> Give me a **animated connector** diagram of transformer's architecture.</p>
|
||||
<img src="../../public/animated_connectors.svg" alt="アニメーションコネクタ付きTransformerアーキテクチャ" width="480" />
|
||||
<strong>アニメーションコネクタ付き Transformer アーキテクチャ</strong><br />
|
||||
<p><strong>Prompt:</strong> Give me a <strong>animated connector</strong> diagram of transformer's architecture.</p>
|
||||
<img src="../../public/animated_connectors.svg" alt="アニメーションコネクタ付き Transformer アーキテクチャ" width="440" />
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<strong>RAG技術ダイアグラム</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate a RAG architecture diagram for **chat application**. Use connected diagram for data ingestion</p>
|
||||
<img src="../../public/rag_prod.svg" alt="RAGアーキテクチャ図" width="480" />
|
||||
<strong>RAG アーキテクチャ</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate a RAG architecture diagram for <strong>chat application</strong>. Use connected diagram for data ingestion</p>
|
||||
<img src="../../public/rag_prod.svg" alt="RAG アーキテクチャ図" width="400" />
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<strong>ReactとAWSによる認証</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate authentication process using React with **AWS**. Use Serverless architecture.</p>
|
||||
<img src="../../public/auth.svg" alt="認証アーキテクチャ図" width="480" />
|
||||
<strong>React と AWS による認証フロー</strong><br />
|
||||
<p><strong>Prompt:</strong> Generate authentication process using React with <strong>AWS</strong>. Use Serverless architecture.</p>
|
||||
<img src="../../public/auth.svg" alt="認証アーキテクチャ図" width="400" />
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<strong>オープンイノベーション</strong><br />
|
||||
<strong>オープンイノベーションモデル</strong><br />
|
||||
<p><strong>Prompt:</strong> Create visualization of Henry Chesbrough's Open Innovation model.</p>
|
||||
<img src="../../public/inno.svg" alt="オープンイノベーション図" width="480" />
|
||||
<img src="../../public/inno.svg" alt="オープンイノベーション図" width="400" />
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<strong>猫のスケッチ</strong><br />
|
||||
<p><strong>Prompt:</strong> Draw a cute cat for me.</p>
|
||||
<img src="../../public/cat_demo.svg" alt="猫の絵" width="240" />
|
||||
<img src="../../public/cat_demo.svg" alt="猫の絵" width="200" />
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
## 機能
|
||||
## 使い方
|
||||
|
||||
- **LLM搭載のダイアグラム作成**:大規模言語モデルを活用して、自然言語コマンドで直接draw.ioダイアグラムを作成・操作
|
||||
- **画像ベースのダイアグラム複製**:既存のダイアグラムや画像をアップロードし、AIが自動的に複製・強化
|
||||
- **PDFとテキストファイルのアップロード**:PDFドキュメントやテキストファイルをアップロードして、既存のドキュメントからコンテンツを抽出し、ダイアグラムを生成
|
||||
- **AI推論プロセス表示**:サポートされているモデル(OpenAI o1/o3、Gemini、Claudeなど)のAIの思考プロセスを表示
|
||||
- **ダイアグラム履歴**:すべての変更を追跡する包括的なバージョン管理。AI編集前のダイアグラムの以前のバージョンを表示・復元可能
|
||||
- **インタラクティブなチャットインターフェース**:AIとリアルタイムでコミュニケーションしてダイアグラムを改善
|
||||
- **クラウドアーキテクチャダイアグラムサポート**:クラウドアーキテクチャダイアグラムの生成を専門的にサポート(AWS、GCP、Azure)
|
||||
- **アニメーションコネクタ**:より良い可視化のためにダイアグラム要素間に動的でアニメーション化されたコネクタを作成
|
||||
### オンラインデモ
|
||||
|
||||
## MCPサーバー
|
||||
[next-ai-drawio.jiang.jp](https://next-ai-drawio.jiang.jp/) を開けばすぐ使えます。インストールは不要です。デモサイトには利用上限があります。チャットパネルの設定アイコンから自分のプロバイダーと API キーを入力すると上限なしで使えます。キーはブラウザ内にだけ保存され、サーバーには送られません。
|
||||
|
||||
MCP(Model Context Protocol)を介して、Claude Desktop、Cursor、VS CodeなどのAIエージェントでNext AI Draw.ioを使用できます。
|
||||
### デスクトップアプリ
|
||||
|
||||
[Releases ページ](https://github.com/DayuanJiang/next-ai-draw-io/releases) から Windows、macOS、Linux 向けのインストーラーをダウンロードしてください。
|
||||
|
||||
### AI エージェントから使う(MCP)
|
||||
|
||||
MCP(Model Context Protocol、AI エージェントが外部ツールを呼び出すためのプロトコル)を通して、Claude Desktop、Cursor、VS Code などから直接 draw.io のダイアグラムを描けます。クライアントの MCP 設定に次を追加します。
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -111,158 +105,61 @@ MCP(Model Context Protocol)を介して、Claude Desktop、Cursor、VS Code
|
||||
}
|
||||
```
|
||||
|
||||
### Claude Code CLI
|
||||
Claude Code ならコマンド一つです。
|
||||
|
||||
```bash
|
||||
claude mcp add drawio -- npx @next-ai-drawio/mcp-server@latest
|
||||
```
|
||||
|
||||
Claudeにダイアグラムの作成を依頼:
|
||||
> 「ログイン、MFA、セッション管理を含むユーザー認証のフローチャートを作成してください」
|
||||
あとは AI に「ログイン、MFA、セッション管理を含むユーザー認証のフローチャートを描いて」と頼めば、描かれていく様子がブラウザに表示されます。MCP サーバーには Web アプリの作図機能のほとんどが入っています。
|
||||
|
||||
ダイアグラムがリアルタイムでブラウザに表示されます!
|
||||
- 同じ作図ルールとアイコンライブラリ(AWS、Azure、GCP、Kubernetes など)
|
||||
- スクリーンショットツール。AI が描いた結果を確認して自分で直せる
|
||||
- バージョン履歴、複数ページのダイアグラム、`.drawio`、`.png`、`.svg`、`.drawio.svg` でのダウンロード
|
||||
- `~/.next-ai-drawio/` への自動保存。再起動後も続きから描ける
|
||||
|
||||
MCPサーバーには、Webアプリの主な作図機能が含まれています:
|
||||
VS Code、Cursor などの設定は [MCP サーバーの README](../../packages/mcp-server/README.md) を参照してください。
|
||||
|
||||
- Webアプリと同じ作図ルールとシェイプライブラリ(AWS、Azure、GCP、Kubernetesなど)
|
||||
- スクリーンショットツール:AIが描画結果を確認して修正できます
|
||||
- バージョン履歴、複数ページのダイアグラム、`.drawio`・`.png`・`.svg`・`.drawio.svg`形式でのダウンロード
|
||||
- `~/.next-ai-drawio/`への自動保存:再起動後も続きから編集できます
|
||||
## 自分でホストする
|
||||
|
||||
詳細は[MCPサーバーREADME](../../packages/mcp-server/README.md)をご覧ください(VS Code、Cursorなどのクライアント設定も含む)。
|
||||
|
||||
## はじめに
|
||||
|
||||
### オンラインで試す
|
||||
|
||||
インストール不要!デモサイトで直接お試しください:
|
||||
|
||||
[](https://next-ai-drawio.jiang.jp/)
|
||||
|
||||
> **自分のAPIキーを使用**:自分のAPIキーを使用することで、デモサイトの利用制限を回避できます。チャットパネルの設定アイコンをクリックして、プロバイダーとAPIキーを設定してください。キーはブラウザのローカルに保存され、サーバーには保存されません。
|
||||
|
||||
### デスクトップアプリケーション
|
||||
|
||||
[Releases ページ](https://github.com/DayuanJiang/next-ai-draw-io/releases)からお使いのプラットフォーム用のネイティブデスクトップアプリをダウンロードしてください:
|
||||
|
||||
対応プラットフォーム:Windows、macOS、Linux。
|
||||
|
||||
### Dockerで実行
|
||||
|
||||
[Docker ガイドを参照](./docker.md)
|
||||
|
||||
### インストール
|
||||
|
||||
1. リポジトリをクローン:
|
||||
### ローカルで動かす
|
||||
|
||||
```bash
|
||||
git clone https://github.com/DayuanJiang/next-ai-draw-io
|
||||
cd next-ai-draw-io
|
||||
npm install
|
||||
cp env.example .env.local
|
||||
```
|
||||
|
||||
詳細な設定手順については[プロバイダー設定ガイド](./ai-providers.md)を参照してください。
|
||||
|
||||
2. 開発サーバーを起動:
|
||||
|
||||
```bash
|
||||
cp env.example .env.local # プロバイダーと API キーを記入。下の「モデルとプロバイダー」を参照
|
||||
npm run dev
|
||||
```
|
||||
|
||||
3. ブラウザで[http://localhost:6002](http://localhost:6002)を開いてアプリケーションを確認。
|
||||
[http://localhost:6002](http://localhost:6002) を開きます。
|
||||
|
||||
## デプロイ
|
||||
### ワンクリックデプロイ
|
||||
|
||||
### EdgeOne Pagesへのデプロイ
|
||||
| プラットフォーム | 方法 |
|
||||
| --- | --- |
|
||||
| Tencent EdgeOne Pages | [](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io) デプロイすると [DeepSeek モデルの毎日の無料クォータ](https://pages.edgeone.ai/document/edge-ai) も付きます |
|
||||
| Vercel | [](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io) `.env.local` と同じ環境変数を Vercel のダッシュボードで設定してください |
|
||||
| Cloudflare Workers | [Cloudflare デプロイガイド](./cloudflare-deploy.md) |
|
||||
| Docker | [Docker ガイド](./docker.md) |
|
||||
| オフラインまたは社内ネットワーク | [オフラインデプロイ](./offline-deployment.md) |
|
||||
|
||||
[Tencent EdgeOne Pages](https://pages.edgeone.ai/)を使用してワンクリックでデプロイできます。
|
||||
### モデルとプロバイダー
|
||||
|
||||
このボタンでデプロイ:
|
||||
AWS Bedrock(既定)、OpenAI、Anthropic、Google AI、Google Vertex AI、Azure OpenAI、Ollama、OpenRouter、AIHubMix、DeepSeek、SiliconFlow、SGLang、Vercel AI Gateway、Tencent EdgeOne、ByteDance Doubao、ModelScope、Zhipu GLM、Qwen、Qiniu、Kimi、MiniMax、Novita、Xiaomi MiMo、Atlas Cloud の 24 プロバイダーに対応しています。各プロバイダーの環境変数と注意点は[プロバイダー設定ガイド](./ai-providers.md)にあります。
|
||||
|
||||
[](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2FDayuanJiang%2Fnext-ai-draw-io)
|
||||
**どのモデルを選ぶか**:厳密な形式の長いテキスト(draw.io の XML)を生成するタスクなので、能力の高いモデルを選んでください。小さなモデルは壊れた図を出しがちです。
|
||||
|
||||
詳細は[Tencent EdgeOne Pagesドキュメント](https://pages.edgeone.ai/document/deployment-overview)をご覧ください。
|
||||
**複数モデルと管理パネル**:`AI_MODEL` にモデル ID をカンマ区切りで並べるか、`AI_MODELS_CONFIG` 環境変数または `ai-models.json` ファイルで複数プロバイダーのモデルを設定すると、全ユーザーが自分のキーなしで使えます。`ADMIN_PASSWORD` を設定して `/admin` を開くと、モデル、アクセスコード、機能の切り替え、オブザーバビリティ、クォータを Web 画面から管理できます。[管理パネルガイド](./admin-panel.md)を参照してください。
|
||||
|
||||
また、Tencent EdgeOne Pagesでデプロイすると、[DeepSeekモデルの毎日の無料クォータ](https://pages.edgeone.ai/document/edge-ai)が付与されます。
|
||||
## サポート
|
||||
|
||||
### Vercelへのデプロイ
|
||||
- 質問や提案:[GitHub Issue](https://github.com/DayuanJiang/next-ai-draw-io/issues) を立てるか、me[at]jiang.jp までメールしてください
|
||||
- よくある問題:[FAQ](./FAQ.md)
|
||||
- このプロジェクトが役に立ったら、デモサイトの運営のために[スポンサー](https://github.com/sponsors/DayuanJiang)をご検討ください
|
||||
|
||||
[](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)をご覧ください。
|
||||
|
||||
### Cloudflare Workersへのデプロイ
|
||||
|
||||
[Cloudflare デプロイガイドを参照](./cloudflare-deploy.md)
|
||||
|
||||
|
||||
## マルチプロバイダーサポート
|
||||
|
||||
- [ByteDance Doubao](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio)
|
||||
- AWS Bedrock(デフォルト)
|
||||
- OpenAI
|
||||
- Anthropic
|
||||
- Google AI
|
||||
- Google Vertex AI
|
||||
- Azure OpenAI
|
||||
- Ollama
|
||||
- OpenRouter
|
||||
- AIHubMix
|
||||
- DeepSeek
|
||||
- SiliconFlow
|
||||
- ModelScope
|
||||
- SGLang
|
||||
- Vercel AI Gateway
|
||||
|
||||
AWS BedrockとOpenRouter以外のすべてのプロバイダーはカスタムエンドポイントをサポートしています。
|
||||
|
||||
📖 **[詳細なプロバイダー設定ガイド](./ai-providers.md)** - 各プロバイダーの設定手順をご覧ください。
|
||||
|
||||
### サーバーサイドマルチモデル設定
|
||||
|
||||
管理者は、ユーザーが個人のAPIキーを提供することなく利用できる複数のサーバーサイドモデルを設定できます。`AI_MODELS_CONFIG` 環境変数(JSON文字列)または `ai-models.json` ファイルで設定します。同一プロバイダー内の複数モデルだけが必要な場合は、`AI_MODEL` にカンマ区切りでモデルIDを列挙する簡易設定も使えます。
|
||||
|
||||
**モデル要件**:このタスクは厳密なフォーマット制約(draw.io XML)を持つ長文テキスト生成を伴うため、強力なモデル機能が必要です。Claude Sonnet 4.5、GPT-5.1、Gemini 3 Pro、DeepSeek V3.2/R1を推奨します。
|
||||
|
||||
注:`claude`シリーズはAWS、Azure、GCPなどのクラウドアーキテクチャロゴ付きのdraw.ioダイアグラムで学習されているため、クラウドアーキテクチャダイアグラムを作成したい場合は最適な選択です。
|
||||
|
||||
### 管理パネル
|
||||
|
||||
`ADMIN_PASSWORD` 環境変数を設定して `/admin` にアクセスすると、`.env` を手動で編集する代わりに Web パネルでサーバー設定(モデル、アクセスコード、機能、可観測性、クォータ)を管理できます。
|
||||
|
||||
📖 **[管理パネルガイド](./admin-panel.md)** — 有効化の方法、優先順位ルール、注意事項。
|
||||
|
||||
|
||||
## 仕組み
|
||||
|
||||
本アプリケーションは以下の技術を使用しています:
|
||||
|
||||
- **Next.js**:フロントエンドフレームワークとルーティング
|
||||
- **Vercel AI SDK**(`ai` + `@ai-sdk/*`):ストリーミングAIレスポンスとマルチプロバイダーサポート
|
||||
- **react-drawio**:ダイアグラムの表現と操作
|
||||
|
||||
ダイアグラムはdraw.ioでレンダリングできるXMLとして表現されます。AIがコマンドを処理し、それに応じてこのXMLを生成または変更します。
|
||||
|
||||
|
||||
## サポート&お問い合わせ
|
||||
|
||||
**デモサイトのAPIトークン使用を支援してくださった[ByteDance Doubao](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio)に特別な感謝を申し上げます!** ARKプラットフォームに登録すると、50万トークンが無料でもらえます!
|
||||
|
||||
このプロジェクトが役に立ったら、ライブデモサイトのホスティングを支援するために[スポンサー](https://github.com/sponsors/DayuanJiang)をご検討ください!
|
||||
|
||||
サポートやお問い合わせについては、GitHubリポジトリでissueを開くか、メンテナーにご連絡ください:
|
||||
|
||||
- メール:me[at]jiang.jp
|
||||
|
||||
## よくある質問
|
||||
|
||||
一般的な問題と解決策については [FAQ](./FAQ.md) をご覧ください。
|
||||
|
||||
## スター履歴
|
||||
<div align="center">
|
||||
|
||||
[](https://www.star-history.com/#DayuanJiang/next-ai-draw-io&type=date&legend=top-left)
|
||||
|
||||
---
|
||||
</div>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
## 設定できる項目
|
||||
|
||||
1. **Models(モデル)** — アプリ内のモデル設定と同じ UI で、プロバイダーの API キーとモデルリストを追加します。保存するとそれらは全ユーザーが利用できるサーバーサイドモデルになり、リクエスト時に環境の `AI_MODELS_CONFIG` / `ai-models.json` とマージされます(パネルがこれらの環境ファイルを変更することはありません)。
|
||||
1. **Models(モデル)** — プロバイダーの API キーとモデルリストを追加します(認証情報の入力欄はアプリ内のモデル設定と同じです)。保存するとそれらは全ユーザーが利用できるサーバーサイドモデルになり、リクエスト時に環境の `AI_MODELS_CONFIG` / `ai-models.json` とマージされます(パネルがこれらの環境ファイルを変更することはありません)。
|
||||
2. **その他のセクション** — アクセスコード、生成パラメータ、機能、可観測性、クォータ。保存された設定は `data/settings.json` に書き込まれ、即座に反映されます — 再起動は不要です(Langfuse や DynamoDB など一部の設定は「再起動が必要」と表示されます)。
|
||||
|
||||
## 優先順位
|
||||
|
||||
@@ -13,8 +13,6 @@
|
||||
|
||||
### Doubao (ByteDance Volcengine)
|
||||
|
||||
> **無料トークン**: [Volcengine ARK プラットフォーム](https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=Z9Z3LDTJ&utm_campaign=drawio&utm_content=drawio&utm_medium=devrel&utm_source=OWO&utm_term=drawio)に登録すると、すべてのモデルで使える50万トークンが無料で入手できます!
|
||||
|
||||
```bash
|
||||
DOUBAO_API_KEY=your_api_key
|
||||
AI_MODEL=doubao-seed-1-8-251215 # または他の Doubao モデル
|
||||
@@ -46,6 +44,8 @@ AI_MODEL=gpt-4o
|
||||
OPENAI_BASE_URL=https://your-custom-endpoint/v1
|
||||
```
|
||||
|
||||
LM Studio などのローカルな OpenAI 互換サーバーも同じ方法で使えます。ベース URL を `http://localhost:1234/v1`(LM Studio の既定ポート)に設定し、API キーには `lm-studio` など空でない任意の値を入力してください。上の環境変数でも、モデル設定画面でも設定できます。
|
||||
|
||||
### AIHubMix
|
||||
|
||||
AIHubMix は、単一の API キーで Claude、GPT、Gemini、DeepSeek などのモデルへのアクセスを提供します。
|
||||
|
||||
@@ -1,13 +1,29 @@
|
||||
# オフラインデプロイ
|
||||
|
||||
`embed.diagrams.net` の代わりに draw.io をセルフホストすることで、Next AI Draw.io をオフライン環境にデプロイできます。
|
||||
|
||||
**注:** `NEXT_PUBLIC_DRAWIO_BASE_URL` は**ビルド時**の変数です。これを変更する場合は、Docker イメージの再ビルドが必要です。
|
||||
Next AI Draw.io には draw.io のコピーが同梱されています。`npm run build`(Docker ビルドを含む)が draw.io のリリースを一度だけ `public/drawio` にダウンロードし、アプリは `/drawio` からそれを配信します。利用中のブラウザは `embed.diagrams.net` にアクセスしないため、ビルド時にインターネットに接続できれば、オフライン環境やイントラネットでも動作します。
|
||||
|
||||
## Docker Compose のセットアップ
|
||||
|
||||
1. リポジトリをクローンし、`.env` ファイルに API キーを定義します。
|
||||
2. `docker-compose.yml` を作成します。
|
||||
2. `docker compose up -d` を実行します(リポジトリの `docker-compose.yml` を使います)。
|
||||
3. `http://localhost:3000` を開きます。
|
||||
|
||||
draw.io 用の別コンテナは不要です。
|
||||
|
||||
## ビルド環境がインターネットに接続できない場合
|
||||
|
||||
ビルドは [draw.io のリリース](https://github.com/jgraph/drawio/releases) から `draw.war`(約 50 MB)をダウンロードします。ビルド環境から GitHub にアクセスできない場合は、次のどちらかを行ってください。
|
||||
|
||||
- 別のマシンで `scripts/fetch-drawio.mjs` に書かれたバージョンの `draw.war` をダウンロードし、`public/drawio` に展開します(`WEB-INF` と `META-INF` は削除)。さらにバージョン(例:`v32.0.2`)を `public/drawio/.version` に書き込みます。ビルドはこのコピーを使います。
|
||||
- インターネットに接続できるマシンでイメージをビルドし、オフライン環境に転送します。
|
||||
|
||||
## ほかのサイトの画像
|
||||
|
||||
同梱の draw.io は静的ファイルだけで、draw.io の画像プロキシ(`/drawio/proxy`)は含まれません。ほかのサイトの画像を URL で挿入するとキャンバスには表示されますが、エクスポートした PNG・SVG やバージョンのサムネイルには入りません。draw.io はこうした画像をこのプロキシ経由で取得するためです。こうした画像はファイルから挿入してください。draw.io が図の中に保存します。
|
||||
|
||||
## 別の draw.io サーバーを使う場合(任意)
|
||||
|
||||
ビルド時の変数 `NEXT_PUBLIC_DRAWIO_BASE_URL` で、`jgraph/drawio` イメージなど別の draw.io を使うこともできます。
|
||||
|
||||
```yaml
|
||||
services:
|
||||
@@ -24,9 +40,7 @@ services:
|
||||
depends_on: [drawio]
|
||||
```
|
||||
|
||||
3. `docker compose up -d` を実行し、`http://localhost:3000` にアクセスします。
|
||||
|
||||
## 設定と重要な警告
|
||||
外部の draw.io を使うと、アプリは draw.io 自身のツールバーを使い、次の機能は使えなくなります:AI が変更した図形の強調表示、選択した図形についての依頼、アプリのキャンバスツールバー、Ctrl+Z による AI の変更の取り消し。ブラウザは、別のオリジンから配信されたエディターをページから操作することを許可しないためです。
|
||||
|
||||
**`NEXT_PUBLIC_DRAWIO_BASE_URL` は、ユーザーのブラウザからアクセスできる必要があります。**
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
appId: com.nextaidrawio.app
|
||||
productName: Next AI Draw.io
|
||||
copyright: Copyright © 2024 Next AI Draw.io
|
||||
electronVersion: 39.2.7
|
||||
|
||||
directories:
|
||||
output: release
|
||||
|
||||
+16
-3
@@ -143,8 +143,11 @@ AI_MODEL=global.anthropic.claude-sonnet-4-5-20250929-v1:0
|
||||
# SETTINGS_FILE=./data/settings.json # Optional: custom settings file location
|
||||
|
||||
# Draw.io Configuration (Optional)
|
||||
# NEXT_PUBLIC_DRAWIO_BASE_URL=https://embed.diagrams.net # Default: https://embed.diagrams.net
|
||||
# Use this to point to a self-hosted draw.io instance
|
||||
# By default the app serves its own copy of draw.io from /drawio (downloaded into
|
||||
# public/drawio by `npm run dev` / `npm run build`). Same origin is required for
|
||||
# highlighting AI changes, asking about selected shapes and the custom toolbar.
|
||||
# NEXT_PUBLIC_DRAWIO_BASE_URL=https://embed.diagrams.net # Optional: use an external draw.io instead
|
||||
# With an external draw.io the app falls back to draw.io's own toolbar and those features are off.
|
||||
|
||||
# Subdirectory Deployment (Optional)
|
||||
# For deploying to a subdirectory (e.g., https://example.com/nextaidrawio)
|
||||
@@ -163,12 +166,22 @@ AI_MODEL=global.anthropic.claude-sonnet-4-5-20250929-v1:0
|
||||
# Set to "false" to block private IPs, localhost, and internal hostnames
|
||||
# ALLOW_PRIVATE_URLS=false
|
||||
|
||||
# Behind a CDN such as Cloudflare (Optional)
|
||||
# The daily quota is counted per IP. By default the IP is the first
|
||||
# X-Forwarded-For entry, which visitors can set to anything. Name the header
|
||||
# your CDN fills with the visitor's real IP instead:
|
||||
# CLIENT_IP_HEADER=cf-connecting-ip
|
||||
# Then have the CDN add an X-Origin-Secret header with this value to every
|
||||
# request. API calls without it get 403, so nobody can skip the CDN and fake
|
||||
# the IP header above.
|
||||
# ORIGIN_SECRET=a-long-random-string
|
||||
|
||||
# Self-hosted deployment (Optional)
|
||||
# Self-hosted users may implement custom quota-management solutions,
|
||||
# which triggers the client UI to display messages suggesting self-hosting or sponsorship.
|
||||
# This switch allows self-hosted users to provide custom messages in response to a 429 code,
|
||||
# in messageTokenSelfHosted, messageApiSelfHosted, and tipSelfHosted translation strings.
|
||||
# It also turns off the MCP server advertisement in the chat examples.
|
||||
# It also turns off the MCP server advertisement in Settings > About.
|
||||
# NEXT_PUBLIC_SELFHOSTED=true
|
||||
|
||||
# Minimax Configuration (Optional)
|
||||
|
||||
@@ -1,20 +1,45 @@
|
||||
import type { MutableRefObject } from "react"
|
||||
import type { RefObject } from "react"
|
||||
import type { DiagramOperation } from "@/components/chat/types"
|
||||
import type {
|
||||
ValidationState,
|
||||
ValidationStatus,
|
||||
} from "@/components/chat/ValidationCard"
|
||||
import type { LoadMode } from "@/contexts/diagram-context"
|
||||
import { pageModelXml, pageSelectorFor, placeOnPage } from "@/lib/diagram-pages"
|
||||
import type { ValidationResult } from "@/lib/diagram-validator"
|
||||
import { formatValidationFeedback } from "@/lib/diagram-validator"
|
||||
import { isMxCellXmlComplete } from "@/lib/utils"
|
||||
import { foldCells } from "@/packages/mcp-server/src/compact-cells.ts"
|
||||
import { editDiagram } from "@/packages/mcp-server/src/edit-diagram.ts"
|
||||
import { prepareNewDiagram } from "@/packages/mcp-server/src/new-diagram.ts"
|
||||
import { hasCells } from "@/packages/mcp-server/src/pages.ts"
|
||||
|
||||
const DEBUG = process.env.NODE_ENV === "development"
|
||||
|
||||
// display_diagram replaces the document with this one page
|
||||
// The page a drawing is wrapped in; on the canvas it replaces the page the
|
||||
// model works on, so the canvas page keeps its own id and name
|
||||
const NEW_PAGE = { pageId: "page-1", pageName: "Page-1" }
|
||||
|
||||
/**
|
||||
* A new diagram written without file variables (%name% placeholders) keeps
|
||||
* the canvas file's, as replacing the page in draw.io does
|
||||
*/
|
||||
export function keepFileVars(xml: string, canvasXml: string): string {
|
||||
const varsOf = (doc: Document) =>
|
||||
doc.documentElement?.nodeName === "mxfile"
|
||||
? doc.documentElement.getAttribute("vars")
|
||||
: null
|
||||
const parser = new DOMParser()
|
||||
const canvasVars = varsOf(parser.parseFromString(canvasXml, "text/xml"))
|
||||
if (!canvasVars) return xml
|
||||
const doc = parser.parseFromString(xml, "text/xml")
|
||||
if (doc.documentElement?.nodeName !== "mxfile" || varsOf(doc) !== null) {
|
||||
return xml
|
||||
}
|
||||
doc.documentElement.setAttribute("vars", canvasVars)
|
||||
return new XMLSerializer().serializeToString(doc)
|
||||
}
|
||||
|
||||
interface ToolCall {
|
||||
toolCallId: string
|
||||
toolName: string
|
||||
@@ -50,16 +75,26 @@ type ValidateDiagramFn = (
|
||||
) => Promise<ValidationResult>
|
||||
|
||||
interface UseDiagramToolHandlersParams {
|
||||
partialXmlRef: MutableRefObject<string>
|
||||
editDiagramOriginalXmlRef: MutableRefObject<Map<string, string>>
|
||||
partialXmlRef: RefObject<string>
|
||||
// Diagram before a cut off display_diagram whose half drawn preview
|
||||
// stays while append_diagram finishes it; null when none is pending
|
||||
continuationOriginalRef: RefObject<string | null>
|
||||
editDiagramOriginalXmlRef: RefObject<Map<string, string>>
|
||||
// Tool calls the streaming preview must leave alone (shared with it)
|
||||
processedToolCallsRef: MutableRefObject<Set<string>>
|
||||
processedToolCallsRef: RefObject<Set<string>>
|
||||
// Failed VLM validations in the current user turn (reset on each user message)
|
||||
validationRetryCountRef: MutableRefObject<number>
|
||||
chartXMLRef: MutableRefObject<string>
|
||||
onDisplayChart: (xml: string, skipValidation?: boolean) => string | null
|
||||
onFetchChart: (saveToHistory?: boolean) => Promise<string>
|
||||
onExport: () => void
|
||||
validationRetryCountRef: RefObject<number>
|
||||
chartXMLRef: RefObject<string>
|
||||
// The page the model reads and writes in this turn (the one the user
|
||||
// viewed when it began); null, or absent, means the first page
|
||||
turnPageIdRef?: RefObject<string | null>
|
||||
onDisplayChart: (
|
||||
xml: string,
|
||||
skipValidation?: boolean,
|
||||
mode?: LoadMode,
|
||||
meta?: { toolCallId?: string; pageId?: string | null },
|
||||
) => string | null
|
||||
onFetchChart: () => Promise<string>
|
||||
captureValidationPng?: () => Promise<string | null>
|
||||
validateDiagram?: ValidateDiagramFn
|
||||
enableVlmValidation?: boolean
|
||||
@@ -84,13 +119,14 @@ interface UseDiagramToolHandlersParams {
|
||||
*/
|
||||
export function useDiagramToolHandlers({
|
||||
partialXmlRef,
|
||||
continuationOriginalRef,
|
||||
editDiagramOriginalXmlRef,
|
||||
processedToolCallsRef,
|
||||
validationRetryCountRef,
|
||||
chartXMLRef,
|
||||
turnPageIdRef,
|
||||
onDisplayChart,
|
||||
onFetchChart,
|
||||
onExport,
|
||||
captureValidationPng,
|
||||
validateDiagram,
|
||||
enableVlmValidation = true,
|
||||
@@ -146,6 +182,35 @@ export function useDiagramToolHandlers({
|
||||
// handler. The first is the diagram before all of them. A call that
|
||||
// draws its result replaces those previews, so the preview code must
|
||||
// neither draw them again nor undo them later. Returns that first one.
|
||||
// The final result as one undo step. A cut off drawing it replaces goes
|
||||
// first, so the step (and the version) starts from the diagram before
|
||||
// it, also when a failed call in between was undone to the cut off one.
|
||||
const commit = (xml: string, toolCallId: string) => {
|
||||
const original = continuationOriginalRef.current
|
||||
if (original !== null) onDisplayChart(original, true, "revert")
|
||||
const error = onDisplayChart(xml, true, "commit", {
|
||||
toolCallId,
|
||||
pageId: aiPageId(),
|
||||
})
|
||||
if (!error) continuationOriginalRef.current = null
|
||||
return error
|
||||
}
|
||||
|
||||
const aiPageId = () => turnPageIdRef?.current ?? null
|
||||
|
||||
// The diagram as the model sees it in the chat request: its page only
|
||||
const shownToModel = (xml: string) =>
|
||||
foldCells(pageModelXml(xml, aiPageId()) ?? xml)
|
||||
|
||||
// A drawn page goes onto the model's page of the canvas file, which
|
||||
// keeps its other pages; a drawing that brings several pages replaces
|
||||
// the file, and gets its variables
|
||||
const onAiPage = (drawnXml: string) =>
|
||||
keepFileVars(
|
||||
placeOnPage(drawnXml, chartXMLRef.current, aiPageId()),
|
||||
chartXMLRef.current,
|
||||
)
|
||||
|
||||
const takeOriginals = (): string | undefined => {
|
||||
const [originalXml] = editDiagramOriginalXmlRef.current.values()
|
||||
for (const id of editDiagramOriginalXmlRef.current.keys()) {
|
||||
@@ -181,6 +246,15 @@ export function useDiagramToolHandlers({
|
||||
if (isTruncated) {
|
||||
// Store the partial XML for continuation via append_diagram
|
||||
partialXmlRef.current = xml
|
||||
// The half drawn preview stays while append_diagram finishes
|
||||
// it; the chat engine brings this diagram back if that never
|
||||
// happens
|
||||
if (
|
||||
originalXml !== undefined &&
|
||||
continuationOriginalRef.current === null
|
||||
) {
|
||||
continuationOriginalRef.current = originalXml
|
||||
}
|
||||
|
||||
// Tell LLM to use append_diagram to continue
|
||||
const partialEnding = partialXmlRef.current.slice(-500)
|
||||
@@ -210,16 +284,19 @@ NEXT STEP: Call append_diagram with the continuation XML.
|
||||
|
||||
// Wrap, validate and auto-fix the model's XML like the MCP server's
|
||||
// create_new_diagram, then load it
|
||||
// One undo step (and a version) right away, before the screenshot
|
||||
// check: a stop, another chat or a hand edit during the check then
|
||||
// finds the diagram already in place
|
||||
const prepared = prepareNewDiagram(finalXml, NEW_PAGE)
|
||||
const validationError = prepared.ok
|
||||
? onDisplayChart(prepared.xml, true)
|
||||
? commit(onAiPage(prepared.xml), toolCall.toolCallId)
|
||||
: prepared.error
|
||||
|
||||
if (validationError) {
|
||||
console.warn("[display_diagram] Validation error:", validationError)
|
||||
// Undo the streamed preview, as a failed edit does: the canvas
|
||||
// keeps the diagram from before this failed call
|
||||
if (originalXml) onDisplayChart(originalXml, true)
|
||||
if (originalXml) onDisplayChart(originalXml, true, "revert")
|
||||
// Return error to model - sendAutomaticallyWhen will trigger retry
|
||||
if (DEBUG) {
|
||||
console.log(
|
||||
@@ -430,7 +507,7 @@ ${finalXml}
|
||||
// On failure, undo the streaming preview so the canvas matches the XML
|
||||
// reported back to the model
|
||||
const restoreOriginal = () => {
|
||||
if (originalXml) onDisplayChart(originalXml, true)
|
||||
if (originalXml) onDisplayChart(originalXml, true, "revert")
|
||||
}
|
||||
try {
|
||||
if (originalXml) {
|
||||
@@ -442,13 +519,17 @@ ${finalXml}
|
||||
currentXml = cachedXML
|
||||
} else {
|
||||
// Last resort: export from iframe
|
||||
currentXml = await onFetchChart(false)
|
||||
currentXml = await onFetchChart()
|
||||
}
|
||||
}
|
||||
|
||||
// All or nothing, checked like the MCP server's edit_diagram.
|
||||
// The model sees the first page, so edits target it.
|
||||
const outcome = editDiagram(currentXml, operations, {})
|
||||
// The model sees its page, so edits target it.
|
||||
const outcome = editDiagram(
|
||||
currentXml,
|
||||
operations,
|
||||
pageSelectorFor(currentXml, aiPageId()),
|
||||
)
|
||||
if (!outcome.ok) {
|
||||
const reason = outcome.pageError
|
||||
? outcome.errors[0]
|
||||
@@ -462,7 +543,7 @@ ${finalXml}
|
||||
|
||||
Current diagram XML:
|
||||
\`\`\`xml
|
||||
${currentXml}
|
||||
${shownToModel(currentXml)}
|
||||
\`\`\`
|
||||
|
||||
Please check the cell IDs and retry.`,
|
||||
@@ -470,8 +551,7 @@ Please check the cell IDs and retry.`,
|
||||
return
|
||||
}
|
||||
|
||||
onDisplayChart(outcome.xml, true)
|
||||
onExport()
|
||||
commit(outcome.xml, toolCall.toolCallId)
|
||||
addToolOutput({
|
||||
tool: "edit_diagram",
|
||||
toolCallId: toolCall.toolCallId,
|
||||
@@ -492,7 +572,7 @@ Please check the cell IDs and retry.`,
|
||||
|
||||
Current diagram XML:
|
||||
\`\`\`xml
|
||||
${currentXml || "No XML available"}
|
||||
${currentXml ? shownToModel(currentXml) : "No XML available"}
|
||||
\`\`\`
|
||||
|
||||
Please check cell IDs and retry, or use display_diagram to regenerate.`,
|
||||
@@ -522,7 +602,10 @@ Use display_diagram to create the complete diagram, or edit_diagram to change th
|
||||
// Detect if LLM incorrectly started fresh instead of continuing
|
||||
// LLM should only output bare mxCells now, so wrapper tags indicate error
|
||||
const trimmed = xml.trim()
|
||||
// Definitions at the start are a restart only once cells were written
|
||||
const isFreshStart =
|
||||
(trimmed.startsWith("<mxStyle") &&
|
||||
hasCells(partialXmlRef.current)) ||
|
||||
trimmed.startsWith("<mxGraphModel") ||
|
||||
trimmed.startsWith("<root") ||
|
||||
trimmed.startsWith("<mxfile") ||
|
||||
@@ -558,17 +641,19 @@ Start your continuation with the NEXT character after where it stopped.`,
|
||||
partialXmlRef.current = "" // Reset
|
||||
|
||||
const prepared = prepareNewDiagram(finalXml, NEW_PAGE)
|
||||
// It draws now: it takes the stored originals, as display_diagram
|
||||
const originalXml = prepared.ok ? takeOriginals() : undefined
|
||||
// The continuation ends here, drawn or not: it takes the stored
|
||||
// originals, so the preview code undoes none of them later
|
||||
const originalXml = takeOriginals()
|
||||
const validationError = prepared.ok
|
||||
? onDisplayChart(prepared.xml, true)
|
||||
? commit(onAiPage(prepared.xml), toolCall.toolCallId)
|
||||
: prepared.error
|
||||
|
||||
if (validationError) {
|
||||
// Loading failed: back to the diagram before the previews
|
||||
if (prepared.ok && originalXml) {
|
||||
onDisplayChart(originalXml, true)
|
||||
}
|
||||
// Back to the diagram before the cut off drawing, or else
|
||||
// before the previews
|
||||
const before = continuationOriginalRef.current ?? originalXml
|
||||
continuationOriginalRef.current = null
|
||||
if (before) onDisplayChart(before, true, "revert")
|
||||
addToolOutput({
|
||||
tool: "append_diagram",
|
||||
toolCallId: toolCall.toolCallId,
|
||||
|
||||
+15
-14
@@ -36,15 +36,19 @@ function migrateOldConfig(): MultiModelConfig | null {
|
||||
const oldApiKey = localStorage.getItem(OLD_KEYS.aiApiKey)
|
||||
const oldModel = localStorage.getItem(OLD_KEYS.aiModel)
|
||||
|
||||
// No old config to migrate
|
||||
if (!oldProvider || !oldApiKey || !oldModel) return null
|
||||
// No old config to migrate. A local Ollama needs no key.
|
||||
if (!oldProvider || !oldModel) return null
|
||||
if (!oldApiKey && oldProvider !== "ollama") return null
|
||||
|
||||
const oldBaseUrl = localStorage.getItem(OLD_KEYS.aiBaseUrl)
|
||||
|
||||
// Create new config from old format
|
||||
const provider = createProviderConfig(oldProvider as ProviderName)
|
||||
provider.apiKey = oldApiKey
|
||||
provider.apiKey = oldApiKey ?? ""
|
||||
if (oldBaseUrl) provider.baseUrl = oldBaseUrl
|
||||
// Without one, the old version used the server's Ollama (OLLAMA_BASE_URL
|
||||
// or this machine), not the cloud address new providers get
|
||||
else if (oldProvider === "ollama") provider.baseUrl = ""
|
||||
|
||||
const model = createModelConfig(oldModel)
|
||||
provider.models.push(model)
|
||||
@@ -161,11 +165,9 @@ export interface UseModelConfigReturn {
|
||||
models: FlattenedModel[]
|
||||
selectedModel: FlattenedModel | undefined
|
||||
selectedModelId: string | undefined
|
||||
showUnvalidatedModels: boolean
|
||||
|
||||
// Actions
|
||||
setSelectedModelId: (modelId: string | undefined) => void
|
||||
setShowUnvalidatedModels: (show: boolean) => void
|
||||
addProvider: (provider: ProviderName) => ProviderConfig
|
||||
updateProvider: (
|
||||
providerId: string,
|
||||
@@ -308,13 +310,6 @@ export function useModelConfig(): UseModelConfigReturn {
|
||||
}))
|
||||
}, [])
|
||||
|
||||
const setShowUnvalidatedModels = useCallback((show: boolean) => {
|
||||
setConfig((prev) => ({
|
||||
...prev,
|
||||
showUnvalidatedModels: show,
|
||||
}))
|
||||
}, [])
|
||||
|
||||
const addProvider = useCallback(
|
||||
(provider: ProviderName): ProviderConfig => {
|
||||
const newProvider = createProviderConfig(provider)
|
||||
@@ -441,9 +436,7 @@ export function useModelConfig(): UseModelConfigReturn {
|
||||
models,
|
||||
selectedModel,
|
||||
selectedModelId: config.selectedModelId,
|
||||
showUnvalidatedModels: config.showUnvalidatedModels ?? false,
|
||||
setSelectedModelId,
|
||||
setShowUnvalidatedModels,
|
||||
addProvider,
|
||||
updateProvider,
|
||||
deleteProvider,
|
||||
@@ -473,6 +466,8 @@ export function getSelectedAIConfig(): {
|
||||
selectedModelId: string
|
||||
// Vertex AI credentials (Express Mode)
|
||||
vertexApiKey: string
|
||||
// The user's provider of the selected model ("" for a server model)
|
||||
providerId: string
|
||||
} {
|
||||
const empty = {
|
||||
accessCode: "",
|
||||
@@ -486,6 +481,7 @@ export function getSelectedAIConfig(): {
|
||||
awsSessionToken: "",
|
||||
selectedModelId: "",
|
||||
vertexApiKey: "",
|
||||
providerId: "",
|
||||
}
|
||||
|
||||
if (typeof window === "undefined") return empty
|
||||
@@ -510,6 +506,7 @@ export function getSelectedAIConfig(): {
|
||||
awsSessionToken: "",
|
||||
selectedModelId: "",
|
||||
vertexApiKey: "",
|
||||
providerId: "",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,5 +563,9 @@ export function getSelectedAIConfig(): {
|
||||
selectedModelId: config.selectedModelId || "",
|
||||
// Vertex AI credentials (Express Mode)
|
||||
vertexApiKey: model.vertexApiKey || "",
|
||||
providerId:
|
||||
config.providers.find((p) =>
|
||||
p.models.some((m) => m.id === config.selectedModelId),
|
||||
)?.id ?? "",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import { PANEL_MIN_WIDTH, useSettingsStore } from "@/stores/settings-store"
|
||||
|
||||
// Room the canvas keeps next to the chat panel in a small window
|
||||
const MIN_CANVAS_WIDTH = 400
|
||||
|
||||
/** The chat panel's width, narrower when the window has no room for it */
|
||||
export function usePanelWidth(): number {
|
||||
const width = useSettingsStore((s) => s.panelWidth)
|
||||
// Set after mounting, so the server render and the first one agree
|
||||
const [windowWidth, setWindowWidth] = useState(Number.POSITIVE_INFINITY)
|
||||
useEffect(() => {
|
||||
const update = () => setWindowWidth(window.innerWidth)
|
||||
update()
|
||||
window.addEventListener("resize", update)
|
||||
return () => window.removeEventListener("resize", update)
|
||||
}, [])
|
||||
return Math.max(
|
||||
PANEL_MIN_WIDTH,
|
||||
Math.min(width, windowWidth - MIN_CANVAS_WIDTH),
|
||||
)
|
||||
}
|
||||
@@ -14,18 +14,32 @@ import {
|
||||
isIndexedDBAvailable,
|
||||
migrateFromLocalStorage,
|
||||
readSessionCount,
|
||||
renameSession as renameSessionInDB,
|
||||
type SessionMetadata,
|
||||
type StoredMessage,
|
||||
saveSession,
|
||||
} from "@/lib/session-storage"
|
||||
import { STORAGE_KEYS } from "@/lib/storage"
|
||||
import {
|
||||
type DiagramVersion,
|
||||
versionsFromLegacyHistory,
|
||||
} from "@/stores/versions-store"
|
||||
|
||||
export interface SessionData {
|
||||
messages: StoredMessage[]
|
||||
xmlSnapshots: [number, string][]
|
||||
diagramXml: string
|
||||
thumbnailDataUrl?: string
|
||||
diagramHistory?: { svg: string; xml: string }[]
|
||||
versions?: DiagramVersion[]
|
||||
/** Title for a session created by this save (default: first message) */
|
||||
title?: string
|
||||
}
|
||||
|
||||
/** Versions of a stored session, converting the old history format */
|
||||
export function getSessionVersions(
|
||||
session: Pick<ChatSession, "versions" | "diagramHistory">,
|
||||
): DiagramVersion[] {
|
||||
return session.versions ?? versionsFromLegacyHistory(session.diagramHistory)
|
||||
}
|
||||
|
||||
// Taken right before a save's data is read: the chat on screen then, and
|
||||
@@ -57,7 +71,22 @@ export interface UseSessionManagerReturn {
|
||||
refreshSessions: () => Promise<void>
|
||||
clearCurrentSession: () => void
|
||||
getChatGeneration: () => number
|
||||
/** The chat on screen now, also right after a save created it */
|
||||
getCurrentSessionId: () => string | null
|
||||
getSaveTicket: () => SaveTicket
|
||||
renameSession: (id: string, title: string) => Promise<void>
|
||||
/**
|
||||
* Run before the URL (browser back or forward) puts another chat on
|
||||
* screen: the chat on screen is saved first, which the app's own ways
|
||||
* of leaving it do themselves
|
||||
*/
|
||||
setBeforeUrlSwitch: (handler: (() => Promise<void>) | null) => void
|
||||
/**
|
||||
* Runs fn while the chat with this id is about to be put on screen: a
|
||||
* save meanwhile that creates a session (over the chat limit) does not
|
||||
* delete it as the oldest one
|
||||
*/
|
||||
whileOpening: <T>(id: string, fn: () => Promise<T>) => Promise<T>
|
||||
}
|
||||
|
||||
// Reading the session list loads every stored session in full, and window
|
||||
@@ -103,6 +132,31 @@ export function useSessionManager(
|
||||
const saveSeqRef = useRef(0)
|
||||
const savedSeqRef = useRef(0)
|
||||
|
||||
const beforeUrlSwitchRef = useRef<(() => Promise<void>) | null>(null)
|
||||
// The chat about to be put on screen, while the one on screen is saved
|
||||
const openingSessionRef = useRef<{ id: string } | null>(null)
|
||||
const whileOpening = useCallback(
|
||||
async <T>(id: string, fn: () => Promise<T>): Promise<T> => {
|
||||
// Its own: another one opened meanwhile sets another
|
||||
const opening = { id }
|
||||
openingSessionRef.current = opening
|
||||
try {
|
||||
return await fn()
|
||||
} finally {
|
||||
if (openingSessionRef.current === opening) {
|
||||
openingSessionRef.current = null
|
||||
}
|
||||
}
|
||||
},
|
||||
[],
|
||||
)
|
||||
const setBeforeUrlSwitch = useCallback(
|
||||
(handler: (() => Promise<void>) | null) => {
|
||||
beforeUrlSwitchRef.current = handler
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const changeChat = useCallback((session: ChatSession | null) => {
|
||||
chatGenerationRef.current++
|
||||
currentSessionRef.current = session
|
||||
@@ -215,6 +269,19 @@ export function useSessionManager(
|
||||
|
||||
// Only update if the session is different from current
|
||||
if (session && currentSessionRef.current?.id !== session.id) {
|
||||
// The chat on screen is saved first. Meanwhile the URL
|
||||
// may change again, or another chat come on screen.
|
||||
await whileOpening(session.id, async () => {
|
||||
try {
|
||||
await beforeUrlSwitchRef.current?.()
|
||||
} catch (error) {
|
||||
console.warn("Failed to save the chat left:", error)
|
||||
}
|
||||
})
|
||||
if (currentSequence !== urlChangeSequenceRef.current) {
|
||||
return
|
||||
}
|
||||
if (generation !== chatGenerationRef.current) return
|
||||
changeChat(session)
|
||||
}
|
||||
}
|
||||
@@ -267,7 +334,7 @@ export function useSessionManager(
|
||||
xmlSnapshots: session.xmlSnapshots,
|
||||
diagramXml: session.diagramXml,
|
||||
thumbnailDataUrl: session.thumbnailDataUrl,
|
||||
diagramHistory: session.diagramHistory,
|
||||
versions: getSessionVersions(session),
|
||||
}
|
||||
},
|
||||
[currentSessionId, changeChat],
|
||||
@@ -319,8 +386,8 @@ export function useSessionManager(
|
||||
xmlSnapshots: data.xmlSnapshots,
|
||||
diagramXml: data.diagramXml,
|
||||
thumbnailDataUrl: data.thumbnailDataUrl,
|
||||
diagramHistory: data.diagramHistory,
|
||||
title: extractTitle(data.messages),
|
||||
versions: data.versions,
|
||||
title: data.title || extractTitle(data.messages),
|
||||
}
|
||||
// Without a stored session, keep no session id (it would end
|
||||
// up in the URL and point to nothing after a reload)
|
||||
@@ -329,7 +396,9 @@ export function useSessionManager(
|
||||
return false
|
||||
}
|
||||
savedSeqRef.current = seq
|
||||
await enforceSessionLimit()
|
||||
await enforceSessionLimit(
|
||||
() => openingSessionRef.current?.id,
|
||||
)
|
||||
if (stillOnScreen()) {
|
||||
currentSessionRef.current = newSession
|
||||
setCurrentSession(newSession)
|
||||
@@ -348,8 +417,9 @@ export function useSessionManager(
|
||||
thumbnailDataUrl:
|
||||
data.thumbnailDataUrl ??
|
||||
currentSession.thumbnailDataUrl,
|
||||
diagramHistory:
|
||||
data.diagramHistory ?? currentSession.diagramHistory,
|
||||
versions:
|
||||
data.versions ?? getSessionVersions(currentSession),
|
||||
diagramHistory: undefined,
|
||||
updatedAt: Date.now(),
|
||||
// Update title if it's still default and we have messages
|
||||
title:
|
||||
@@ -403,6 +473,10 @@ export function useSessionManager(
|
||||
}, [changeChat])
|
||||
|
||||
const getChatGeneration = useCallback(() => chatGenerationRef.current, [])
|
||||
const getCurrentSessionId = useCallback(
|
||||
() => currentSessionRef.current?.id ?? null,
|
||||
[],
|
||||
)
|
||||
|
||||
const getSaveTicket = useCallback(
|
||||
(): SaveTicket => ({
|
||||
@@ -412,6 +486,38 @@ export function useSessionManager(
|
||||
[],
|
||||
)
|
||||
|
||||
const renameSession = useCallback(
|
||||
(id: string, title: string): Promise<void> => {
|
||||
const trimmed = title.trim().slice(0, 100)
|
||||
if (!trimmed) return Promise.resolve()
|
||||
// In the save queue, so a save running now cannot put the old
|
||||
// title back
|
||||
const run = async () => {
|
||||
const updated = await renameSessionInDB(id, trimmed)
|
||||
// Also when it could not be stored (another tab deleted the
|
||||
// chat): the next save of the chat on screen writes it
|
||||
const current = currentSessionRef.current
|
||||
if (current?.id === id) {
|
||||
currentSessionRef.current = { ...current, title: trimmed }
|
||||
setCurrentSession(currentSessionRef.current)
|
||||
}
|
||||
if (!updated) {
|
||||
notifySaveFailed(dict.errors.sessionSaveFailed)
|
||||
return
|
||||
}
|
||||
setSessions((prev) =>
|
||||
prev.map((s) =>
|
||||
s.id === id ? { ...s, title: trimmed } : s,
|
||||
),
|
||||
)
|
||||
}
|
||||
const result = saveQueueRef.current.then(run)
|
||||
saveQueueRef.current = result.catch(() => {})
|
||||
return result
|
||||
},
|
||||
[dict],
|
||||
)
|
||||
|
||||
return {
|
||||
sessions,
|
||||
currentSessionId,
|
||||
@@ -424,6 +530,10 @@ export function useSessionManager(
|
||||
refreshSessions,
|
||||
clearCurrentSession,
|
||||
getChatGeneration,
|
||||
getCurrentSessionId,
|
||||
getSaveTicket,
|
||||
renameSession,
|
||||
setBeforeUrlSwitch,
|
||||
whileOpening,
|
||||
}
|
||||
}
|
||||
|
||||
+37
-19
@@ -911,7 +911,9 @@ export function getAIModel(clientOverrides?: ClientOverrides): ModelConfig {
|
||||
|
||||
switch (provider) {
|
||||
case "bedrock": {
|
||||
// Use client-provided credentials if available, otherwise fall back to IAM/env vars
|
||||
// Use client-provided credentials if available (a Bedrock API
|
||||
// key, or an access key pair), otherwise fall back to IAM/env vars
|
||||
const clientApiKey = overrides?.apiKey
|
||||
const hasClientCredentials =
|
||||
overrides?.awsAccessKeyId && overrides?.awsSecretAccessKey
|
||||
// Keys from the admin panel. The ADMIN_ names keep them out of the
|
||||
@@ -937,33 +939,46 @@ export function getAIModel(clientOverrides?: ClientOverrides): ModelConfig {
|
||||
process.env.AWS_REGION ||
|
||||
"us-west-2"
|
||||
|
||||
const bedrockProvider = hasClientCredentials
|
||||
const bedrockProvider = clientApiKey
|
||||
? createAmazonBedrock({
|
||||
region: bedrockRegion,
|
||||
accessKeyId: overrides.awsAccessKeyId as string,
|
||||
secretAccessKey: overrides.awsSecretAccessKey as string,
|
||||
...(overrides?.awsSessionToken && {
|
||||
sessionToken: overrides.awsSessionToken,
|
||||
}),
|
||||
// Without an apiKey the SDK reads the server's
|
||||
// AWS_BEARER_TOKEN_BEDROCK, which wins over the keys
|
||||
apiKey: "",
|
||||
apiKey: clientApiKey,
|
||||
// The SDK falls back to signing with AWS keys when it
|
||||
// drops a key (one of spaces): never the server's
|
||||
credentialProvider: async () => {
|
||||
throw new Error("The Bedrock API key is empty")
|
||||
},
|
||||
// Without a baseURL it reads the server's
|
||||
// AWS_ENDPOINT_URL_BEDROCK_RUNTIME / AWS_ENDPOINT_URL
|
||||
baseURL: bedrockRuntimeUrl(bedrockRegion),
|
||||
})
|
||||
: adminAccessKeyId && adminSecretAccessKey
|
||||
: hasClientCredentials
|
||||
? createAmazonBedrock({
|
||||
region: bedrockRegion,
|
||||
accessKeyId: adminAccessKeyId,
|
||||
secretAccessKey: adminSecretAccessKey,
|
||||
// The keys the admin panel's Test button checked
|
||||
accessKeyId: overrides.awsAccessKeyId as string,
|
||||
secretAccessKey: overrides.awsSecretAccessKey as string,
|
||||
...(overrides?.awsSessionToken && {
|
||||
sessionToken: overrides.awsSessionToken,
|
||||
}),
|
||||
// Without an apiKey the SDK reads the server's
|
||||
// AWS_BEARER_TOKEN_BEDROCK, which wins over the keys
|
||||
apiKey: "",
|
||||
// Without a baseURL it reads the server's
|
||||
// AWS_ENDPOINT_URL_BEDROCK_RUNTIME / AWS_ENDPOINT_URL
|
||||
baseURL: bedrockRuntimeUrl(bedrockRegion),
|
||||
})
|
||||
: createAmazonBedrock({
|
||||
region: bedrockRegion,
|
||||
credentialProvider: fromNodeProviderChain(),
|
||||
})
|
||||
: adminAccessKeyId && adminSecretAccessKey
|
||||
? createAmazonBedrock({
|
||||
region: bedrockRegion,
|
||||
accessKeyId: adminAccessKeyId,
|
||||
secretAccessKey: adminSecretAccessKey,
|
||||
// The keys the admin panel's Test button checked
|
||||
apiKey: "",
|
||||
})
|
||||
: createAmazonBedrock({
|
||||
region: bedrockRegion,
|
||||
credentialProvider: fromNodeProviderChain(),
|
||||
})
|
||||
model = bedrockProvider(modelId)
|
||||
// Add Anthropic beta options if using Claude models via Bedrock
|
||||
if (modelId.includes("anthropic.claude")) {
|
||||
@@ -1194,7 +1209,10 @@ export function usesServerCredentials(
|
||||
const baseUrl = normalizeBaseUrl(overrides?.baseUrl ?? "")
|
||||
switch (provider) {
|
||||
case "bedrock":
|
||||
return !(overrides?.awsAccessKeyId && overrides?.awsSecretAccessKey)
|
||||
return !(
|
||||
overrides?.apiKey ||
|
||||
(overrides?.awsAccessKeyId && overrides?.awsSecretAccessKey)
|
||||
)
|
||||
case "vertexai":
|
||||
return !overrides?.vertexApiKey
|
||||
case "edgeone":
|
||||
|
||||
+133
-125
@@ -740,146 +740,154 @@ export const CACHED_EXAMPLE_RESPONSES: CachedResponse[] = [
|
||||
{
|
||||
promptText: "Draw a cat for me",
|
||||
hasImage: false,
|
||||
xml: `<mxCell id="2" value="" style="ellipse;whiteSpace=wrap;html=1;aspect=fixed;fillColor=#FFE6CC;strokeColor=#000000;strokeWidth=2;" vertex="1" parent="1">
|
||||
<mxGeometry x="300" y="150" width="120" height="120" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="3" value="" style="triangle;whiteSpace=wrap;html=1;fillColor=#FFE6CC;strokeColor=#000000;strokeWidth=2;rotation=30;" vertex="1" parent="1">
|
||||
<mxGeometry x="280" y="120" width="50" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="4" value="" style="triangle;whiteSpace=wrap;html=1;fillColor=#FFE6CC;strokeColor=#000000;strokeWidth=2;rotation=-30;" vertex="1" parent="1">
|
||||
<mxGeometry x="390" y="120" width="50" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="5" value="" style="triangle;whiteSpace=wrap;html=1;fillColor=#FFB6C1;strokeColor=none;rotation=30;" vertex="1" parent="1">
|
||||
<mxGeometry x="290" y="135" width="30" height="35" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="6" value="" style="triangle;whiteSpace=wrap;html=1;fillColor=#FFB6C1;strokeColor=none;rotation=-30;" vertex="1" parent="1">
|
||||
<mxGeometry x="400" y="135" width="30" height="35" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="7" value="" style="ellipse;whiteSpace=wrap;html=1;aspect=fixed;fillColor=#000000;strokeColor=#000000;" vertex="1" parent="1">
|
||||
<mxGeometry x="325" y="185" width="15" height="15" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="8" value="" style="ellipse;whiteSpace=wrap;html=1;aspect=fixed;fillColor=#000000;strokeColor=#000000;" vertex="1" parent="1">
|
||||
<mxGeometry x="380" y="185" width="15" height="15" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="9" value="" style="triangle;whiteSpace=wrap;html=1;fillColor=#FFB6C1;strokeColor=#000000;strokeWidth=1;rotation=180;" vertex="1" parent="1">
|
||||
<mxGeometry x="350" y="210" width="20" height="15" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="10" value="" style="curved=1;endArrow=none;html=1;strokeColor=#000000;strokeWidth=2;exitX=0.5;exitY=1;exitDx=0;exitDy=0;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="360" y="220" as="sourcePoint"/>
|
||||
<mxPoint x="340" y="235" as="targetPoint"/>
|
||||
xml: `<mxCell id="2" edge="1" parent="1" style="curved=1;endArrow=none;html=1;strokeWidth=14;strokeColor=#F4A460;" value="">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="355" y="230"/>
|
||||
<mxPoint x="580" y="480"/>
|
||||
<mxPoint x="600" y="380"/>
|
||||
</Array>
|
||||
<mxPoint x="490" y="480" as="sourcePoint"/>
|
||||
<mxPoint x="560" y="330" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="11" value="" style="curved=1;endArrow=none;html=1;strokeColor=#000000;strokeWidth=2;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="360" y="220" as="sourcePoint"/>
|
||||
<mxPoint x="380" y="235" as="targetPoint"/>
|
||||
<mxCell id="3" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#F4A460;strokeColor=#8B5A2B;strokeWidth=2;" value="" vertex="1">
|
||||
<mxGeometry height="190" width="200" x="320" y="320" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="4" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFE4C4;strokeColor=none;" value="" vertex="1">
|
||||
<mxGeometry height="120" width="100" x="370" y="360" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="5" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#F4A460;strokeColor=#8B5A2B;strokeWidth=2;" value="" vertex="1">
|
||||
<mxGeometry height="40" width="60" x="350" y="480" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="6" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#F4A460;strokeColor=#8B5A2B;strokeWidth=2;" value="" vertex="1">
|
||||
<mxGeometry height="40" width="60" x="430" y="480" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="7" parent="1" style="triangle;direction=north;whiteSpace=wrap;html=1;fillColor=#F4A460;strokeColor=#8B5A2B;strokeWidth=2;rotation=-15;" value="" vertex="1">
|
||||
<mxGeometry height="80" width="70" x="310" y="110" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="8" parent="1" style="triangle;direction=north;whiteSpace=wrap;html=1;fillColor=#F4A460;strokeColor=#8B5A2B;strokeWidth=2;rotation=15;" value="" vertex="1">
|
||||
<mxGeometry height="80" width="70" x="460" y="110" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="9" parent="1" style="triangle;direction=north;whiteSpace=wrap;html=1;fillColor=#FFB6C1;strokeColor=none;rotation=-15;" value="" vertex="1">
|
||||
<mxGeometry height="45" width="36" x="327" y="135" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="10" parent="1" style="triangle;direction=north;whiteSpace=wrap;html=1;fillColor=#FFB6C1;strokeColor=none;rotation=15;" value="" vertex="1">
|
||||
<mxGeometry height="45" width="36" x="477" y="135" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="11" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#F4A460;strokeColor=#8B5A2B;strokeWidth=2;" value="" vertex="1">
|
||||
<mxGeometry height="200" width="240" x="300" y="140" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="12" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#333333;strokeColor=none;" value="" vertex="1">
|
||||
<mxGeometry height="44" width="36" x="355" y="200" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="13" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#333333;strokeColor=none;" value="" vertex="1">
|
||||
<mxGeometry height="44" width="36" x="449" y="200" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="14" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFFFFF;strokeColor=none;" value="" vertex="1">
|
||||
<mxGeometry height="13" width="13" x="363" y="207" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="15" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFFFFF;strokeColor=none;" value="" vertex="1">
|
||||
<mxGeometry height="13" width="13" x="457" y="207" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="16" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFB6C1;strokeColor=none;opacity=70;" value="" vertex="1">
|
||||
<mxGeometry height="22" width="40" x="325" y="255" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="17" parent="1" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFB6C1;strokeColor=none;opacity=70;" value="" vertex="1">
|
||||
<mxGeometry height="22" width="40" x="475" y="255" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="18" parent="1" style="triangle;direction=south;whiteSpace=wrap;html=1;fillColor=#FF69B4;strokeColor=none;" value="" vertex="1">
|
||||
<mxGeometry height="16" width="24" x="408" y="252" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="19" edge="1" parent="1" style="curved=1;endArrow=none;html=1;strokeWidth=2;strokeColor=#333333;" value="">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="365" y="230"/>
|
||||
<mxPoint x="410" y="288"/>
|
||||
</Array>
|
||||
<mxPoint x="400" y="278" as="sourcePoint"/>
|
||||
<mxPoint x="420" y="270" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="12" value="" style="endArrow=none;html=1;strokeColor=#000000;strokeWidth=1.5;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="310" y="200" as="sourcePoint"/>
|
||||
<mxPoint x="260" y="195" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="13" value="" style="endArrow=none;html=1;strokeColor=#000000;strokeWidth=1.5;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="310" y="210" as="sourcePoint"/>
|
||||
<mxPoint x="260" y="210" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="14" value="" style="endArrow=none;html=1;strokeColor=#000000;strokeWidth=1.5;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="310" y="220" as="sourcePoint"/>
|
||||
<mxPoint x="260" y="225" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="15" value="" style="endArrow=none;html=1;strokeColor=#000000;strokeWidth=1.5;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="410" y="200" as="sourcePoint"/>
|
||||
<mxPoint x="460" y="195" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="16" value="" style="endArrow=none;html=1;strokeColor=#000000;strokeWidth=1.5;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="410" y="210" as="sourcePoint"/>
|
||||
<mxPoint x="460" y="210" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="17" value="" style="endArrow=none;html=1;strokeColor=#000000;strokeWidth=1.5;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="410" y="220" as="sourcePoint"/>
|
||||
<mxPoint x="460" y="225" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="18" value="" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFE6CC;strokeColor=#000000;strokeWidth=2;" vertex="1" parent="1">
|
||||
<mxGeometry x="285" y="250" width="150" height="180" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="19" value="" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFFFFF;strokeColor=none;" vertex="1" parent="1">
|
||||
<mxGeometry x="315" y="280" width="90" height="120" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="20" value="" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFE6CC;strokeColor=#000000;strokeWidth=2;" vertex="1" parent="1">
|
||||
<mxGeometry x="300" y="410" width="40" height="50" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="21" value="" style="ellipse;whiteSpace=wrap;html=1;fillColor=#FFE6CC;strokeColor=#000000;strokeWidth=2;" vertex="1" parent="1">
|
||||
<mxGeometry x="380" y="410" width="40" height="50" as="geometry"/>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="22" value="" style="curved=1;endArrow=none;html=1;strokeColor=#000000;strokeWidth=3;fillColor=#FFE6CC;" edge="1" parent="1">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="285" y="340" as="sourcePoint"/>
|
||||
<mxPoint x="240" y="260" as="targetPoint"/>
|
||||
<mxCell id="20" edge="1" parent="1" style="curved=1;endArrow=none;html=1;strokeWidth=2;strokeColor=#333333;" value="">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="260" y="350"/>
|
||||
<mxPoint x="240" y="320"/>
|
||||
<mxPoint x="235" y="290"/>
|
||||
<mxPoint x="430" y="288"/>
|
||||
</Array>
|
||||
<mxPoint x="420" y="270" as="sourcePoint"/>
|
||||
<mxPoint x="440" y="278" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="21" edge="1" parent="1" style="endArrow=none;html=1;strokeWidth=2;strokeColor=#5C3A1A;" value="">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<mxPoint x="370" y="262" as="sourcePoint"/>
|
||||
<mxPoint x="270" y="245" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="22" edge="1" parent="1" style="endArrow=none;html=1;strokeWidth=2;strokeColor=#5C3A1A;" value="">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<mxPoint x="370" y="272" as="sourcePoint"/>
|
||||
<mxPoint x="268" y="278" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="23" edge="1" parent="1" style="endArrow=none;html=1;strokeWidth=2;strokeColor=#5C3A1A;" value="">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<mxPoint x="470" y="262" as="sourcePoint"/>
|
||||
<mxPoint x="570" y="245" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="24" edge="1" parent="1" style="endArrow=none;html=1;strokeWidth=2;strokeColor=#5C3A1A;" value="">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<mxPoint x="470" y="272" as="sourcePoint"/>
|
||||
<mxPoint x="572" y="278" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
|
||||
|
||||
<mxCell id="25" parent="1" style="text;html=1;align=center;verticalAlign=middle;fontSize=22;fontStyle=1;fontColor=#FF69B4;" value="Meow~ ♥" vertex="1">
|
||||
<mxGeometry height="40" width="120" x="530" y="120" as="geometry"/>
|
||||
</mxCell>`,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -133,3 +133,37 @@ export function fixToolInputJson(input: string): string {
|
||||
.replace(/"(\w+)"\s*=\s*"/g, '"$1": "')
|
||||
)
|
||||
}
|
||||
|
||||
// Shapes the user selected on the canvas; sent with the request as
|
||||
// selectedCells: [{ id, label }]
|
||||
const MAX_SELECTED_CELLS = 50
|
||||
const MAX_SELECTED_TEXT = 100
|
||||
|
||||
function cleanSelectionText(value: unknown): string {
|
||||
if (typeof value !== "string") return ""
|
||||
return value
|
||||
.replace(/[\r\n"]+/g, " ")
|
||||
.trim()
|
||||
.slice(0, MAX_SELECTED_TEXT)
|
||||
}
|
||||
|
||||
/** Prompt text describing the selection, or "" when there is none */
|
||||
export function formatSelectionContext(selectedCells: unknown): string {
|
||||
if (!Array.isArray(selectedCells)) return ""
|
||||
const lines = selectedCells
|
||||
.slice(0, MAX_SELECTED_CELLS)
|
||||
.map((cell) => {
|
||||
const id = cleanSelectionText(cell?.id)
|
||||
if (!id) return null
|
||||
const label = cleanSelectionText(cell?.label)
|
||||
return label ? `- id="${id}" (${label})` : `- id="${id}"`
|
||||
})
|
||||
.filter((line): line is string => line !== null)
|
||||
if (lines.length === 0) return ""
|
||||
// Past the limit the model must know the list is cut short
|
||||
const more = selectedCells.length - MAX_SELECTED_CELLS
|
||||
if (more > 0) lines.push(`- and ${more} more selected shapes not listed`)
|
||||
return `The user selected these shapes on the canvas before sending this message:
|
||||
${lines.join("\n")}
|
||||
Apply the request to the selected shapes unless it clearly asks for something else. Prefer edit_diagram with these cell ids over redrawing the whole diagram.`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { getSelectedAIConfig } from "@/hooks/use-model-config"
|
||||
|
||||
type AIConfig = ReturnType<typeof getSelectedAIConfig>
|
||||
|
||||
/**
|
||||
* Request headers for /api/chat: the access code, the user's own provider
|
||||
* credentials (when a client-side model is selected) and per-request options.
|
||||
*/
|
||||
export function buildChatHeaders(
|
||||
config: AIConfig,
|
||||
options: { minimalStyle: boolean; maxOutputTokens: string },
|
||||
): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
"x-access-code": config.accessCode,
|
||||
}
|
||||
const set = (name: string, value: string | undefined) => {
|
||||
if (value) headers[name] = value
|
||||
}
|
||||
if (config.aiProvider) {
|
||||
set("x-ai-provider", config.aiProvider)
|
||||
set("x-ai-base-url", config.aiBaseUrl)
|
||||
set("x-ai-api-key", config.aiApiKey)
|
||||
set("x-ai-model", config.aiModel)
|
||||
// AWS Bedrock credentials
|
||||
set("x-aws-access-key-id", config.awsAccessKeyId)
|
||||
set("x-aws-secret-access-key", config.awsSecretAccessKey)
|
||||
set("x-aws-region", config.awsRegion)
|
||||
set("x-aws-session-token", config.awsSessionToken)
|
||||
// Vertex AI credentials (Express Mode)
|
||||
set("x-vertex-api-key", config.vertexApiKey)
|
||||
}
|
||||
// Selected model ID for server model lookup (apiKeyEnv/baseUrlEnv)
|
||||
set("x-selected-model-id", config.selectedModelId)
|
||||
if (options.minimalStyle) headers["x-minimal-style"] = "true"
|
||||
set("x-max-output-tokens", options.maxOutputTokens)
|
||||
return headers
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useState } from "react"
|
||||
|
||||
/** Copy text, falling back to execCommand for non-secure contexts (HTTP) */
|
||||
export async function copyText(text: string): Promise<boolean> {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
return true
|
||||
} catch {
|
||||
const textarea = document.createElement("textarea")
|
||||
textarea.value = text
|
||||
textarea.style.position = "fixed"
|
||||
textarea.style.left = "-9999px"
|
||||
textarea.style.opacity = "0"
|
||||
document.body.appendChild(textarea)
|
||||
try {
|
||||
textarea.select()
|
||||
return document.execCommand("copy")
|
||||
} catch {
|
||||
return false
|
||||
} finally {
|
||||
document.body.removeChild(textarea)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Copy text and show "copied" for a moment; onFail runs when it failed */
|
||||
export function useCopy(onFail?: () => void) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const copy = async (text: string) => {
|
||||
const ok = await copyText(text)
|
||||
if (!ok) onFail?.()
|
||||
setCopied(ok)
|
||||
setTimeout(() => setCopied(false), 1500)
|
||||
}
|
||||
return { copied, copy }
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
import { modelOfPage, pageElement } from "@/lib/diagram-pages"
|
||||
|
||||
/** What changed on one page between two versions of a diagram */
|
||||
export interface ChangeSummary {
|
||||
shapesAdded: number
|
||||
shapesRemoved: number
|
||||
shapesChanged: number
|
||||
edgesAdded: number
|
||||
edgesRemoved: number
|
||||
edgesChanged: number
|
||||
}
|
||||
|
||||
export interface DiagramDiff {
|
||||
summary: ChangeSummary
|
||||
/** Ids of cells that were added or changed (for highlighting) */
|
||||
touchedIds: string[]
|
||||
/** The diagram before had no shapes or connectors */
|
||||
fromScratch: boolean
|
||||
}
|
||||
|
||||
export const EMPTY_SUMMARY: ChangeSummary = {
|
||||
shapesAdded: 0,
|
||||
shapesRemoved: 0,
|
||||
shapesChanged: 0,
|
||||
edgesAdded: 0,
|
||||
edgesRemoved: 0,
|
||||
edgesChanged: 0,
|
||||
}
|
||||
|
||||
interface CellInfo {
|
||||
isEdge: boolean
|
||||
signature: string
|
||||
}
|
||||
|
||||
function parse(xml: string): Document | null {
|
||||
if (!xml?.trim()) return null
|
||||
const doc = new DOMParser().parseFromString(xml, "text/xml")
|
||||
return doc.querySelector("parsererror") ? null : doc
|
||||
}
|
||||
|
||||
/**
|
||||
* A page's mxGraphModel element, whatever wrapper the XML has: the page
|
||||
* with this id, else the first
|
||||
*/
|
||||
function pageModel(xml: string, pageId?: string | null): Element | null {
|
||||
const doc = parse(xml)
|
||||
if (!doc) return null
|
||||
const diagram = pageElement(doc, pageId)
|
||||
if (diagram) return modelOfPage(diagram)
|
||||
return doc.querySelector("mxGraphModel") ?? doc.documentElement
|
||||
}
|
||||
|
||||
// Values draw.io leaves out when it saves: the model may write them
|
||||
const DEFAULT_VALUES: Record<string, Record<string, string>> = {
|
||||
mxCell: {
|
||||
vertex: "0",
|
||||
edge: "0",
|
||||
connectable: "1",
|
||||
visible: "1",
|
||||
collapsed: "0",
|
||||
style: "",
|
||||
},
|
||||
mxGeometry: { x: "0", y: "0", width: "0", height: "0", relative: "0" },
|
||||
mxPoint: { x: "0", y: "0" },
|
||||
}
|
||||
// Numbers draw.io writes back in their shortest form ("40.0" is "40"), on
|
||||
// the elements that hold a position or size (a wrapper's "x" is the
|
||||
// user's own data, shown as written)
|
||||
const NUMBERS = new Set(["x", "y", "width", "height"])
|
||||
const GEOMETRY = new Set(["mxGeometry", "mxPoint", "mxRectangle"])
|
||||
|
||||
/**
|
||||
* A style as draw.io reads it (mxStylesheet.getCellStyle): entries apply in
|
||||
* order and empty ones do nothing; a leading ";" leaves the default out
|
||||
*/
|
||||
function normalStyle(style: string): string {
|
||||
const entries = style.split(";").filter((entry) => entry.trim() !== "")
|
||||
return (style.startsWith(";") ? ";" : "") + entries.join(";")
|
||||
}
|
||||
|
||||
/**
|
||||
* What a cell is, independent of how the XML was written: the same cell
|
||||
* saved by draw.io and written by the model can order attributes
|
||||
* differently, and draw.io drops values that are the default. Style
|
||||
* entries keep their order, which counts.
|
||||
*/
|
||||
function signatureOf(node: Element): string {
|
||||
const defaults = DEFAULT_VALUES[node.tagName] ?? {}
|
||||
const attrs = Array.from(node.attributes)
|
||||
.flatMap((a) => {
|
||||
let value = a.value
|
||||
// A cell's style (a wrapper's "style" is the user's own data)
|
||||
if (a.name === "style" && node.tagName === "mxCell") {
|
||||
value = normalStyle(value)
|
||||
} else if (
|
||||
GEOMETRY.has(node.tagName) &&
|
||||
NUMBERS.has(a.name) &&
|
||||
value.trim() !== ""
|
||||
) {
|
||||
const n = Number(value)
|
||||
if (Number.isFinite(n)) value = String(n)
|
||||
}
|
||||
if (defaults[a.name] === value) return []
|
||||
return [[a.name, value]]
|
||||
})
|
||||
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
||||
// As JSON: a value can hold any text, also "name=value" pairs
|
||||
return JSON.stringify([
|
||||
node.tagName,
|
||||
attrs,
|
||||
Array.from(node.children).map(signatureOf),
|
||||
])
|
||||
}
|
||||
|
||||
/** The cells of a page, layers included, with the element that holds each */
|
||||
function cellsIn(model: Element | null) {
|
||||
if (!model) return []
|
||||
return Array.from(model.getElementsByTagName("mxCell")).flatMap((cell) => {
|
||||
// Cells with links or custom data are wrapped; the wrapper holds the id
|
||||
const wrapper = cell.parentElement
|
||||
const isWrapped =
|
||||
wrapper?.tagName === "object" || wrapper?.tagName === "UserObject"
|
||||
const id = cell.getAttribute("id") || wrapper?.getAttribute("id")
|
||||
if (!id) return []
|
||||
return [{ id, cell, node: isWrapped && wrapper ? wrapper : cell }]
|
||||
})
|
||||
}
|
||||
|
||||
/** Shapes and connectors of one page (not the root and its layers) */
|
||||
function collectCells(
|
||||
xml: string,
|
||||
pageId?: string | null,
|
||||
): Map<string, CellInfo> {
|
||||
const cells = new Map<string, CellInfo>()
|
||||
for (const { id, cell, node } of cellsIn(pageModel(xml, pageId))) {
|
||||
if (id === "0" || cell.getAttribute("parent") === "0") continue
|
||||
cells.set(id, {
|
||||
isEdge: cell.getAttribute("edge") === "1",
|
||||
signature: signatureOf(node),
|
||||
})
|
||||
}
|
||||
return cells
|
||||
}
|
||||
|
||||
/** What changed on one page (the first when no id is given) */
|
||||
export function diffDiagrams(
|
||||
beforeXml: string,
|
||||
afterXml: string,
|
||||
pageId?: string | null,
|
||||
): DiagramDiff {
|
||||
const before = collectCells(beforeXml, pageId)
|
||||
const after = collectCells(afterXml, pageId)
|
||||
const summary: ChangeSummary = { ...EMPTY_SUMMARY }
|
||||
const touchedIds: string[] = []
|
||||
|
||||
for (const [id, cell] of after) {
|
||||
const old = before.get(id)
|
||||
if (!old) {
|
||||
touchedIds.push(id)
|
||||
if (cell.isEdge) summary.edgesAdded++
|
||||
else summary.shapesAdded++
|
||||
} else if (old.signature !== cell.signature) {
|
||||
touchedIds.push(id)
|
||||
if (cell.isEdge) summary.edgesChanged++
|
||||
else summary.shapesChanged++
|
||||
}
|
||||
}
|
||||
for (const [id, cell] of before) {
|
||||
if (after.has(id)) continue
|
||||
if (cell.isEdge) summary.edgesRemoved++
|
||||
else summary.shapesRemoved++
|
||||
}
|
||||
return { summary, touchedIds, fromScratch: before.size === 0 }
|
||||
}
|
||||
|
||||
// Where the view was scrolled to, saved with the page; not a change
|
||||
const VIEW_ATTRIBUTES = new Set(["dx", "dy"])
|
||||
|
||||
// A page setting written on one side only is draw.io's default being
|
||||
// filled in when the other side has that default; an empty list: any value
|
||||
// is a change. Settings not listed are not compared then, like the paper
|
||||
// size: a page without it keeps the canvas's (draw.io's readGraphState).
|
||||
const PAGE_DEFAULTS: Record<string, string[]> = {
|
||||
background: ["none"],
|
||||
backgroundImage: [],
|
||||
extFonts: [],
|
||||
math: ["0"],
|
||||
shadow: ["0"],
|
||||
page: ["1"],
|
||||
pageScale: ["1"],
|
||||
grid: ["1"],
|
||||
gridSize: ["10"],
|
||||
guides: ["1"],
|
||||
tooltips: ["1"],
|
||||
connect: ["1"],
|
||||
arrows: ["1"],
|
||||
fold: ["1"],
|
||||
}
|
||||
|
||||
// Settings draw.io reads as numbers (Editor.readGraphState): "10.0" is 10
|
||||
const PAGE_NUMBERS = new Set([
|
||||
"gridSize",
|
||||
"pageScale",
|
||||
"pageWidth",
|
||||
"pageHeight",
|
||||
])
|
||||
|
||||
function samePageSettings(a: Element, b: Element): boolean {
|
||||
const names = new Set(
|
||||
[...Array.from(a.attributes), ...Array.from(b.attributes)].map(
|
||||
(attr) => attr.name,
|
||||
),
|
||||
)
|
||||
const read = (page: Element, name: string) => {
|
||||
const value = page.getAttribute(name)
|
||||
if (value === null || !PAGE_NUMBERS.has(name) || !value.trim()) {
|
||||
return value
|
||||
}
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) ? String(n) : value
|
||||
}
|
||||
for (const name of names) {
|
||||
if (VIEW_ATTRIBUTES.has(name)) continue
|
||||
const va = read(a, name)
|
||||
const vb = read(b, name)
|
||||
if (va !== null && vb !== null) {
|
||||
if (va !== vb) return false
|
||||
continue
|
||||
}
|
||||
const defaults = PAGE_DEFAULTS[name]
|
||||
if (defaults && !defaults.includes((va ?? vb) as string)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Every cell of a page, layers included, and the order of each parent's
|
||||
* children (which shape is in front)
|
||||
*/
|
||||
function contentOf(model: Element | null) {
|
||||
const cells = new Map<string, string>()
|
||||
const children = new Map<string, string[]>()
|
||||
for (const { id, cell, node } of cellsIn(model)) {
|
||||
cells.set(id, signatureOf(node))
|
||||
const parent = cell.getAttribute("parent") ?? ""
|
||||
children.set(parent, [...(children.get(parent) ?? []), id])
|
||||
}
|
||||
return { cells, children }
|
||||
}
|
||||
|
||||
function sameContent(a: Element | null, b: Element | null): boolean {
|
||||
const ca = contentOf(a)
|
||||
const cb = contentOf(b)
|
||||
if (ca.cells.size !== cb.cells.size) return false
|
||||
for (const [id, signature] of ca.cells) {
|
||||
if (cb.cells.get(id) !== signature) return false
|
||||
}
|
||||
for (const [parent, ids] of ca.children) {
|
||||
if (cb.children.get(parent)?.join("\n") !== ids.join("\n")) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* File variables (%name% placeholders) as draw.io reads them, from JSON:
|
||||
* the same names and values in any order; none is the same as "{}"
|
||||
*/
|
||||
export function sameFileVars(a: string | null, b: string | null): boolean {
|
||||
if (a === b) return true
|
||||
try {
|
||||
// By name: names are unique, and a pair's text can look like another's
|
||||
const sorted = (vars: string | null) =>
|
||||
JSON.stringify(
|
||||
Object.entries(JSON.parse(vars ?? "{}")).sort(([a], [b]) =>
|
||||
a < b ? -1 : a > b ? 1 : 0,
|
||||
),
|
||||
)
|
||||
return sorted(a) === sorted(b)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two documents hold the same pages (names, cells, their order),
|
||||
* page settings and file variables
|
||||
*/
|
||||
export function isSameDocument(a: string, b: string): boolean {
|
||||
const pagesOf = (doc: Document) => {
|
||||
const diagrams = Array.from(doc.getElementsByTagName("diagram"))
|
||||
if (diagrams.length === 0) {
|
||||
return [{ name: null, model: doc.querySelector("mxGraphModel") }]
|
||||
}
|
||||
return diagrams.map((d) => ({
|
||||
name: d.getAttribute("name"),
|
||||
model: modelOfPage(d),
|
||||
}))
|
||||
}
|
||||
const docA = parse(a)
|
||||
const docB = parse(b)
|
||||
if (!docA || !docB) return a === b
|
||||
const varsOf = (doc: Document) =>
|
||||
doc.documentElement.nodeName === "mxfile"
|
||||
? doc.documentElement.getAttribute("vars")
|
||||
: null
|
||||
if (!sameFileVars(varsOf(docA), varsOf(docB))) return false
|
||||
const pagesA = pagesOf(docA)
|
||||
const pagesB = pagesOf(docB)
|
||||
if (pagesA.length !== pagesB.length) return false
|
||||
return pagesA.every((pageA, i) => {
|
||||
const pageB = pagesB[i]
|
||||
if (pageA.name !== null && pageB.name !== null) {
|
||||
if (pageA.name !== pageB.name) return false
|
||||
}
|
||||
if (pageA.model && pageB.model) {
|
||||
if (!samePageSettings(pageA.model, pageB.model)) return false
|
||||
}
|
||||
return sameContent(pageA.model, pageB.model)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* The page the AI works on is the page the user is viewing. These helpers
|
||||
* read that page out of a multi-page document and write a drawing into it
|
||||
* while the other pages stay as they are. A page id that matches no page
|
||||
* (or none at all, as with an external draw.io that cannot tell us) means
|
||||
* the first page, which is what the app always used before.
|
||||
*/
|
||||
|
||||
import { decompressPageContent } from "@/packages/mcp-server/src/load-diagram.ts"
|
||||
import {
|
||||
BLANK_MXFILE,
|
||||
type PageSelector,
|
||||
} from "@/packages/mcp-server/src/pages.ts"
|
||||
|
||||
function parse(xml: string): Document | null {
|
||||
if (!xml?.trim()) return null
|
||||
const doc = new DOMParser().parseFromString(xml, "text/xml")
|
||||
return doc.querySelector("parsererror") ? null : doc
|
||||
}
|
||||
|
||||
/** The <diagram> the AI works on: the one with this id, else the first */
|
||||
export function pageElement(
|
||||
doc: Document,
|
||||
pageId: string | null | undefined,
|
||||
): Element | null {
|
||||
const diagrams = Array.from(doc.getElementsByTagName("diagram"))
|
||||
if (diagrams.length === 0) return null
|
||||
return (
|
||||
(pageId &&
|
||||
diagrams.find(
|
||||
(diagram) => diagram.getAttribute("id") === pageId,
|
||||
)) ||
|
||||
diagrams[0]
|
||||
)
|
||||
}
|
||||
|
||||
/** A page's mxGraphModel element, inflated when the page is compressed */
|
||||
export function modelOfPage(diagram: Element): Element | null {
|
||||
const model = diagram.querySelector("mxGraphModel")
|
||||
if (model) return model
|
||||
const inflated = decompressPageContent(diagram.textContent || "")
|
||||
if (!inflated) return null
|
||||
return parse(inflated)?.querySelector("mxGraphModel") ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Selector for editDiagram and applyDiagramOperations: the page with this
|
||||
* id when the document has it, else their default (the first page)
|
||||
*/
|
||||
export function pageSelectorFor(
|
||||
xml: string,
|
||||
pageId: string | null | undefined,
|
||||
): PageSelector {
|
||||
if (!pageId) return {}
|
||||
const doc = parse(xml)
|
||||
const found = doc
|
||||
? Array.from(doc.getElementsByTagName("diagram")).some(
|
||||
(diagram) => diagram.getAttribute("id") === pageId,
|
||||
)
|
||||
: false
|
||||
return found ? { page_id: pageId } : {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's mxGraphModel as XML. A bare mxGraphModel is returned as it
|
||||
* is; null when the XML does not parse or has no model.
|
||||
*/
|
||||
export function pageModelXml(
|
||||
xml: string,
|
||||
pageId: string | null | undefined,
|
||||
): string | null {
|
||||
const doc = parse(xml)
|
||||
if (!doc) return null
|
||||
const root = doc.documentElement
|
||||
if (root.nodeName === "mxGraphModel") return xml
|
||||
if (root.nodeName !== "mxfile") return null
|
||||
const diagram = pageElement(doc, pageId)
|
||||
const model = diagram ? modelOfPage(diagram) : null
|
||||
return model ? new XMLSerializer().serializeToString(model) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The document with one page's content replaced by this model. The page
|
||||
* keeps its id and name, the other pages and the file's attributes (its
|
||||
* variables) stay. Without a document to put the page in, the blank
|
||||
* one-page file is used.
|
||||
*/
|
||||
export function replacePageModel(
|
||||
fileXml: string,
|
||||
pageId: string | null | undefined,
|
||||
modelXml: string,
|
||||
): string {
|
||||
const model = parse(modelXml)
|
||||
if (model?.documentElement.nodeName !== "mxGraphModel") {
|
||||
throw new Error("replacePageModel needs an <mxGraphModel>")
|
||||
}
|
||||
let doc = parse(fileXml)
|
||||
if (doc?.documentElement.nodeName !== "mxfile") doc = parse(BLANK_MXFILE)
|
||||
let diagram = pageElement(doc as Document, pageId)
|
||||
if (!diagram) {
|
||||
doc = parse(BLANK_MXFILE)
|
||||
diagram = pageElement(doc as Document, null)
|
||||
}
|
||||
const target = diagram as Element
|
||||
while (target.firstChild) target.removeChild(target.firstChild)
|
||||
target.appendChild(
|
||||
(doc as Document).importNode(model.documentElement, true),
|
||||
)
|
||||
return new XMLSerializer().serializeToString(doc as Document)
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a drawn diagram goes. One page's worth (bare cells wrapped by
|
||||
* prepareNewDiagram, or a one-page file) replaces the AI's page of the
|
||||
* canvas file; file variables the drawn file sets replace the canvas
|
||||
* file's. A file with several pages replaces the whole document: the model
|
||||
* wrote the pages on purpose.
|
||||
*/
|
||||
export function placeOnPage(
|
||||
drawnXml: string,
|
||||
canvasXml: string,
|
||||
pageId: string | null | undefined,
|
||||
): string {
|
||||
const doc = parse(drawnXml)
|
||||
const drawnFile =
|
||||
doc?.documentElement.nodeName === "mxfile" ? doc.documentElement : null
|
||||
if (drawnFile && drawnFile.getElementsByTagName("diagram").length > 1) {
|
||||
return drawnXml
|
||||
}
|
||||
const model = pageModelXml(drawnXml, null)
|
||||
if (!model) return drawnXml
|
||||
const placed = replacePageModel(canvasXml, pageId, model)
|
||||
const vars = drawnFile?.getAttribute("vars")
|
||||
if (vars === null || vars === undefined) return placed
|
||||
const result = parse(placed) as Document
|
||||
result.documentElement.setAttribute("vars", vars)
|
||||
return new XMLSerializer().serializeToString(result)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
export const DRAWIO_THEMES = [
|
||||
"kennedy",
|
||||
"atlas",
|
||||
"dark",
|
||||
"min",
|
||||
"sketch",
|
||||
"simple",
|
||||
] as const
|
||||
|
||||
export type DrawioTheme = (typeof DRAWIO_THEMES)[number]
|
||||
|
||||
export function isDrawioTheme(value: unknown): value is DrawioTheme {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
(DRAWIO_THEMES as readonly string[]).includes(value)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { getAssetUrl } from "@/lib/base-path"
|
||||
import type { Locale } from "@/lib/i18n/config"
|
||||
import { BLANK_MXFILE } from "@/packages/mcp-server/src/pages.ts"
|
||||
|
||||
/** External draw.io configured at build time (cross-origin, limited features) */
|
||||
const EXTERNAL_DRAWIO_URL = process.env.NEXT_PUBLIC_DRAWIO_BASE_URL || ""
|
||||
|
||||
/**
|
||||
* URL of the draw.io editor iframe. By default this is the copy bundled in
|
||||
* public/drawio, served from our own origin.
|
||||
*/
|
||||
export function getDrawioSrc({
|
||||
lang,
|
||||
isElectron,
|
||||
dark,
|
||||
}: {
|
||||
lang: Locale
|
||||
isElectron: boolean
|
||||
dark: boolean
|
||||
}): string {
|
||||
// index.html: Next.js does not serve directory indexes
|
||||
const base =
|
||||
EXTERNAL_DRAWIO_URL ||
|
||||
`${window.location.origin}${getAssetUrl("/drawio/index.html")}`
|
||||
const url = new URL(base)
|
||||
const params: Record<string, string> = {
|
||||
embed: "1",
|
||||
proto: "json",
|
||||
configure: "1",
|
||||
ui: "simple",
|
||||
spin: "0",
|
||||
libraries: "0",
|
||||
noSaveBtn: "1",
|
||||
noExitBtn: "1",
|
||||
saveAndExit: "0",
|
||||
// draw.io's own dark mode (switched in place later when the editor
|
||||
// can be driven directly)
|
||||
dark: dark ? "1" : "0",
|
||||
// draw.io names Traditional Chinese "zh-tw"
|
||||
lang: lang === "zh-Hant" ? "zh-tw" : lang,
|
||||
}
|
||||
// No calls to external services from the desktop app
|
||||
if (isElectron && !EXTERNAL_DRAWIO_URL) params.offline = "1"
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, value)
|
||||
}
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the page (a white sheet with a grid) unless the diagram says
|
||||
* otherwise. AI output usually has a bare <mxGraphModel>, and draw.io's
|
||||
* simple UI would then show neither page nor grid.
|
||||
*/
|
||||
export function withPageDefaults(xml: string): string {
|
||||
return xml.replace(
|
||||
/<mxGraphModel\b([^>]*?)(\/?)>/g,
|
||||
(_match, attrs, slash) => {
|
||||
let next = attrs as string
|
||||
if (!/\spage\s*=/.test(next)) next += ' page="1"'
|
||||
if (!/\sgrid\s*=/.test(next)) next += ' grid="1"'
|
||||
if (!/\sgridSize\s*=/.test(next)) next += ' gridSize="10"'
|
||||
return `<mxGraphModel${next}${slash}>`
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** Empty document loaded when draw.io starts */
|
||||
export const EMPTY_DRAWIO_DOCUMENT = withPageDefaults(BLANK_MXFILE)
|
||||
|
||||
/**
|
||||
* Editor defaults sent with draw.io's configure message. The simple UI turns
|
||||
* page view off for new diagrams; keep the white page on the canvas, as in
|
||||
* the classic UI.
|
||||
*/
|
||||
export const DRAWIO_CONFIG = {
|
||||
defaultPageVisible: true,
|
||||
defaultGridEnabled: true,
|
||||
// A loaded diagram leaves the focus where it is (draw.io focuses its
|
||||
// window otherwise, and keys typed for the chat would go to the canvas)
|
||||
noAutoFocus: true,
|
||||
}
|
||||
|
||||
/**
|
||||
* CSS injected into draw.io: the table around the sheet and its toolbar in
|
||||
* light mode. Dark mode keeps draw.io's own colors: the rules only match
|
||||
* while draw.io is light (it puts geDarkMode on the body), so they need no
|
||||
* change when the theme switches.
|
||||
*/
|
||||
export const DRAWIO_CSS = `
|
||||
body:not(.geDarkMode) {
|
||||
--workspace-color: #f4f5f7;
|
||||
--focus-color: #14181d;
|
||||
}
|
||||
body:not(.geDarkMode) .geDiagramContainer { background-color: #f4f5f7; }
|
||||
body:not(.geDarkMode) .geBackgroundPage { box-shadow: 0 1px 2px rgba(20,24,29,.08), 0 12px 32px -12px rgba(20,24,29,.18) !important; }
|
||||
body:not(.geDarkMode) .geSimpleMainMenu { border-bottom: 1px solid #e4e7eb !important; box-shadow: none !important; }
|
||||
.geSidebarContainer[style*="width: 0px"] { border: none !important; }
|
||||
`
|
||||
@@ -0,0 +1,756 @@
|
||||
/**
|
||||
* Direct access to the draw.io editor running in our same-origin iframe.
|
||||
*
|
||||
* draw.io has no public JavaScript API for embedders; everything here uses
|
||||
* its internal objects (EditorUi, mxGraph). Every call checks that what it
|
||||
* needs exists, so a draw.io update that renames something turns the feature
|
||||
* off (with a console warning) instead of breaking the page.
|
||||
*
|
||||
* With an external draw.io (cross-origin) none of this is available and the
|
||||
* app uses the postMessage protocol only.
|
||||
*/
|
||||
import { isSameDocument, sameFileVars } from "@/lib/diagram-diff"
|
||||
import { hasCells } from "@/packages/mcp-server/src/pages.ts"
|
||||
import { type SelectedCell, useCanvasStore } from "@/stores/canvas-store"
|
||||
|
||||
type EditorUi = any
|
||||
type FrameWindow = any
|
||||
|
||||
let ui: EditorUi | null = null
|
||||
let win: FrameWindow | null = null
|
||||
let detachListeners: (() => void) | null = null
|
||||
const warned = new Set<string>()
|
||||
// Keyboard shortcuts of the app that must also work while focus is inside
|
||||
// the draw.io iframe (keydown events there never reach our window)
|
||||
let appShortcutHandler: ((event: KeyboardEvent) => boolean) | null = null
|
||||
|
||||
/** The handler returns true when it handled the key */
|
||||
export function setAppShortcutHandler(
|
||||
handler: ((event: KeyboardEvent) => boolean) | null,
|
||||
) {
|
||||
appShortcutHandler = handler
|
||||
}
|
||||
|
||||
function warnOnce(key: string, message: string) {
|
||||
if (warned.has(key)) return
|
||||
warned.add(key)
|
||||
console.warn(`[drawio] ${message}`)
|
||||
}
|
||||
|
||||
export function attachEditor(editorUi: EditorUi, frameWindow: FrameWindow) {
|
||||
if (ui === editorUi) return
|
||||
detachEditor()
|
||||
ui = editorUi
|
||||
win = frameWindow
|
||||
detachListeners = installListeners()
|
||||
keepPanelsOnResize()
|
||||
closeSidePanels()
|
||||
softenGrid()
|
||||
useCanvasStore.getState().set({ hasEditor: true })
|
||||
syncAll()
|
||||
}
|
||||
|
||||
// draw.io's simple UI opens or closes its format panel and shape library
|
||||
// when its window crosses a width; the user opens them from its toolbar, so
|
||||
// a resize (the chat panel sliding, a narrow window) must leave them alone.
|
||||
// windowResized only toggles them when it knows the previous width.
|
||||
function keepPanelsOnResize() {
|
||||
const original = ui?.windowResized
|
||||
if (typeof original !== "function" || original.naiWrapped) return
|
||||
const wrapped = function (this: any, ...args: unknown[]) {
|
||||
this.lastWindowWidth = null
|
||||
return original.apply(this, args)
|
||||
}
|
||||
wrapped.naiWrapped = true
|
||||
ui.windowResized = wrapped
|
||||
}
|
||||
|
||||
// draw.io's grid (#e6e6e6 every 10 px) is busy behind pale shapes
|
||||
function softenGrid() {
|
||||
const view = graph()?.view
|
||||
if (!view) return
|
||||
try {
|
||||
view.gridColor = "#eceef1"
|
||||
view.validateBackground()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// draw.io opens its format panel and shape library on start, which leaves
|
||||
// little room for the diagram next to the chat panel; its toolbar opens them
|
||||
function closeSidePanels() {
|
||||
try {
|
||||
if (isFormatPanelOpen()) ui.actions?.get?.("format")?.funct()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
if (ui.sidebarWindow?.window?.isVisible?.()) {
|
||||
ui.sidebarWindow.window.setVisible(false)
|
||||
} else if (ui.isShapesPanelVisible?.()) {
|
||||
// At once, as the end of draw.io's toggleShapesPanel does: its
|
||||
// slide takes a moment, and a diagram loaded meanwhile is
|
||||
// centered in the narrower canvas
|
||||
ui.hsplitPosition = 0
|
||||
ui.refresh()
|
||||
ui.fireEvent?.(new win.mxEventObject("shapesPanelChanged"))
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function detachEditor() {
|
||||
detachListeners?.()
|
||||
detachListeners = null
|
||||
clearHighlights()
|
||||
ui = null
|
||||
win = null
|
||||
previewBase = null
|
||||
useCanvasStore.getState().set({
|
||||
hasEditor: false,
|
||||
selection: [],
|
||||
selectionRect: null,
|
||||
isDrawioPopupOpen: false,
|
||||
})
|
||||
}
|
||||
|
||||
function graph() {
|
||||
return ui?.editor?.graph ?? null
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Replacing the diagram (AI changes)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Diagram before the current AI turn started streaming. Previews are applied
|
||||
// without undo history; the final result replaces this base as one undo step.
|
||||
let previewBase: string | null = null
|
||||
|
||||
function currentFileXml(): string | null {
|
||||
try {
|
||||
const node = ui.getXmlFileData(null, null, true)
|
||||
return win.mxUtils.getXml(node)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function withoutUndo(fn: () => void) {
|
||||
const manager = ui?.editor?.undoManager
|
||||
if (!manager?.undoableEditHappened) {
|
||||
fn()
|
||||
return
|
||||
}
|
||||
const original = manager.undoableEditHappened
|
||||
manager.undoableEditHappened = () => {}
|
||||
try {
|
||||
fn()
|
||||
} finally {
|
||||
manager.undoableEditHappened = original
|
||||
}
|
||||
}
|
||||
|
||||
/** Id of the page on the canvas, when draw.io has pages */
|
||||
function currentPageId(): string | null {
|
||||
const id = ui?.currentPage?.getId?.()
|
||||
return id === undefined || id === null ? null : String(id)
|
||||
}
|
||||
|
||||
/** A page's <mxGraphModel> as XML, inflated when the page is compressed */
|
||||
function modelXmlOf(diagram: Element): string | null {
|
||||
const model = diagram.getElementsByTagName("mxGraphModel")[0]
|
||||
if (model) return new XMLSerializer().serializeToString(model)
|
||||
try {
|
||||
const text = diagram.textContent?.trim()
|
||||
const inflated = text ? win?.Graph?.decompress?.(text) : null
|
||||
return typeof inflated === "string" &&
|
||||
inflated.includes("<mxGraphModel")
|
||||
? inflated
|
||||
: null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* replaceDiagramData replaces the current page with one <mxGraphModel>:
|
||||
* the document's page with the canvas page's id, or its only page
|
||||
*/
|
||||
function pageModelOf(xml: string): string | null {
|
||||
const doc = new DOMParser().parseFromString(xml, "text/xml")
|
||||
if (doc.querySelector("parsererror")) return null
|
||||
const root = doc.documentElement
|
||||
if (root.nodeName === "mxGraphModel") return xml
|
||||
if (root.nodeName !== "mxfile") return null
|
||||
const diagrams = Array.from(root.getElementsByTagName("diagram"))
|
||||
const id = currentPageId()
|
||||
const diagram =
|
||||
diagrams.length === 1
|
||||
? diagrams[0]
|
||||
: diagrams.find((d) => d.getAttribute("id") === id)
|
||||
return diagram ? modelXmlOf(diagram) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The document without the current page, for comparing the other pages.
|
||||
* null when the XML is not a document; "" for a single page.
|
||||
*/
|
||||
function withoutCurrentPage(xml: string | null): string | null {
|
||||
if (!xml) return null
|
||||
const doc = new DOMParser().parseFromString(xml, "text/xml")
|
||||
if (doc.querySelector("parsererror")) return null
|
||||
const root = doc.documentElement
|
||||
if (root.nodeName === "mxGraphModel") return ""
|
||||
if (root.nodeName !== "mxfile") return null
|
||||
const diagrams = Array.from(root.getElementsByTagName("diagram"))
|
||||
if (diagrams.length <= 1) return ""
|
||||
const id = currentPageId()
|
||||
for (const diagram of diagrams) {
|
||||
if (diagram.getAttribute("id") === id) root.removeChild(diagram)
|
||||
}
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
|
||||
/**
|
||||
* The document changes the current page only: its other pages are the
|
||||
* canvas's (same names, cells and page settings; draw.io fills in settings
|
||||
* a loaded file left out, so the text can differ)
|
||||
*/
|
||||
function otherPagesSame(xml: string): boolean {
|
||||
const theirs = withoutCurrentPage(xml)
|
||||
if (theirs === null) return false
|
||||
const pageCount = Array.isArray(ui.pages) ? ui.pages.length : 1
|
||||
if (pageCount <= 1 && theirs === "") return true
|
||||
const ours = withoutCurrentPage(currentFileXml())
|
||||
if (ours === null || ours === "" || theirs === "") return false
|
||||
return isSameDocument(theirs, ours)
|
||||
}
|
||||
|
||||
function replace(xml: string) {
|
||||
const model = pageModelOf(xml)
|
||||
if (!model || typeof ui?.replaceDiagramData !== "function") {
|
||||
throw new Error("Diagram can't be replaced in place")
|
||||
}
|
||||
ui.replaceDiagramData(model)
|
||||
}
|
||||
|
||||
/** No shapes on any layer */
|
||||
function isEmptyModel(): boolean {
|
||||
const g = graph()
|
||||
const root = g?.model.getRoot()
|
||||
if (!root) return true
|
||||
for (let i = 0; i < g.model.getChildCount(root); i++) {
|
||||
if (g.model.getChildCount(g.model.getChildAt(root, i)) > 0) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Whether a page has shapes; layers (cells under the root) are none */
|
||||
function hasShapes(xml: string): boolean {
|
||||
const model = pageModelOf(xml)
|
||||
if (model === null) return hasCells(xml)
|
||||
const cells = new DOMParser()
|
||||
.parseFromString(model, "text/xml")
|
||||
.getElementsByTagName("mxCell")
|
||||
return Array.from(cells).some((cell) => {
|
||||
const parent = cell.getAttribute("parent")
|
||||
return parent !== null && parent !== "0"
|
||||
})
|
||||
}
|
||||
|
||||
// Page settings draw.io applies on a full load only: replacing the page in
|
||||
// place (Editor.readGraphState) keeps the old ones. (Its adaptive colors and
|
||||
// theme stay too: a diagram the AI writes does not set them.)
|
||||
function hasLoadOnlySettings(model: string): boolean {
|
||||
const page = new DOMParser().parseFromString(
|
||||
model,
|
||||
"text/xml",
|
||||
).documentElement
|
||||
return (
|
||||
page.hasAttribute("backgroundImage") ||
|
||||
page.hasAttribute("extFonts") ||
|
||||
page.getAttribute("math") === "1" ||
|
||||
page.getAttribute("shadow") === "1"
|
||||
)
|
||||
}
|
||||
|
||||
function canvasHasLoadOnlySettings(): boolean {
|
||||
const g = graph()
|
||||
return (
|
||||
!!g &&
|
||||
(!!g.backgroundImage ||
|
||||
!!g.mathEnabled ||
|
||||
!!g.shadowVisible ||
|
||||
(g.extFonts?.length ?? 0) > 0)
|
||||
)
|
||||
}
|
||||
|
||||
/** The file variables (%name% placeholders) a document sets, if any */
|
||||
function fileVars(xml: string): string | null {
|
||||
const root = new DOMParser().parseFromString(
|
||||
xml,
|
||||
"text/xml",
|
||||
).documentElement
|
||||
return root?.nodeName === "mxfile" ? root.getAttribute("vars") : null
|
||||
}
|
||||
|
||||
/** Can this diagram go through the editor (with undo) instead of a full load? */
|
||||
export function canReplaceDiagram(xml: string): boolean {
|
||||
if (!ui) return false
|
||||
if (typeof ui.replaceDiagramData !== "function") {
|
||||
warnOnce("replace", "replaceDiagramData not found, using full loads")
|
||||
return false
|
||||
}
|
||||
// Replacing changes the current page only: a document whose other
|
||||
// pages differ from the canvas's loads in full
|
||||
if (!otherPagesSame(xml)) return false
|
||||
// Replacing the page keeps the file's variables: other ones, or none
|
||||
// over a file with some, load in full
|
||||
if (
|
||||
!sameFileVars(
|
||||
fileVars(xml),
|
||||
ui.fileNode?.getAttribute?.("vars") ?? null,
|
||||
)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
const model = pageModelOf(xml)
|
||||
// A document with them, or replacing one with them, loads in full
|
||||
return (
|
||||
model !== null &&
|
||||
!hasLoadOnlySettings(model) &&
|
||||
!canvasHasLoadOnlySettings()
|
||||
)
|
||||
}
|
||||
|
||||
/** Show a streaming preview without touching the undo history */
|
||||
export function previewDiagram(xml: string) {
|
||||
if (previewBase === null) previewBase = currentFileXml() ?? ""
|
||||
const wasEmpty = isEmptyModel()
|
||||
withoutUndo(() => replace(xml))
|
||||
if (wasEmpty) fitDiagram()
|
||||
}
|
||||
|
||||
/**
|
||||
* Name and id the document gives the canvas page: of its page with that
|
||||
* id, or of its only page
|
||||
*/
|
||||
function pageOf(xml: string): { name: string | null; id: string | null } {
|
||||
const doc = new DOMParser().parseFromString(xml, "text/xml")
|
||||
const diagrams =
|
||||
doc.documentElement?.nodeName === "mxfile"
|
||||
? Array.from(doc.getElementsByTagName("diagram"))
|
||||
: []
|
||||
const id = currentPageId()
|
||||
const diagram =
|
||||
diagrams.length === 1
|
||||
? diagrams[0]
|
||||
: diagrams.find((d) => d.getAttribute("id") === id)
|
||||
return {
|
||||
name: diagram?.getAttribute("name") || null,
|
||||
id: diagram?.getAttribute("id") || null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A change of the page's id for draw.io's undo history (it has none of its
|
||||
* own): execute swaps the ids, as draw.io's RenamePage does with names
|
||||
*/
|
||||
function changePageId(page: any, id: string) {
|
||||
let other = id
|
||||
return {
|
||||
execute() {
|
||||
const current = page.getId()
|
||||
page.node.setAttribute("id", other)
|
||||
other = current
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the final AI result (or a restored version) as a single undo step,
|
||||
* page name and id included: the page gets the document's id, as a full
|
||||
* load would give it (links to the page use it). The view is fitted only
|
||||
* when the canvas was empty, so a restore keeps the user's zoom.
|
||||
*/
|
||||
export function commitDiagram(xml: string) {
|
||||
const wasEmpty =
|
||||
isEmptyModel() || (previewBase !== null && !hasShapes(previewBase))
|
||||
const base = previewBase ? pageModelOf(previewBase) : null
|
||||
previewBase = null
|
||||
// Undo goes back to the diagram before streaming started. draw.io's
|
||||
// ReplaceDiagram change keeps the document it replaced for undo: hand it
|
||||
// that diagram, so the canvas changes once. (Putting it back on the
|
||||
// canvas first would also send it to the app, after the result.)
|
||||
const ReplaceDiagram = win?.ReplaceDiagram
|
||||
const parse = (model: string) => win.mxUtils.parseXml(model).documentElement
|
||||
const direct = typeof ReplaceDiagram === "function" && !!win?.mxUtils
|
||||
if (base && !direct) withoutUndo(() => replace(base))
|
||||
const model = graph()?.model
|
||||
const { name, id } = pageOf(xml)
|
||||
const page = ui?.currentPage
|
||||
model?.beginUpdate()
|
||||
try {
|
||||
const next = pageModelOf(xml)
|
||||
if (direct && next) {
|
||||
const change = new ReplaceDiagram(ui, parse(next))
|
||||
model.execute(change)
|
||||
if (base) change.data = parse(base)
|
||||
} else {
|
||||
replace(xml)
|
||||
}
|
||||
if (name && page && win?.RenamePage && page.getName?.() !== name) {
|
||||
model.execute(new win.RenamePage(ui, page, name))
|
||||
}
|
||||
if (id && page?.node && page.getId?.() !== id) {
|
||||
model.execute(changePageId(page, id))
|
||||
}
|
||||
} finally {
|
||||
model?.endUpdate()
|
||||
}
|
||||
if (wasEmpty) fitDiagram()
|
||||
}
|
||||
|
||||
/** Throw away the preview and go back to the given diagram */
|
||||
export function revertPreview(targetXml: string) {
|
||||
previewBase = null
|
||||
withoutUndo(() => replace(targetXml))
|
||||
}
|
||||
|
||||
/** Forget the preview base (new user turn) without changing the canvas */
|
||||
export function resetPreview() {
|
||||
previewBase = null
|
||||
}
|
||||
|
||||
/** Show the page with this id; false when draw.io has no such page */
|
||||
export function selectPage(pageId: string): boolean {
|
||||
try {
|
||||
const page = ui?.getPageById?.(pageId)
|
||||
if (!page || typeof ui.selectPage !== "function") return false
|
||||
if (ui.currentPage !== page) ui.selectPage(page, true)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// When the app last fitted the diagram on its own; a canvas resize right
|
||||
// after (the chat panel sliding in) fits again, unless the user zoomed since
|
||||
let lastAutoFitAt = 0
|
||||
|
||||
// True while fitDiagram runs: its own zoom change is not the user's
|
||||
let fitting = false
|
||||
|
||||
/** The zoom changed: if the user did it, a later resize keeps their view */
|
||||
function zoomChanged() {
|
||||
if (!fitting) lastAutoFitAt = 0
|
||||
}
|
||||
|
||||
/** Fit again if the last automatic fit just happened (layout still moving) */
|
||||
export function refitIfRecent(windowMs = 1500) {
|
||||
if (Date.now() - lastAutoFitAt < windowMs) {
|
||||
fitDiagram()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Room around a fitted diagram (half of this on each side)
|
||||
const FIT_BORDER = 128
|
||||
|
||||
/** Fit the shapes (not the whole page) into the canvas, at most at 100% */
|
||||
function fitDiagram() {
|
||||
const g = graph()
|
||||
if (!g) return
|
||||
fitting = true
|
||||
try {
|
||||
const b = g.getGraphBounds()
|
||||
const { scale, translate } = g.view
|
||||
if (b && b.width > 0 && b.height > 0 && win?.mxRectangle) {
|
||||
const model = new win.mxRectangle(
|
||||
b.x / scale - translate.x,
|
||||
b.y / scale - translate.y,
|
||||
b.width / scale,
|
||||
b.height / scale,
|
||||
)
|
||||
g.fitWindow(model, FIT_BORDER, 1)
|
||||
} else if (ui?.actions?.get?.("fitWindow")) {
|
||||
ui.actions.get("fitWindow").funct()
|
||||
if (g.view.scale > 1) g.zoomTo(1, true)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
fitting = false
|
||||
}
|
||||
// After the zoom events of the fit itself
|
||||
lastAutoFitAt = Date.now()
|
||||
}
|
||||
|
||||
/** The canvas changed width: keep what was in the middle in the middle */
|
||||
export function keepCenter(oldWidth: number, newWidth: number) {
|
||||
const container = graph()?.container
|
||||
if (!container || !oldWidth || !newWidth) return
|
||||
container.scrollLeft += (oldWidth - newWidth) / 2
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlighting what the AI changed
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let highlights: any[] = []
|
||||
|
||||
export function clearHighlights() {
|
||||
for (const h of highlights) {
|
||||
try {
|
||||
h.destroy()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
highlights = []
|
||||
}
|
||||
|
||||
// Outline of changed shapes: dark enough to show on white paper and on
|
||||
// draw.io's pale fills (yellow ones included)
|
||||
const HIGHLIGHT_OUTLINE = "#a86b00"
|
||||
|
||||
/**
|
||||
* Marks changed cells: shapes get a soft halo plus a thin outline,
|
||||
* connectors only the outline (a halo would cover their labels and arrows)
|
||||
*/
|
||||
export function highlightCells(ids: string[], color: string) {
|
||||
clearHighlights()
|
||||
const g = graph()
|
||||
if (!g || !win?.mxCellHighlight || ids.length === 0) return
|
||||
const add = (
|
||||
state: any,
|
||||
stroke: string,
|
||||
width: number,
|
||||
opacity: number,
|
||||
) => {
|
||||
const h = new win.mxCellHighlight(g, stroke, width)
|
||||
h.opacity = opacity
|
||||
h.highlight(state)
|
||||
highlights.push(h)
|
||||
}
|
||||
for (const id of ids.slice(0, 200)) {
|
||||
const cell = g.model.getCell(id)
|
||||
const state = cell ? g.view.getState(cell) : null
|
||||
if (!state) continue
|
||||
if (!g.model.isEdge(cell)) add(state, color, 8, 18)
|
||||
add(state, HIGHLIGHT_OUTLINE, 2, 100)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Selection
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function cellLabel(cell: any): string {
|
||||
const g = graph()
|
||||
let text = ""
|
||||
try {
|
||||
text = g?.convertValueToString(cell) ?? ""
|
||||
} catch {
|
||||
text = ""
|
||||
}
|
||||
// Labels can contain HTML
|
||||
text = text
|
||||
.replace(/<br\s*\/?>/gi, " ")
|
||||
.replace(/<[^>]+>/g, "")
|
||||
.replace(/ /g, " ")
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
return text.length > 80 ? `${text.slice(0, 80)}…` : text
|
||||
}
|
||||
|
||||
function readSelection(): SelectedCell[] {
|
||||
const g = graph()
|
||||
if (!g) return []
|
||||
return (g.getSelectionCells() as any[])
|
||||
.filter((cell) => cell?.id)
|
||||
.map((cell) => ({
|
||||
id: String(cell.id),
|
||||
label: cellLabel(cell),
|
||||
isEdge: !!g.model.isEdge(cell),
|
||||
}))
|
||||
}
|
||||
|
||||
function readSelectionRect() {
|
||||
const g = graph()
|
||||
if (!g || g.isSelectionEmpty()) return null
|
||||
const cells = g.getSelectionCells()
|
||||
const bounds = g.view.getBounds(cells)
|
||||
if (!bounds) return null
|
||||
const container = g.container as HTMLElement
|
||||
const rect = container.getBoundingClientRect()
|
||||
return {
|
||||
x: rect.left + bounds.x - container.scrollLeft,
|
||||
y: rect.top + bounds.y - container.scrollTop,
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pages
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function readPages() {
|
||||
const pages = (ui?.pages ?? []) as any[]
|
||||
return pages.map((page, index) => ({
|
||||
id: String(page.getId?.() ?? index),
|
||||
name: String(page.getName?.() ?? `Page-${index + 1}`),
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Keeping the store in sync
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function syncSelectionRect() {
|
||||
useCanvasStore.getState().set({ selectionRect: readSelectionRect() })
|
||||
}
|
||||
|
||||
function syncAll() {
|
||||
if (!ui) return
|
||||
const g = graph()
|
||||
useCanvasStore.getState().set({
|
||||
pages: readPages(),
|
||||
currentPageId: ui.currentPage?.getId
|
||||
? String(ui.currentPage.getId())
|
||||
: null,
|
||||
selection: readSelection(),
|
||||
selectionRect: readSelectionRect(),
|
||||
isFreehand: !!g?.freehand?.isDrawing?.(),
|
||||
})
|
||||
}
|
||||
|
||||
function isFormatPanelOpen(): boolean {
|
||||
try {
|
||||
if (typeof ui.isFormatPanelVisible === "function") {
|
||||
return !!ui.isFormatPanelVisible()
|
||||
}
|
||||
return (ui.formatWidth ?? 0) > 0
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function installListeners(): () => void {
|
||||
const g = graph()
|
||||
if (!g || !win?.mxEvent) return () => {}
|
||||
const mxEvent = win.mxEvent
|
||||
const cleanups: (() => void)[] = []
|
||||
|
||||
const listen = (source: any, name: string, handler: () => void) => {
|
||||
if (!source?.addListener) return
|
||||
source.addListener(name, handler)
|
||||
cleanups.push(() => source.removeListener(handler))
|
||||
}
|
||||
|
||||
// Any user action ends the "what the AI just changed" highlight
|
||||
const onSelection = () => {
|
||||
clearHighlights()
|
||||
syncAll()
|
||||
}
|
||||
const onScale = () => {
|
||||
zoomChanged()
|
||||
syncSelectionRect()
|
||||
}
|
||||
|
||||
listen(g.getSelectionModel(), mxEvent.CHANGE, onSelection)
|
||||
listen(g.model, mxEvent.CHANGE, syncAll)
|
||||
// Drawing started or stopped: the "ask AI" button hides meanwhile
|
||||
listen(g, "freehandStateChanged", syncAll)
|
||||
listen(g.view, mxEvent.SCALE, onScale)
|
||||
listen(g.view, mxEvent.TRANSLATE, syncSelectionRect)
|
||||
listen(g.view, mxEvent.SCALE_AND_TRANSLATE, onScale)
|
||||
listen(ui.editor, "pageSelected", syncAll)
|
||||
|
||||
// Capture phase, so the app shortcut wins before draw.io's key handler
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (appShortcutHandler?.(event)) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}
|
||||
}
|
||||
const frameDocument = win.document as Document | undefined
|
||||
frameDocument?.addEventListener("keydown", onKeyDown, true)
|
||||
cleanups.push(() =>
|
||||
frameDocument?.removeEventListener("keydown", onKeyDown, true),
|
||||
)
|
||||
|
||||
// draw.io adds its menus and dialogs to its body, and the shape picker
|
||||
// (from the arrows next to a selection) to the canvas, and removes them
|
||||
// when they close: the "ask AI" button over the frame must not cover them
|
||||
const body = frameDocument?.body
|
||||
const canvas = g.container as HTMLElement | undefined
|
||||
if (body && canvas && win.MutationObserver) {
|
||||
const syncPopups = () =>
|
||||
useCanvasStore.getState().set({
|
||||
isDrawioPopupOpen:
|
||||
!!body.querySelector(
|
||||
":scope > .mxPopupMenu, :scope > .geDialog",
|
||||
) || !!canvas.querySelector(":scope > .geShapePicker"),
|
||||
})
|
||||
const observer = new win.MutationObserver(syncPopups)
|
||||
observer.observe(body, { childList: true })
|
||||
observer.observe(canvas, { childList: true })
|
||||
cleanups.push(() => observer.disconnect())
|
||||
}
|
||||
|
||||
const container = g.container as HTMLElement | undefined
|
||||
container?.addEventListener("scroll", syncSelectionRect, { passive: true })
|
||||
cleanups.push(() =>
|
||||
container?.removeEventListener("scroll", syncSelectionRect),
|
||||
)
|
||||
|
||||
return () => {
|
||||
for (const cleanup of cleanups) cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the EditorUi instance inside a same-origin draw.io iframe.
|
||||
*
|
||||
* draw.io keeps no global reference to it, so we wrap prototype methods it
|
||||
* calls on startup and after every load; the first call hands us `this`.
|
||||
* Returns false when the frame is cross-origin.
|
||||
*/
|
||||
export function watchForEditorUi(
|
||||
frameWindow: Window,
|
||||
onFound: (editorUi: EditorUi) => void,
|
||||
): boolean {
|
||||
let w: any
|
||||
try {
|
||||
w = frameWindow as any
|
||||
// Throws for a cross-origin frame
|
||||
void w.document
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
const hook = (proto: any, method: string) => {
|
||||
if (!proto || typeof proto[method] !== "function") return
|
||||
if (proto[method].__naiWrapped) return
|
||||
const original = proto[method]
|
||||
const wrapped = function (this: any, ...args: any[]) {
|
||||
onFound(this)
|
||||
return original.apply(this, args)
|
||||
}
|
||||
;(wrapped as any).__naiWrapped = true
|
||||
proto[method] = wrapped
|
||||
}
|
||||
hook(w.EditorUi?.prototype, "updateActionStates")
|
||||
hook(w.App?.prototype, "fileLoaded")
|
||||
hook(w.EditorUi?.prototype, "fileLoaded")
|
||||
return true
|
||||
}
|
||||
+325
-200
@@ -3,22 +3,19 @@
|
||||
"save": "Save",
|
||||
"cancel": "Cancel",
|
||||
"close": "Close",
|
||||
"confirm": "Confirm",
|
||||
"clear": "Clear",
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"loading": "Loading..",
|
||||
"new": "NEW"
|
||||
"loading": "Loading.."
|
||||
},
|
||||
"nav": {
|
||||
"about": "About",
|
||||
"editor": "Editor",
|
||||
"newChat": "Start fresh chat",
|
||||
"newChat": "New diagram",
|
||||
"github": "GitHub",
|
||||
"settings": "Settings",
|
||||
"hidePanel": "Hide chat panel (Ctrl+B)",
|
||||
"showPanel": "Show chat panel (Ctrl+B)",
|
||||
"aiChat": "AI Chat"
|
||||
"hidePanel": "Hide chat panel",
|
||||
"showPanel": "Show chat panel",
|
||||
"aiChat": "AI chat"
|
||||
},
|
||||
"providers": {
|
||||
"useServerDefault": "Use Server Default",
|
||||
@@ -39,12 +36,11 @@
|
||||
},
|
||||
"chat": {
|
||||
"placeholder": "Describe your diagram or upload a file...",
|
||||
"inputLabel": "Chat input",
|
||||
"send": "Send",
|
||||
"stopGeneration": "Stop generation",
|
||||
"sendMessage": "Send message",
|
||||
"clearConversation": "Clear conversation",
|
||||
"diagramHistory": "Diagram history",
|
||||
"saveDiagram": "Save diagram",
|
||||
"uploadFile": "Upload file (image, PDF, text)",
|
||||
"minimalStyle": "Minimal",
|
||||
"styledMode": "Styled",
|
||||
@@ -52,39 +48,38 @@
|
||||
"regenerate": "Regenerate response",
|
||||
"copyResponse": "Copy response",
|
||||
"copied": "Copied!",
|
||||
"failedToCopy": "Failed to copy",
|
||||
"failedToCopyDetail": "Failed to copy message. Please copy manually or check clipboard permissions.",
|
||||
"goodResponse": "Good response",
|
||||
"badResponse": "Bad response",
|
||||
"clickToEdit": "Click to edit",
|
||||
"editMessage": "Edit message",
|
||||
"saveAndSubmit": "Save & Submit",
|
||||
"ExtractURL": "Extract from URL"
|
||||
"saveAndSubmit": "Save & submit",
|
||||
"ExtractURL": "Extract from URL",
|
||||
"attach": "Add",
|
||||
"placeholderFollowUp": "Ask for a change, or select shapes to edit them",
|
||||
"emptyThread": "Draw on the canvas, or describe what you want below.",
|
||||
"attachedImage": "Attached image",
|
||||
"retry": "Retry"
|
||||
},
|
||||
"examples": {
|
||||
"title": "Create diagrams with AI",
|
||||
"subtitle": "Describe what you want to create or upload an image to replicate",
|
||||
"quickExamples": "Quick Examples",
|
||||
"paperToDiagram": "Paper to Diagram",
|
||||
"paperToDiagram": "Paper to diagram",
|
||||
"paperDescription": "Upload .pdf, .txt, .md, .json, .csv, .py, .js, .ts and more",
|
||||
"animatedDiagram": "Animated Diagram",
|
||||
"animatedDiagram": "Animated diagram",
|
||||
"animatedDescription": "Draw a transformer architecture with animated connectors",
|
||||
"awsArchitecture": "AWS Architecture",
|
||||
"awsArchitecture": "AWS architecture",
|
||||
"awsDescription": "Create a cloud architecture diagram with AWS icons",
|
||||
"replicateFlowchart": "Replicate Flowchart",
|
||||
"replicateFlowchart": "Replicate a flowchart",
|
||||
"replicateDescription": "Upload and replicate an existing flowchart",
|
||||
"creativeDrawing": "Creative Drawing",
|
||||
"creativeDrawing": "Creative drawing",
|
||||
"creativeDescription": "Draw something fun and creative",
|
||||
"cachedNote": "Examples are cached for instant response",
|
||||
"cachedNote": "Examples use saved answers: they appear instantly and don't call the AI.",
|
||||
"mcpServer": "MCP Server",
|
||||
"mcpDescription": "Use in Claude Desktop, VS Code & Cursor"
|
||||
},
|
||||
"settings": {
|
||||
"title": "Settings",
|
||||
"description": "Configure your application settings.",
|
||||
"apiKeysModels": "API Keys & Models",
|
||||
"apiKeysModelsDescription": "Configure AI providers and API keys.",
|
||||
"accessCode": "Access Code",
|
||||
"accessCode": "Access code",
|
||||
"accessCodePlaceholder": "Enter access code",
|
||||
"accessCodeDescription": "Required to use this application.",
|
||||
"aiProvider": "AI Provider Settings",
|
||||
@@ -101,17 +96,10 @@
|
||||
"language": "Language",
|
||||
"languageDescription": "Choose your interface language.",
|
||||
"theme": "Theme",
|
||||
"themeDescription": "Dark/Light mode for interface and DrawIO canvas.",
|
||||
"drawioStyle": "DrawIO Style",
|
||||
"drawioStyleDescription": "Canvas style",
|
||||
"themeDefault": "Default",
|
||||
"themeDark": "Dark",
|
||||
"themeMinimal": "Minimal",
|
||||
"themeSketch": "Sketch",
|
||||
"themeSimple": "Simple",
|
||||
"diagramStyle": "Diagram Style",
|
||||
"diagramStyleDescription": "Toggle between minimal and styled diagram output.",
|
||||
"sendShortcut": "Send Shortcut",
|
||||
"themeDescription": "Light or dark interface. The canvas follows the same theme.",
|
||||
"diagramStyle": "Diagram style",
|
||||
"diagramStyleDescription": "How the AI draws new diagrams: Styled uses colors and icons, Minimal keeps shapes plain.",
|
||||
"sendShortcut": "Send shortcut",
|
||||
"sendShortcutDescription": "Choose how to send messages.",
|
||||
"enterToSend": "Enter to send",
|
||||
"ctrlEnterToSend": "Cmd/Ctrl+Enter to send",
|
||||
@@ -119,52 +107,55 @@
|
||||
"diagramActionsDescription": "Manage diagram history and exports",
|
||||
"history": "History",
|
||||
"download": "Download",
|
||||
"proxy": "Proxy Settings",
|
||||
"proxy": "Proxy settings",
|
||||
"proxyDescription": "Configure HTTP/HTTPS proxy for API requests (Desktop only)",
|
||||
"httpProxy": "HTTP Proxy",
|
||||
"httpsProxy": "HTTPS Proxy",
|
||||
"httpProxy": "HTTP proxy",
|
||||
"httpsProxy": "HTTPS proxy",
|
||||
"applyProxy": "Apply",
|
||||
"proxyApplied": "Proxy settings applied",
|
||||
"diagramValidation": "Diagram Validation (Experimental)",
|
||||
"diagramValidationDescription": "Use a vision language model to validate generated diagrams. Requires a VLM like GPT-5.2 or Sonnet-4.5.",
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled",
|
||||
"customSystemMessage": "Custom System Message",
|
||||
"diagramValidation": "Check diagrams with a screenshot (experimental)",
|
||||
"diagramValidationDescription": "After each drawing, a model that can read images looks at a screenshot and asks for fixes. Needs a model that can read images.",
|
||||
"customSystemMessage": "Custom instructions",
|
||||
"customSystemMessageDescription": "Add custom instructions appended to the AI's system prompt.",
|
||||
"customSystemMessagePlaceholder": "e.g., Always use blue color scheme for diagrams...",
|
||||
"maxOutputTokens": "Max Output Tokens",
|
||||
"maxOutputTokens": "Output token limit",
|
||||
"maxOutputTokensDescription": "Budget for one reply, shared by thinking and the diagram XML. Raise it if the AI keeps thinking and no diagram appears. Leave empty for the default.",
|
||||
"panelVisibility": "Lobby Panels",
|
||||
"panelVisibilityDescription": "Choose which panels to show on the chat lobby.",
|
||||
"showRecentChats": "Recent Chats",
|
||||
"showMyTemplates": "My Templates",
|
||||
"showQuickExamples": "Quick Examples"
|
||||
"tabModels": "Models",
|
||||
"tabAbout": "About",
|
||||
"themeLight": "Light",
|
||||
"themeDarkMode": "Dark",
|
||||
"themeSystem": "System",
|
||||
"accessCodeSaved": "Access code saved",
|
||||
"proxyInvalid": "Proxy addresses must start with http:// or https://",
|
||||
"proxyFailed": "Couldn't apply the proxy settings",
|
||||
"appVersion": "Version",
|
||||
"projectWebsite": "Project website",
|
||||
"tabGeneral": "General",
|
||||
"tabDrawing": "Drawing",
|
||||
"sectionInterface": "Interface",
|
||||
"sectionAccess": "Access"
|
||||
},
|
||||
"save": {
|
||||
"title": "Save Diagram",
|
||||
"description": "Choose a format and filename to save your diagram.",
|
||||
"title": "Export diagram",
|
||||
"description": "Pick a format and a file name.",
|
||||
"format": "Format",
|
||||
"filename": "Filename",
|
||||
"filenamePlaceholder": "Enter filename",
|
||||
"formats": {
|
||||
"drawio": "Draw.io XML",
|
||||
"png": "PNG Image",
|
||||
"svg": "SVG Image",
|
||||
"drawio": "draw.io file",
|
||||
"png": "PNG image",
|
||||
"svg": "SVG image",
|
||||
"xmlsvg": "Editable SVG"
|
||||
},
|
||||
"savedSuccessfully": "Saved successfully!"
|
||||
},
|
||||
"history": {
|
||||
"title": "Diagram History",
|
||||
"description": "Here saved each diagram before AI modification.\nClick on a diagram to restore it",
|
||||
"noHistory": "No history available yet. Send messages to create diagram history.",
|
||||
"version": "Version",
|
||||
"restoreTo": "Restore to Version {version}?"
|
||||
"savedSuccessfully": "Diagram exported",
|
||||
"hints": {
|
||||
"drawio": "Keeps everything editable",
|
||||
"png": "A picture for slides and documents",
|
||||
"svg": "A picture that scales without blur",
|
||||
"xmlsvg": "A picture that still opens in draw.io"
|
||||
}
|
||||
},
|
||||
"dialogs": {
|
||||
"clearTitle": "Clear Everything?",
|
||||
"clearDescription": "This will clear the current conversation and reset the diagram. This action cannot be undone.",
|
||||
"clearEverything": "Clear Everything",
|
||||
"clearSuccess": "Started a fresh chat"
|
||||
},
|
||||
"errors": {
|
||||
@@ -189,9 +180,18 @@
|
||||
"sessionSaveFailed": "Could not save this chat. Browser storage may be full: delete old chats from history and try again.",
|
||||
"sessionSaveFailedLeave": "Could not save this chat. Browser storage may be full. You can go on without saving it, then delete old chats from the list in the new chat.",
|
||||
"continueWithoutSaving": "Continue without saving",
|
||||
"notADiagramFile": "{name} isn't a draw.io diagram.",
|
||||
"fileTooLong": "{name}: Content exceeds {limit}k character limit ({size}k chars)",
|
||||
"fileReadFailed": "Failed to read file: {name}",
|
||||
"answerEndedEarly": "The answer ended before the diagram was finished.",
|
||||
"attachmentsStillReading": "Attachments are still being read. Send again when they are ready.",
|
||||
"sendInProgress": "The last message is still being sent. Try again in a moment.",
|
||||
"answerInProgress": "An answer is still coming. Send again when it is done.",
|
||||
"cannotResend": "This message can't be sent again: the diagram from when it was sent wasn't saved.",
|
||||
"llm": {
|
||||
"invalid_api_key": "The provider rejected the API key. Check it in model settings.",
|
||||
"forbidden": "The provider refused the request. The key may not have access to this model or region.",
|
||||
"server_key_forbidden": "Today's free quota is used up. It resets tomorrow. You can also add your own API key in model settings to keep going.",
|
||||
"model_not_found": "The provider does not know this model. Check the model ID in model settings.",
|
||||
"insufficient_quota": "The provider account has no credit or quota left.",
|
||||
"rate_limited": "The provider is limiting requests. Wait a moment and try again.",
|
||||
@@ -211,14 +211,13 @@
|
||||
"tpmLimit": "Rate Limit",
|
||||
"tpmMessage": "Too many requests. Please wait a moment.",
|
||||
"tpmMessageDetailed": "Rate limit reached ({limit} tokens/min). Please wait {seconds} seconds before sending another request.",
|
||||
"messageApi": "Looks like you've reached today's demo limit. We're thrilled you're enjoying it, and while ByteDance Doubao generously sponsors this demo, we've had to set a few boundaries to keep things fair for everyone.",
|
||||
"messageApi": "Looks like you've reached today's demo limit. We're glad you're enjoying it; the limit keeps the demo fair for everyone.",
|
||||
"messageApiSelfHosted": null,
|
||||
"messageToken": "Looks like you've reached today's token limit. We're thrilled you're enjoying it, and while ByteDance Doubao generously sponsors this demo, we've had to set a few boundaries to keep things fair for everyone.",
|
||||
"messageToken": "Looks like you've reached today's token limit. We're glad you're enjoying it; the limit keeps the demo fair for everyone.",
|
||||
"messageTokenSelfHosted": null,
|
||||
"tip": "<strong>Tip:</strong> You can use your own API key (click the Settings icon) or self-host the project to bypass these limits.",
|
||||
"tipSelfHosted": "<strong>Tip:</strong> You can configure your own API key in the settings to continue using the service.",
|
||||
"reset": "Your limit resets tomorrow. Thanks for understanding.",
|
||||
"doubaoSponsorship": "<a href=\"{link}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline hover:text-foreground\">Register here</a> to get 500K free tokens per model (including Doubao, DeepSeek and Kimi), then configure your API key in model settings.",
|
||||
"configModel": "Use Your API Key",
|
||||
"selfHost": "Self-host",
|
||||
"sponsor": "Sponsor",
|
||||
@@ -226,11 +225,6 @@
|
||||
"usedOf": "{used}/{limit}"
|
||||
},
|
||||
"tools": {
|
||||
"generateDiagram": "Generate Diagram",
|
||||
"editDiagram": "Edit Diagram",
|
||||
"appendDiagram": "Continue Diagram",
|
||||
"complete": "Complete",
|
||||
"error": "Error",
|
||||
"truncated": "Truncated"
|
||||
},
|
||||
"file": {
|
||||
@@ -245,7 +239,8 @@
|
||||
"extract": "Extract",
|
||||
"Cancel": "Cancel",
|
||||
"enterUrl": "Please enter a URL",
|
||||
"invalidFormat": "Invalid URL format"
|
||||
"invalidFormat": "Invalid URL format",
|
||||
"failed": "Couldn't read that page"
|
||||
},
|
||||
"reasoning": {
|
||||
"thinking": "Thinking...",
|
||||
@@ -278,30 +273,29 @@
|
||||
"sessionHistory": {
|
||||
"tooltip": "Chat History",
|
||||
"newChat": "New Chat",
|
||||
"empty": "No chat history yet",
|
||||
"empty": "No diagrams yet",
|
||||
"emptyHint": "Start a conversation to begin",
|
||||
"today": "Today",
|
||||
"yesterday": "Yesterday",
|
||||
"thisWeek": "This Week",
|
||||
"earlier": "Earlier",
|
||||
"deleteTitle": "Delete this chat?",
|
||||
"deleteDescription": "This will permanently delete this chat session and its diagram. This action cannot be undone.",
|
||||
"recentChats": "Recent Chats",
|
||||
"deleteTitle": "Delete this diagram?",
|
||||
"deleteDescription": "The diagram and its conversation are deleted for good.",
|
||||
"justNow": "Just now",
|
||||
"searchPlaceholder": "Search chats...",
|
||||
"noResults": "No chats found"
|
||||
"searchPlaceholder": "Search diagrams…",
|
||||
"noResults": "No chats found",
|
||||
"rename": "Rename",
|
||||
"busyHint": "Available when the answer is finished"
|
||||
},
|
||||
"templates": {
|
||||
"title": "My Templates",
|
||||
"subtitle": "Your personal prompt library for quick diagram creation",
|
||||
"emptyTitle": "No templates yet",
|
||||
"emptyDescription": "Create your first template to start building your personal prompt library",
|
||||
"createFirst": "Create First Template",
|
||||
"emptyTitle": "No saved prompts yet",
|
||||
"emptyDescription": "Save a prompt you reuse, for example \"Draw an AWS architecture for…\". It shows up here.",
|
||||
"createFirst": "Save your first prompt",
|
||||
"neverUsed": "Not used yet",
|
||||
"usedCount": "{count} uses",
|
||||
"myTemplates": "My Templates",
|
||||
"createTitle": "Create Template",
|
||||
"createDescription": "Save a prompt for repeated use. Templates help you quickly start common workflows.",
|
||||
"myTemplates": "Saved prompts",
|
||||
"createTitle": "Save a prompt",
|
||||
"createDescription": "Save a prompt to use again later.",
|
||||
"promptLabel": "Prompt",
|
||||
"promptPlaceholder": "Describe the diagram you want to create...",
|
||||
"promptRequired": "Prompt is required",
|
||||
@@ -309,33 +303,34 @@
|
||||
"titlePlaceholder": "Enter a title",
|
||||
"titleHint": "Leave empty to use the first 20 characters of prompt",
|
||||
"descriptionLabel": "Description",
|
||||
"descriptionPlaceholder": "Add a description for this template",
|
||||
"pinnedLabel": "Pin Template",
|
||||
"pinnedHint": "Pinned templates appear at the top of the list",
|
||||
"createButton": "Create Template",
|
||||
"createFailed": "Failed to create template. Please try again.",
|
||||
"editTitle": "Edit Template",
|
||||
"editDescription": "Update your template content and settings.",
|
||||
"updateFailed": "Failed to update template. Please try again.",
|
||||
"descriptionPlaceholder": "What this prompt is for",
|
||||
"pinnedLabel": "Pin to top",
|
||||
"pinnedHint": "Pinned prompts appear at the top of the list",
|
||||
"createButton": "Save prompt",
|
||||
"createFailed": "Couldn't save the prompt. Try again.",
|
||||
"editTitle": "Edit saved prompt",
|
||||
"editDescription": "Change the prompt and its settings.",
|
||||
"updateFailed": "Couldn't update the prompt. Try again.",
|
||||
"duplicate": "Duplicate",
|
||||
"copySuffix": "(copy)",
|
||||
"deleteTitle": "Delete this template?",
|
||||
"deleteDescription": "This will permanently delete this template. This action cannot be undone.",
|
||||
"deleteTitle": "Delete this saved prompt?",
|
||||
"deleteDescription": "The prompt is deleted for good.",
|
||||
"confirmSendTitle": "Replace current input?",
|
||||
"confirmSendDescription": "You have unsent content in the input. Sending this template will replace it.",
|
||||
"confirmSendButton": "Send Template",
|
||||
"searchPlaceholder": "Search templates...",
|
||||
"searchNoResults": "No templates match your search",
|
||||
"confirmSendDescription": "You have unsent text in the message box. Sending this prompt replaces it.",
|
||||
"confirmSendButton": "Send prompt",
|
||||
"searchPlaceholder": "Search saved prompts…",
|
||||
"searchNoResults": "No saved prompts match",
|
||||
"pin": "Pin to top",
|
||||
"unpin": "Unpin from top",
|
||||
"saveAsTemplate": "Save as Template",
|
||||
"exportTemplates": "Export Templates",
|
||||
"importTemplates": "Import Templates",
|
||||
"exportEmpty": "No templates to export",
|
||||
"exportSuccess": "Exported {count} template(s) successfully",
|
||||
"saveAsTemplate": "Save this prompt",
|
||||
"exportTemplates": "Export saved prompts",
|
||||
"importTemplates": "Import saved prompts",
|
||||
"exportEmpty": "No saved prompts to export",
|
||||
"exportSuccess": "Exported {count} saved prompt(s)",
|
||||
"importNoFile": "Please select a JSON file",
|
||||
"importFailed": "Import failed: {error}",
|
||||
"importSuccess": "Imported {imported} template(s), skipped {skipped} duplicate(s)"
|
||||
"importSuccess": "Imported {imported} saved prompt(s), skipped {skipped} duplicate(s)",
|
||||
"saveDisabledHint": "Type a prompt first"
|
||||
},
|
||||
"validation": {
|
||||
"title": "Validate Diagram",
|
||||
@@ -356,39 +351,30 @@
|
||||
"regenerateWithFeedback": "Regenerate the diagram using the validation feedback"
|
||||
},
|
||||
"modelConfig": {
|
||||
"title": "AI Model Configuration",
|
||||
"description": "Configure multiple AI providers and models",
|
||||
"configure": "Configure",
|
||||
"addProvider": "Add Provider",
|
||||
"addProvider": "Add provider",
|
||||
"addModel": "Add Model",
|
||||
"modelId": "Model ID",
|
||||
"modelLabel": "Display Label",
|
||||
"streaming": "Enable Streaming",
|
||||
"deleteProvider": "Delete Provider",
|
||||
"deleteProvider": "Delete provider",
|
||||
"deleteModel": "Delete Model",
|
||||
"noModels": "No models configured. Add a model to get started.",
|
||||
"selectProvider": "Select a provider or add a new one",
|
||||
"configureMultiple": "Configure multiple AI providers and switch between them easily",
|
||||
"apiKeyStored": "API keys are stored locally in your browser",
|
||||
"test": "Test",
|
||||
"validationError": "Validation failed",
|
||||
"addModelFirst": "Add at least one model to validate",
|
||||
"providers": "Providers",
|
||||
"addProviderHint": "Add a provider to get started",
|
||||
"verified": "Verified",
|
||||
"configuration": "Configuration",
|
||||
"validationError": "The test failed",
|
||||
"addModelFirst": "Add a model first.",
|
||||
"displayName": "Display Name",
|
||||
"bedrockApiKey": "Bedrock API key",
|
||||
"bedrockApiKeyHint": "With an API key, the access keys below are not needed.",
|
||||
"awsAccessKeyId": "AWS Access Key ID",
|
||||
"awsSecretAccessKey": "AWS Secret Access Key",
|
||||
"awsRegion": "AWS Region",
|
||||
"selectRegion": "Select region",
|
||||
"apiKey": "API Key",
|
||||
"apiKey": "API key",
|
||||
"enterApiKey": "Enter your API key",
|
||||
"enterSecretKey": "Enter your secret access key",
|
||||
"baseUrl": "Base URL",
|
||||
"optional": "(optional)",
|
||||
"getApiKey": "Get API key",
|
||||
"fetchModels": "Fetch models from the provider",
|
||||
"noTools": "no tool calls",
|
||||
"mayNotDraw": "models.dev lists no tool call support for this model, so it may not be able to draw.",
|
||||
"requestUrl": "Requests go to {url}",
|
||||
@@ -399,80 +385,143 @@
|
||||
"models": "Models",
|
||||
"customModelId": "Custom model ID...",
|
||||
"allAdded": "All added",
|
||||
"suggested": "Suggested",
|
||||
"noModelsConfigured": "No models configured",
|
||||
"modelIdEmpty": "Model ID cannot be empty",
|
||||
"modelIdExists": "This model ID already exists",
|
||||
"configureProviders": "Configure AI Providers",
|
||||
"selectProviderHint": "Select a provider from the list or add a new one to configure API keys and models",
|
||||
"deleteConfirmDesc": "Are you sure you want to delete {name}? This will remove all configured models and cannot be undone.",
|
||||
"typeToConfirm": "Type \"{name}\" to confirm",
|
||||
"typeProviderName": "Type provider name...",
|
||||
"modelsConfiguredCount": "{count} model(s) configured",
|
||||
"validationFailedCount": "{count} model(s) failed validation",
|
||||
"typeProviderName": "Type the provider name...",
|
||||
"requestFailed": "Request failed ({status})",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete",
|
||||
"clickToChange": "(click to change)",
|
||||
"usingServerDefault": "Using server default model",
|
||||
"selectModel": "Select Model",
|
||||
"searchModels": "Search models...",
|
||||
"noVerifiedModels": "No verified models. Test your models first.",
|
||||
"noModelsFound": "No models found.",
|
||||
"default": "Default",
|
||||
"serverDefault": "Server Default",
|
||||
"serverDefault": "Server model",
|
||||
"serverModels": "Server Models",
|
||||
"userModels": "User Models",
|
||||
"configureModels": "Configure Models...",
|
||||
"onlyVerifiedShown": "Only verified models are shown",
|
||||
"showUnvalidatedModels": "Show unvalidated models",
|
||||
"allModelsShown": "All models are shown (including unvalidated)",
|
||||
"unvalidatedModelWarning": "This model has not been validated",
|
||||
"serverDefaultModel": "Server default model",
|
||||
"showValue": "Show value",
|
||||
"hideValue": "Hide value"
|
||||
"hideValue": "Hide value",
|
||||
"myProviders": "My providers",
|
||||
"inUse": "In use",
|
||||
"listSeparator": ", ",
|
||||
"serverModelsTitle": "Models from this server",
|
||||
"serverDefaultSummary": "No API key needed: the server's default model.",
|
||||
"statusError": "{count} failed",
|
||||
"statusIncomplete": "Not set up yet",
|
||||
"statusUntested": "{count} untested",
|
||||
"statusOk": "{count} working",
|
||||
"noModelsYet": "No models yet",
|
||||
"keysStayLocal": "API keys stay in this browser on this device and go to the server only with your requests.",
|
||||
"useOwnKey": "Use your own API key",
|
||||
"useOwnKeyHint": "Add a provider to use its models from the chat's model picker. Pick one to start:",
|
||||
"viewAllProviders": "See all {count} providers",
|
||||
"searchProviders": "Search providers, e.g. DeepSeek, Qwen, Ollama",
|
||||
"noProvidersFound": "No provider matches.",
|
||||
"groupVendors": "Model makers",
|
||||
"groupAggregators": "Aggregators",
|
||||
"groupCloud": "Cloud platforms",
|
||||
"groupSelfHosted": "Self-hosted",
|
||||
"noteBedrock": "AWS credentials",
|
||||
"noteVertex": "Express mode key",
|
||||
"noteAzure": "Key and resource URL",
|
||||
"noteEdgeone": "No key needed",
|
||||
"noteOllama": "Key optional",
|
||||
"noteSglang": "Your server's URL",
|
||||
"added": "Added",
|
||||
"awsCredentials": "AWS credentials",
|
||||
"bedrockAuthApiKey": "Bedrock API key",
|
||||
"bedrockAuthAccessKey": "Access keys",
|
||||
"moreOptions": "More options: base URL, display name",
|
||||
"moreOptionsName": "More options: display name",
|
||||
"keyRejected": "The provider rejected this API key. Check that the key above was copied in full.",
|
||||
"modelNotFound": "The provider can't find this model ID. Check its spelling.",
|
||||
"modelWorks": "Works",
|
||||
"modelWorksTime": "Works · {seconds} s",
|
||||
"modelFailed": "Failed",
|
||||
"modelUntested": "Untested",
|
||||
"needKey": "Fill in the API key first.",
|
||||
"needAws": "Fill in the AWS credentials and region first.",
|
||||
"needModel": "Add a model first.",
|
||||
"stepConnect": "Connection",
|
||||
"edgeoneNoKey": "EdgeOne Pages uses the model service that comes with this site's deployment: no API key needed.",
|
||||
"stepModels": "Models",
|
||||
"fetchAllModels": "Get all models from {name}",
|
||||
"suggestedLabel": "Suggested:",
|
||||
"orTypeModelId": "Or type another model ID",
|
||||
"add": "Add",
|
||||
"browseModels": "Browse models",
|
||||
"stepTest": "Test",
|
||||
"testHint": "Sends each model a very short message to check that the key and the model work.",
|
||||
"testOne": "Test {model}",
|
||||
"testAll": "Test all {count} models",
|
||||
"testPassedOne": "{model} works",
|
||||
"testPassedAll": "All {count} models work",
|
||||
"answeredIn": "(answered in {seconds} s)",
|
||||
"useInChat": "Use {model} in the chat",
|
||||
"backToProviders": "Back to providers",
|
||||
"deleteProviderOnly": "Delete {name}",
|
||||
"addProviderEntry": "Add a provider…",
|
||||
"awsKeysRejected": "AWS rejected these access keys. Check that both were copied in full.",
|
||||
"needAzure": "Fill in the API key and your Azure resource's base URL first.",
|
||||
"validationFailedCountOne": "{count} model failed the test",
|
||||
"validationFailedCountOther": "{count} models failed the test",
|
||||
"deleteProviderNamedOne": "Delete {name} and its model",
|
||||
"deleteProviderNamedOther": "Delete {name} and its {count} models",
|
||||
"serverModelsSummaryOne": "No API key needed. {count} model: {names}",
|
||||
"serverModelsSummaryOther": "No API key needed. {count} models: {names}",
|
||||
"noModelsReturned": "The provider returned no models.",
|
||||
"awsSessionToken": "AWS session token (optional)",
|
||||
"awsSessionTokenHint": "Only for temporary credentials: access keys that start with ASIA.",
|
||||
"bedrockBothSaved": "This provider also keeps an access key pair, unused while there is an API key.",
|
||||
"removeAccessKeys": "Remove the access keys"
|
||||
},
|
||||
"admin": {
|
||||
"title": "Admin Settings",
|
||||
"loginPrompt": "Enter the admin password (the ADMIN_PASSWORD environment variable) to manage server settings.",
|
||||
"loginPrompt": "Enter the admin password (the ADMIN_PASSWORD environment variable)",
|
||||
"password": "Password",
|
||||
"signIn": "Sign In",
|
||||
"signingIn": "Signing In…",
|
||||
"signingIn": "Signing in…",
|
||||
"loginFailed": "Login failed",
|
||||
"precedence": "File overrides env · env overrides defaults",
|
||||
"notWritable": "The settings file is not writable on this deployment (serverless platforms have no persistent disk). Settings are shown read-only — configure via environment variables instead.",
|
||||
"precedence": "Priority: this page > environment variables > defaults",
|
||||
"notWritable": "Settings can't be saved on this deployment, only viewed; use environment variables instead",
|
||||
"settingGroups": "Setting groups",
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled",
|
||||
"enableGroup": "Enable {group}",
|
||||
"enabled": "On",
|
||||
"disabled": "Off",
|
||||
"enableGroup": "Turn on {group}",
|
||||
"unsavedChanges": "Unsaved changes",
|
||||
"saved": "Settings saved. Changes apply immediately.",
|
||||
"saveFailed": "Save failed. Check your connection and try again.",
|
||||
"invalidSettings": "Some settings are invalid.",
|
||||
"discard": "Discard",
|
||||
"saveChanges": "Save Changes",
|
||||
"saved": "Saved. Changes apply right away, except items marked \"Needs restart\"",
|
||||
"saveFailed": "Save failed. Check your connection and try again",
|
||||
"invalidSettings": "Some settings are invalid; see the notes under them",
|
||||
"discard": "Discard changes",
|
||||
"saveChanges": "Save changes",
|
||||
"saving": "Saving…",
|
||||
"sourceSaved": "Saved",
|
||||
"sourceSaved": "This page",
|
||||
"sourceEnv": "Env",
|
||||
"sourceSavedTitle": "Set in the admin settings file",
|
||||
"sourceEnvTitle": "Set by an environment variable",
|
||||
"restartRequired": "Restart Required",
|
||||
"sourceSavedTitle": "Set on this page",
|
||||
"sourceEnvTitle": "From an environment variable",
|
||||
"restartRequired": "Needs restart",
|
||||
"modified": "Modified",
|
||||
"notSet": "Not set",
|
||||
"savedReplace": "Saved ({hint}) — type to replace",
|
||||
"showValue": "Show value",
|
||||
"hideValue": "Hide value",
|
||||
"removeValue": "Remove value",
|
||||
"removeValueTitle": "Remove the stored value",
|
||||
"savedReplace": "Saved ({hint}); type a new value to replace it",
|
||||
"showValue": "Show",
|
||||
"hideValue": "Hide",
|
||||
"removeValue": "Clear",
|
||||
"removeValueTitle": "Clear the saved value",
|
||||
"resetToDefault": "Reset to default",
|
||||
"models": "Models",
|
||||
"modelsDescription": "Server-side providers and models available to all users — no personal API key needed. The default provider's first model is used when users don't pick one.",
|
||||
"addProviderHint": "Add a provider to offer server-side models to all users.",
|
||||
"selectProviderHint": "Select or add a provider to configure its credentials and models.",
|
||||
"addProviderToOfferModels": "Add at least one model to expose this provider to users.",
|
||||
"managedViaEnv": "(managed via env)",
|
||||
"envReadOnly": "Defined in AI_MODELS_CONFIG / ai-models.json — read-only here. Edit the environment configuration to change it.",
|
||||
"modelsDescription": "Models every user can use, no personal API key needed",
|
||||
"addProviderHint": "Add a provider to offer models to all users",
|
||||
"selectProviderHint": "Select or add a provider, then enter its key and models",
|
||||
"addProviderToOfferModels": "Add at least one model before users can see this provider",
|
||||
"managedViaEnv": "(environment variables)",
|
||||
"envReadOnly": "Defined in AI_MODELS_CONFIG / ai-models.json; view only here, edit it there",
|
||||
"defaultModel": "Default Model",
|
||||
"noModelsConfigured": "No models configured",
|
||||
"noModelsConfigured": "No models yet",
|
||||
"modelCount": "{count} model",
|
||||
"modelCountPlural": "{count} models",
|
||||
"default": "Default",
|
||||
@@ -482,65 +531,65 @@
|
||||
"addModel": "Add model",
|
||||
"suggested": "Suggested",
|
||||
"test": "Test",
|
||||
"testOk": "OK ({ms}ms)",
|
||||
"testOk": "Passed ({ms} ms)",
|
||||
"testFailed": "Failed",
|
||||
"removeModel": "Remove {model}",
|
||||
"removeModel": "Delete {model}",
|
||||
"deleteProviderTitle": "Delete {name}?",
|
||||
"deleteProviderDesc": "Its credentials and models will be removed from the server after you save.",
|
||||
"deleteProviderDesc": "After you save, its key and models are deleted from the server",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete",
|
||||
"groups": {
|
||||
"generation": {
|
||||
"title": "Generation",
|
||||
"description": "Output parameters applied to all chat requests."
|
||||
"title": "Replies",
|
||||
"description": "How the AI replies, for every conversation"
|
||||
},
|
||||
"access": {
|
||||
"title": "Access Control",
|
||||
"description": "Restrict who can use this deployment."
|
||||
"title": "Access",
|
||||
"description": "Limit who can use this site"
|
||||
},
|
||||
"features": {
|
||||
"title": "Features",
|
||||
"description": "Optional features and security toggles."
|
||||
"title": "Optional Features",
|
||||
"description": "Extra features and safety options"
|
||||
},
|
||||
"observability": {
|
||||
"title": "Observability",
|
||||
"description": "Langfuse tracing for LLM calls."
|
||||
"title": "Call Logs",
|
||||
"description": "Record model calls with Langfuse"
|
||||
},
|
||||
"quota": {
|
||||
"title": "Quota & Rate Limits",
|
||||
"description": "Per-IP usage limits. Enforcement requires a DynamoDB table."
|
||||
"title": "Usage Limits",
|
||||
"description": "Per-IP limits; they take effect only with a DynamoDB table"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"TEMPERATURE": {
|
||||
"label": "Temperature",
|
||||
"description": "Leave unset for reasoning models that reject temperature."
|
||||
"description": "Higher is more random; leave empty for reasoning models that don't support it"
|
||||
},
|
||||
"MAX_OUTPUT_TOKENS": {
|
||||
"label": "Max Output Tokens"
|
||||
"label": "Output Token Limit"
|
||||
},
|
||||
"ACCESS_CODE_LIST": {
|
||||
"label": "Access Codes",
|
||||
"description": "Comma-separated list. Users must enter one to chat. Empty = open access."
|
||||
"description": "Separate several with commas; users must enter one to chat; empty means no limit"
|
||||
},
|
||||
"ENABLE_VLM_VALIDATION": {
|
||||
"label": "VLM Diagram Validation",
|
||||
"description": "Visually validate generated diagrams with a vision model."
|
||||
"label": "Diagram Check",
|
||||
"description": "After drawing, a model that can see images checks a screenshot"
|
||||
},
|
||||
"VALIDATION_MODEL": {
|
||||
"label": "Validation Model",
|
||||
"description": "Falls back to the default AI model when empty."
|
||||
"label": "Check Model",
|
||||
"description": "Empty means the default model"
|
||||
},
|
||||
"VALIDATION_TIMEOUT": {
|
||||
"label": "Validation Timeout (ms)"
|
||||
"label": "Check Timeout (ms)"
|
||||
},
|
||||
"ENABLE_HISTORY_XML_REPLACE": {
|
||||
"label": "History XML Compression",
|
||||
"description": "Replace old diagram XML in history with placeholders."
|
||||
"label": "Trim Old Diagrams",
|
||||
"description": "Old diagrams in the chat history are kept as a short marker"
|
||||
},
|
||||
"ALLOW_PRIVATE_URLS": {
|
||||
"label": "Allow Private URLs",
|
||||
"description": "Turn off to block requests to private IPs and internal hostnames (SSRF protection)."
|
||||
"description": "When off, custom model URLs can't point to private networks; safer"
|
||||
},
|
||||
"LANGFUSE_PUBLIC_KEY": {
|
||||
"label": "Langfuse Public Key"
|
||||
@@ -549,30 +598,106 @@
|
||||
"label": "Langfuse Secret Key"
|
||||
},
|
||||
"LANGFUSE_BASEURL": {
|
||||
"label": "Langfuse Base URL"
|
||||
"label": "Langfuse URL"
|
||||
},
|
||||
"DAILY_REQUEST_LIMIT": {
|
||||
"label": "Daily Request Limit",
|
||||
"description": "Per IP per day."
|
||||
"label": "Daily Requests",
|
||||
"description": "Requests per IP per day"
|
||||
},
|
||||
"DAILY_TOKEN_LIMIT": {
|
||||
"label": "Daily Token Limit",
|
||||
"description": "Per IP per day."
|
||||
"label": "Daily Tokens",
|
||||
"description": "Tokens per IP per day"
|
||||
},
|
||||
"TPM_LIMIT": {
|
||||
"label": "Tokens Per Minute"
|
||||
},
|
||||
"DYNAMODB_QUOTA_TABLE": {
|
||||
"label": "DynamoDB Table",
|
||||
"description": "Quota enforcement is disabled when empty."
|
||||
"label": "DynamoDB Table Name",
|
||||
"description": "Empty means no usage limits"
|
||||
},
|
||||
"DYNAMODB_REGION": {
|
||||
"label": "DynamoDB Region"
|
||||
},
|
||||
"QUOTA_TIMEZONE": {
|
||||
"label": "Quota Timezone",
|
||||
"description": "Timezone for the daily reset boundary."
|
||||
"label": "Time Zone",
|
||||
"description": "Daily usage resets at midnight in this time zone"
|
||||
}
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"export": "Export",
|
||||
"openFile": "Open .drawio file",
|
||||
"canvasLoading": "Loading the canvas…",
|
||||
"askAi": "Ask AI to change this",
|
||||
"untitled": "Untitled diagram",
|
||||
"mobileCanvas": "Canvas",
|
||||
"mobileChat": "Chat"
|
||||
},
|
||||
"selection": {
|
||||
"one": "Selected: {label}",
|
||||
"many": "{count} shapes selected",
|
||||
"shape": "shape",
|
||||
"connector": "connector",
|
||||
"remove": "Don't send the selection",
|
||||
"placeholder": "Describe how to change the selected shapes"
|
||||
},
|
||||
"versions": {
|
||||
"strip": "Versions",
|
||||
"created": "Drew the diagram",
|
||||
"edited": "Changed the diagram",
|
||||
"undone": "Change undone",
|
||||
"undo": "Undo change",
|
||||
"redo": "Redo change",
|
||||
"compare": "Compare",
|
||||
"compareTitle": "Compare versions",
|
||||
"currentCanvas": "Canvas now",
|
||||
"versionLabel": "Version {n}",
|
||||
"previous": "Previous version",
|
||||
"next": "Next version",
|
||||
"rendering": "Rendering preview…",
|
||||
"showCode": "Show XML",
|
||||
"hideCode": "Hide XML",
|
||||
"drawing": "Drawing the diagram…",
|
||||
"editing": "Changing the diagram…",
|
||||
"loadingLibrary": "Loading a shape library…",
|
||||
"libraryLoaded": "Loaded a shape library",
|
||||
"failed": "This attempt failed",
|
||||
"failedRetrying": "This attempt failed, trying again",
|
||||
"stopped": "Stopped",
|
||||
"truncatedHint": "The reply hit the output limit before the diagram was complete. Ask for a simpler diagram, or raise Max output tokens in Settings > Drawing.",
|
||||
"noChanges": "No visible changes",
|
||||
"listSeparator": ", ",
|
||||
"shapesAddedOne": "added 1 shape",
|
||||
"shapesAddedOther": "added {count} shapes",
|
||||
"edgesAddedOne": "added 1 connector",
|
||||
"edgesAddedOther": "added {count} connectors",
|
||||
"shapesChangedOne": "changed 1 shape",
|
||||
"shapesChangedOther": "changed {count} shapes",
|
||||
"edgesChangedOne": "changed 1 connector",
|
||||
"edgesChangedOther": "changed {count} connectors",
|
||||
"shapesRemovedOne": "removed 1 shape",
|
||||
"shapesRemovedOther": "removed {count} shapes",
|
||||
"edgesRemovedOne": "removed 1 connector",
|
||||
"edgesRemovedOther": "removed {count} connectors",
|
||||
"totals": "{shapes}, {edges}",
|
||||
"shapesTotalOne": "1 shape",
|
||||
"shapesTotalOther": "{count} shapes",
|
||||
"edgesTotalOne": "1 connector",
|
||||
"edgesTotalOther": "{count} connectors",
|
||||
"restoreVersion": "Restore v{n}",
|
||||
"restoredVersion": "Restored v{n}",
|
||||
"undoRestore": "Undo",
|
||||
"noPreview": "No preview",
|
||||
"compareSince": "Since version {n}, the canvas has changed:",
|
||||
"isOnCanvas": "This version is what the canvas shows now.",
|
||||
"differsElsewhere": "The shapes and connectors on the first page are the same as in version {n}; their order, other pages or the page settings differ."
|
||||
},
|
||||
"lobby": {
|
||||
"title": "What would you like to draw?",
|
||||
"lede": "Describe a diagram or upload a screenshot or PDF. You get a draw.io diagram you can keep editing and export.",
|
||||
"placeholder": "For example: a login sequence diagram with SMS codes and retries",
|
||||
"recent": "Recent diagrams",
|
||||
"drawYourself": "Start with a blank canvas",
|
||||
"openFileHint": "Keep working on a diagram you have"
|
||||
}
|
||||
}
|
||||
|
||||
+313
-188
@@ -3,21 +3,18 @@
|
||||
"save": "保存",
|
||||
"cancel": "キャンセル",
|
||||
"close": "閉じる",
|
||||
"confirm": "確認",
|
||||
"clear": "クリア",
|
||||
"edit": "編集",
|
||||
"delete": "削除",
|
||||
"loading": "読み込み中..",
|
||||
"new": "新規"
|
||||
"loading": "読み込み中.."
|
||||
},
|
||||
"nav": {
|
||||
"about": "概要",
|
||||
"editor": "エディタ",
|
||||
"newChat": "新しいチャットを開始",
|
||||
"newChat": "新しい図",
|
||||
"github": "GitHub",
|
||||
"settings": "設定",
|
||||
"hidePanel": "チャットパネルを非表示 (Ctrl+B)",
|
||||
"showPanel": "チャットパネルを表示 (Ctrl+B)",
|
||||
"hidePanel": "チャットパネルを非表示",
|
||||
"showPanel": "チャットパネルを表示",
|
||||
"aiChat": "AI チャット"
|
||||
},
|
||||
"providers": {
|
||||
@@ -39,12 +36,11 @@
|
||||
},
|
||||
"chat": {
|
||||
"placeholder": "ダイアグラムを説明するか、ファイルをアップロード...",
|
||||
"inputLabel": "チャット入力",
|
||||
"send": "送信",
|
||||
"stopGeneration": "生成を停止",
|
||||
"sendMessage": "メッセージを送信",
|
||||
"clearConversation": "会話をクリア",
|
||||
"diagramHistory": "ダイアグラム履歴",
|
||||
"saveDiagram": "ダイアグラムを保存",
|
||||
"uploadFile": "ファイルをアップロード(画像、PDF、テキスト)",
|
||||
"minimalStyle": "ミニマル",
|
||||
"styledMode": "スタイル付き",
|
||||
@@ -52,38 +48,37 @@
|
||||
"regenerate": "応答を再生成",
|
||||
"copyResponse": "応答をコピー",
|
||||
"copied": "コピーしました!",
|
||||
"failedToCopy": "コピーに失敗しました",
|
||||
"failedToCopyDetail": "メッセージのコピーに失敗しました。手動でコピーするか、クリップボードの権限を確認してください。",
|
||||
"goodResponse": "良い応答",
|
||||
"badResponse": "悪い応答",
|
||||
"clickToEdit": "クリックして編集",
|
||||
"editMessage": "メッセージを編集",
|
||||
"saveAndSubmit": "保存して送信",
|
||||
"ExtractURL": "URLから抽出"
|
||||
"ExtractURL": "URLから抽出",
|
||||
"attach": "追加",
|
||||
"placeholderFollowUp": "変更したい内容を入力。図形を選んでから頼むこともできます",
|
||||
"emptyThread": "キャンバスに直接描くか、下で描きたいものを伝えてください。",
|
||||
"attachedImage": "添付画像",
|
||||
"retry": "再試行"
|
||||
},
|
||||
"examples": {
|
||||
"title": "AI でダイアグラムを作成",
|
||||
"subtitle": "作成したいものを説明するか、画像をアップロードして複製",
|
||||
"quickExamples": "クイック例",
|
||||
"paperToDiagram": "論文からダイアグラムへ",
|
||||
"paperToDiagram": "論文を図に",
|
||||
"paperDescription": ".pdf, .txt, .md, .json, .csv, .py, .js, .ts などをアップロード",
|
||||
"animatedDiagram": "アニメーション図",
|
||||
"animatedDescription": "アニメーションコネクタ付きの Transformer アーキテクチャを描画",
|
||||
"awsArchitecture": "AWS アーキテクチャ",
|
||||
"awsArchitecture": "AWS 構成図",
|
||||
"awsDescription": "AWS アイコンでクラウドアーキテクチャ図を作成",
|
||||
"replicateFlowchart": "フローチャートを複製",
|
||||
"replicateFlowchart": "フローチャートを再現",
|
||||
"replicateDescription": "既存のフローチャートをアップロードして複製",
|
||||
"creativeDrawing": "クリエイティブな描画",
|
||||
"creativeDrawing": "自由なイラスト",
|
||||
"creativeDescription": "楽しくてクリエイティブなものを描く",
|
||||
"cachedNote": "例はキャッシュされ、即座に応答します",
|
||||
"cachedNote": "例は保存済みの回答を使うので、すぐに表示され、AI を呼び出しません。",
|
||||
"mcpServer": "MCP サーバー",
|
||||
"mcpDescription": "Claude Desktop、VS Code、Cursor で使用"
|
||||
},
|
||||
"settings": {
|
||||
"title": "設定",
|
||||
"description": "アプリケーション設定を構成します。",
|
||||
"apiKeysModels": "API キーとモデル",
|
||||
"apiKeysModelsDescription": "AI プロバイダーと API キーを設定します。",
|
||||
"accessCode": "アクセスコード",
|
||||
"accessCodePlaceholder": "アクセスコードを入力",
|
||||
"accessCodeDescription": "このアプリケーションを使用するために必要です。",
|
||||
@@ -101,17 +96,10 @@
|
||||
"language": "言語",
|
||||
"languageDescription": "インターフェース言語を選択します。",
|
||||
"theme": "テーマ",
|
||||
"themeDescription": "インターフェースと DrawIO キャンバスのダーク/ライトモード。",
|
||||
"drawioStyle": "DrawIO スタイル",
|
||||
"drawioStyleDescription": "キャンバススタイル",
|
||||
"themeDefault": "デフォルト",
|
||||
"themeDark": "ダーク",
|
||||
"themeMinimal": "ミニマル",
|
||||
"themeSketch": "スケッチ",
|
||||
"themeSimple": "シンプル",
|
||||
"diagramStyle": "ダイアグラムスタイル",
|
||||
"diagramStyleDescription": "ミニマルとスタイル付きの出力を切り替えます。",
|
||||
"sendShortcut": "送信ショートカット",
|
||||
"themeDescription": "画面をライトにするかダークにするか。キャンバスも同じテーマになります。",
|
||||
"diagramStyle": "図のスタイル",
|
||||
"diagramStyleDescription": "AI が新しい図を描くときのスタイル。スタイル付きは色やアイコンを使い、ミニマルは素朴な図形だけにします。",
|
||||
"sendShortcut": "送信のショートカット",
|
||||
"sendShortcutDescription": "メッセージの送信方法を選択します。",
|
||||
"enterToSend": "Enterで送信",
|
||||
"ctrlEnterToSend": "Cmd/Ctrl+Enterで送信",
|
||||
@@ -125,46 +113,49 @@
|
||||
"httpsProxy": "HTTPS プロキシ",
|
||||
"applyProxy": "適用",
|
||||
"proxyApplied": "プロキシ設定が適用されました",
|
||||
"diagramValidation": "ダイアグラム検証(実験的)",
|
||||
"diagramValidationDescription": "視覚言語モデルを使用して生成されたダイアグラムを検証します。GPT-5.2 や Sonnet-4.5 などの VLM が必要です。",
|
||||
"enabled": "有効",
|
||||
"disabled": "無効",
|
||||
"customSystemMessage": "カスタムシステムメッセージ",
|
||||
"diagramValidation": "スクリーンショットで図をチェック(実験的)",
|
||||
"diagramValidationDescription": "描くたびに、画像を読めるモデルがスクリーンショットを確認し、修正を求めます。画像を読めるモデルが必要です。",
|
||||
"customSystemMessage": "カスタム指示",
|
||||
"customSystemMessageDescription": "AIのシステムプロンプトに追加されるカスタム指示を入力します。",
|
||||
"customSystemMessagePlaceholder": "例:ダイアグラムには常に青色のカラースキームを使用...",
|
||||
"maxOutputTokens": "最大出力トークン数",
|
||||
"maxOutputTokens": "出力トークン上限",
|
||||
"maxOutputTokensDescription": "1回の応答の予算で、思考過程とダイアグラムの XML が共有します。AI が考え続けてダイアグラムが生成されない場合は大きくしてください。空欄ならデフォルト値を使います。",
|
||||
"panelVisibility": "ロビーパネル",
|
||||
"panelVisibilityDescription": "チャットロビーに表示するパネルを選択します。",
|
||||
"showRecentChats": "最近のチャット",
|
||||
"showMyTemplates": "マイテンプレート",
|
||||
"showQuickExamples": "クイック例"
|
||||
"tabModels": "モデル",
|
||||
"tabAbout": "このアプリについて",
|
||||
"themeLight": "ライト",
|
||||
"themeDarkMode": "ダーク",
|
||||
"themeSystem": "システムに合わせる",
|
||||
"accessCodeSaved": "アクセスコードを保存しました",
|
||||
"proxyInvalid": "プロキシのアドレスは http:// または https:// で始めてください",
|
||||
"proxyFailed": "プロキシ設定を適用できませんでした",
|
||||
"appVersion": "バージョン",
|
||||
"projectWebsite": "プロジェクトのサイト",
|
||||
"tabGeneral": "一般",
|
||||
"tabDrawing": "描画",
|
||||
"sectionInterface": "表示",
|
||||
"sectionAccess": "アクセス"
|
||||
},
|
||||
"save": {
|
||||
"title": "ダイアグラムを保存",
|
||||
"description": "形式とファイル名を選択してダイアグラムを保存します。",
|
||||
"title": "図をエクスポート",
|
||||
"description": "形式とファイル名を選んでください。",
|
||||
"format": "形式",
|
||||
"filename": "ファイル名",
|
||||
"filenamePlaceholder": "ファイル名を入力",
|
||||
"formats": {
|
||||
"drawio": "Draw.io XML",
|
||||
"drawio": "draw.io ファイル",
|
||||
"png": "PNG 画像",
|
||||
"svg": "SVG 画像",
|
||||
"xmlsvg": "編集可能 SVG"
|
||||
"xmlsvg": "編集できる SVG"
|
||||
},
|
||||
"savedSuccessfully": "保存完了!"
|
||||
},
|
||||
"history": {
|
||||
"title": "ダイアグラム履歴",
|
||||
"description": "AI 修正前に保存された各ダイアグラム。\nダイアグラムをクリックして復元",
|
||||
"noHistory": "まだ履歴がありません。メッセージを送信してダイアグラム履歴を作成してください。",
|
||||
"version": "バージョン",
|
||||
"restoreTo": "バージョン {version} に復元しますか?"
|
||||
"savedSuccessfully": "エクスポートしました",
|
||||
"hints": {
|
||||
"drawio": "すべて編集できるまま保存",
|
||||
"png": "スライドや文書向けの画像",
|
||||
"svg": "拡大してもぼやけない画像",
|
||||
"xmlsvg": "draw.io でも開ける画像"
|
||||
}
|
||||
},
|
||||
"dialogs": {
|
||||
"clearTitle": "すべてクリアしますか?",
|
||||
"clearDescription": "現在の会話をクリアし、ダイアグラムをリセットします。この操作は元に戻せません。",
|
||||
"clearEverything": "すべてクリア",
|
||||
"clearSuccess": "新しいチャットを開始しました"
|
||||
},
|
||||
"errors": {
|
||||
@@ -189,9 +180,18 @@
|
||||
"sessionSaveFailed": "このチャットを保存できませんでした。ブラウザのストレージがいっぱいの可能性があります。履歴から古いチャットを削除して、もう一度お試しください。",
|
||||
"sessionSaveFailedLeave": "このチャットを保存できませんでした。ブラウザのストレージがいっぱいの可能性があります。保存せずに続けて、新しいチャットの一覧から古いチャットを削除できます。",
|
||||
"continueWithoutSaving": "保存せずに続ける",
|
||||
"notADiagramFile": "{name} は draw.io の図ではありません。",
|
||||
"fileTooLong": "{name}:内容が上限の {limit}k 文字を超えています({size}k 文字)",
|
||||
"fileReadFailed": "ファイルを読み込めませんでした:{name}",
|
||||
"answerEndedEarly": "図を描き終える前に回答が終わりました。",
|
||||
"attachmentsStillReading": "添付ファイルをまだ読み込んでいます。読み込みが終わってから送信してください。",
|
||||
"sendInProgress": "前のメッセージを送信しています。少し待ってからもう一度お試しください。",
|
||||
"answerInProgress": "回答をまだ受信しています。終わってからもう一度送信してください。",
|
||||
"cannotResend": "このメッセージは送り直せません。送信時の図が保存されていません。",
|
||||
"llm": {
|
||||
"invalid_api_key": "プロバイダーが API キーを拒否しました。モデル設定で確認してください。",
|
||||
"forbidden": "プロバイダーがリクエストを拒否しました。このキーにはこのモデルまたはリージョンの利用権限がない可能性があります。",
|
||||
"server_key_forbidden": "本日の無料枠を使い切りました。明日になると自動的に回復します。モデル設定でご自身の API キーを入力すると、引き続きご利用いただけます。",
|
||||
"model_not_found": "プロバイダーがこのモデルを認識できません。モデル設定でモデル ID を確認してください。",
|
||||
"insufficient_quota": "プロバイダーのアカウントの残高または利用枠がなくなりました。",
|
||||
"rate_limited": "プロバイダーがリクエスト数を制限しています。少し待ってから再試行してください。",
|
||||
@@ -211,14 +211,13 @@
|
||||
"tpmLimit": "レート制限",
|
||||
"tpmMessage": "リクエストが多すぎます。しばらくお待ちください。",
|
||||
"tpmMessageDetailed": "レート制限に達しました({limit}トークン/分)。{seconds}秒待ってからもう一度リクエストしてください。",
|
||||
"messageApi": "今日のデモ利用上限に達してしまったようです。楽しんでいただけて本当に嬉しいです。このデモはByteDance Doubaoのご厚意により提供されていますが、皆様に公平にご利用いただくため、少し制限を設けさせていただいております。",
|
||||
"messageApi": "今日のデモ利用上限に達したようです。楽しんでいただけて嬉しいです。皆様に公平にご利用いただくため、利用量に上限を設けています。",
|
||||
"messageApiSelfHosted": null,
|
||||
"messageToken": "今日のトークン利用上限に達してしまったようです。楽しんでいただけて本当に嬉しいです。このデモはByteDance Doubaoのご厚意により提供されていますが、皆様に公平にご利用いただくため、少し制限を設けさせていただいております。",
|
||||
"messageToken": "今日のトークン利用上限に達したようです。楽しんでいただけて嬉しいです。皆様に公平にご利用いただくため、利用量に上限を設けています。",
|
||||
"messageTokenSelfHosted": null,
|
||||
"tip": "<strong>ヒント:</strong>独自の API キーを使用する(設定アイコンをクリック)か、プロジェクトをセルフホストしてこれらの制限を回避できます。",
|
||||
"tipSelfHosted": "<strong>ヒント:</strong>設定で独自の API キーを設定することで、引き続きサービスをご利用いただけます。",
|
||||
"reset": "制限は明日リセットされます。ご理解ありがとうございます。",
|
||||
"doubaoSponsorship": "<a href=\"{link}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline hover:text-foreground\">こちらから登録</a>すると、各モデル(Doubao、DeepSeek、Kimi含む)で50万トークンを無料で取得できます。モデル設定でAPIキーを設定してください。",
|
||||
"configModel": "APIキーを使用",
|
||||
"selfHost": "セルフホスト",
|
||||
"sponsor": "スポンサー",
|
||||
@@ -226,11 +225,6 @@
|
||||
"usedOf": "{used}/{limit}"
|
||||
},
|
||||
"tools": {
|
||||
"generateDiagram": "ダイアグラムを生成",
|
||||
"editDiagram": "ダイアグラムを編集",
|
||||
"appendDiagram": "ダイアグラムに追加",
|
||||
"complete": "完了",
|
||||
"error": "エラー",
|
||||
"truncated": "切り捨て"
|
||||
},
|
||||
"file": {
|
||||
@@ -245,7 +239,8 @@
|
||||
"extract": "抽出",
|
||||
"Cancel": "キャンセル",
|
||||
"enterUrl": "URLを入力してください",
|
||||
"invalidFormat": "無効なURL形式です"
|
||||
"invalidFormat": "無効なURL形式です",
|
||||
"failed": "このページを読み込めませんでした"
|
||||
},
|
||||
"reasoning": {
|
||||
"thinking": "考え中...",
|
||||
@@ -278,18 +273,19 @@
|
||||
"sessionHistory": {
|
||||
"tooltip": "チャット履歴",
|
||||
"newChat": "新しいチャット",
|
||||
"empty": "チャット履歴はまだありません",
|
||||
"empty": "まだ図はありません",
|
||||
"emptyHint": "会話を始めてください",
|
||||
"today": "今日",
|
||||
"yesterday": "昨日",
|
||||
"thisWeek": "今週",
|
||||
"earlier": "それ以前",
|
||||
"deleteTitle": "このチャットを削除しますか?",
|
||||
"deleteDescription": "このチャットセッションとダイアグラムは完全に削除されます。この操作は取り消せません。",
|
||||
"recentChats": "最近のチャット",
|
||||
"deleteTitle": "この図を削除しますか?",
|
||||
"deleteDescription": "図とその会話は完全に削除されます。",
|
||||
"justNow": "たった今",
|
||||
"searchPlaceholder": "チャットを検索...",
|
||||
"noResults": "チャットが見つかりません"
|
||||
"searchPlaceholder": "図を検索…",
|
||||
"noResults": "チャットが見つかりません",
|
||||
"rename": "名前を変更",
|
||||
"busyHint": "回答が終わると選べます"
|
||||
},
|
||||
"validation": {
|
||||
"title": "ダイアグラムを検証",
|
||||
@@ -310,8 +306,6 @@
|
||||
"regenerateWithFeedback": "検証フィードバックを使用してダイアグラムを再生成"
|
||||
},
|
||||
"modelConfig": {
|
||||
"title": "AIモデル設定",
|
||||
"description": "複数のAIプロバイダーとモデルを設定",
|
||||
"configure": "設定",
|
||||
"addProvider": "プロバイダーを追加",
|
||||
"addModel": "モデルを追加",
|
||||
@@ -321,17 +315,11 @@
|
||||
"deleteProvider": "プロバイダーを削除",
|
||||
"deleteModel": "モデルを削除",
|
||||
"noModels": "モデルが設定されていません。モデルを追加してください。",
|
||||
"selectProvider": "プロバイダーを選択または追加してください",
|
||||
"configureMultiple": "複数のAIプロバイダーを設定して簡単に切り替え",
|
||||
"apiKeyStored": "APIキーはブラウザにローカル保存されます",
|
||||
"test": "テスト",
|
||||
"validationError": "検証に失敗しました",
|
||||
"addModelFirst": "検証するには少なくとも1つのモデルを追加してください",
|
||||
"providers": "プロバイダー",
|
||||
"addProviderHint": "プロバイダーを追加して開始",
|
||||
"verified": "検証済み",
|
||||
"configuration": "設定",
|
||||
"validationError": "テストに失敗しました",
|
||||
"addModelFirst": "先にモデルを追加してください。",
|
||||
"displayName": "表示名",
|
||||
"bedrockApiKey": "Bedrock API キー",
|
||||
"bedrockApiKeyHint": "API キーを入力すれば、下のアクセスキーは不要です。",
|
||||
"awsAccessKeyId": "AWS アクセスキー ID",
|
||||
"awsSecretAccessKey": "AWS シークレットアクセスキー",
|
||||
"awsRegion": "AWS リージョン",
|
||||
@@ -342,7 +330,6 @@
|
||||
"baseUrl": "ベース URL",
|
||||
"optional": "(オプション)",
|
||||
"getApiKey": "API キーを取得",
|
||||
"fetchModels": "プロバイダーからモデル一覧を取得",
|
||||
"noTools": "ツール呼び出し非対応",
|
||||
"mayNotDraw": "models.dev によると、このモデルはツール呼び出しに対応していないため、作図できない可能性があります。",
|
||||
"requestUrl": "リクエスト先: {url}",
|
||||
@@ -353,49 +340,110 @@
|
||||
"models": "モデル",
|
||||
"customModelId": "カスタムモデル ID...",
|
||||
"allAdded": "すべて追加済み",
|
||||
"suggested": "おすすめ",
|
||||
"noModelsConfigured": "モデルが設定されていません",
|
||||
"modelIdEmpty": "モデル ID は空にできません",
|
||||
"modelIdExists": "このモデル ID は既に存在します",
|
||||
"configureProviders": "AI プロバイダーを設定",
|
||||
"selectProviderHint": "リストからプロバイダーを選択するか、新規追加して API キーとモデルを設定",
|
||||
"deleteConfirmDesc": "{name} を削除してもよろしいですか?設定されたすべてのモデルが削除され、元に戻せません。",
|
||||
"typeToConfirm": "確認のため「{name}」と入力",
|
||||
"typeProviderName": "プロバイダー名を入力...",
|
||||
"modelsConfiguredCount": "{count} 個のモデルを設定済み",
|
||||
"validationFailedCount": "{count} 個のモデルの検証に失敗",
|
||||
"requestFailed": "リクエストに失敗しました({status})",
|
||||
"cancel": "キャンセル",
|
||||
"delete": "削除",
|
||||
"clickToChange": "(クリックして変更)",
|
||||
"usingServerDefault": "サーバーデフォルトモデルを使用中",
|
||||
"selectModel": "モデルを選択",
|
||||
"searchModels": "モデルを検索...",
|
||||
"noVerifiedModels": "検証済みのモデルがありません。先にモデルをテストしてください。",
|
||||
"noModelsFound": "モデルが見つかりません。",
|
||||
"default": "デフォルト",
|
||||
"serverDefault": "サーバーデフォルト",
|
||||
"serverDefault": "サーバーのモデル",
|
||||
"serverModels": "サーバーモデル",
|
||||
"userModels": "ユーザーモデル",
|
||||
"configureModels": "モデルを設定...",
|
||||
"onlyVerifiedShown": "検証済みのモデルのみ表示",
|
||||
"showUnvalidatedModels": "未検証のモデルを表示",
|
||||
"allModelsShown": "すべてのモデルを表示(未検証を含む)",
|
||||
"unvalidatedModelWarning": "このモデルは検証されていません",
|
||||
"serverDefaultModel": "サーバーデフォルトモデル",
|
||||
"showValue": "値を表示",
|
||||
"hideValue": "値を非表示"
|
||||
"hideValue": "値を非表示",
|
||||
"myProviders": "マイプロバイダー",
|
||||
"inUse": "使用中",
|
||||
"listSeparator": "、",
|
||||
"serverModelsTitle": "このサーバーのモデル",
|
||||
"serverDefaultSummary": "API キーは不要です。サーバーの既定のモデルを使います。",
|
||||
"statusError": "{count} 個でエラー",
|
||||
"statusIncomplete": "設定が終わっていません",
|
||||
"statusUntested": "{count} 個が未テスト",
|
||||
"statusOk": "{count} 個が使用可能",
|
||||
"noModelsYet": "モデルはまだありません",
|
||||
"keysStayLocal": "API キーはこの端末のブラウザーにだけ保存され、リクエストのときだけサーバーに送られます。",
|
||||
"useOwnKey": "自分の API キーを使う",
|
||||
"useOwnKeyHint": "プロバイダーを追加すると、チャットのモデル選択でそのモデルを使えます。まず一つ選んでください:",
|
||||
"viewAllProviders": "{count} 個のプロバイダーをすべて表示",
|
||||
"searchProviders": "プロバイダーを検索(例:DeepSeek、Qwen、Ollama)",
|
||||
"noProvidersFound": "一致するプロバイダーはありません。",
|
||||
"groupVendors": "モデル開発元",
|
||||
"groupAggregators": "アグリゲーター",
|
||||
"groupCloud": "クラウド",
|
||||
"groupSelfHosted": "セルフホスト",
|
||||
"noteBedrock": "AWS 認証情報",
|
||||
"noteVertex": "Express モードのキー",
|
||||
"noteAzure": "キーとリソース URL",
|
||||
"noteEdgeone": "キー不要",
|
||||
"noteOllama": "キーは任意",
|
||||
"noteSglang": "サーバーの URL",
|
||||
"added": "追加済み",
|
||||
"awsCredentials": "AWS 認証情報",
|
||||
"bedrockAuthApiKey": "Bedrock API キー",
|
||||
"bedrockAuthAccessKey": "アクセスキー",
|
||||
"moreOptions": "その他のオプション:ベース URL、表示名",
|
||||
"moreOptionsName": "その他のオプション:表示名",
|
||||
"keyRejected": "プロバイダーがこの API キーを拒否しました。上のキーが最後までコピーされているか確認してください。",
|
||||
"modelNotFound": "プロバイダーがこのモデル ID を見つけられません。綴りを確認してください。",
|
||||
"modelWorks": "使用可能",
|
||||
"modelWorksTime": "使用可能 · {seconds} 秒",
|
||||
"modelFailed": "エラー",
|
||||
"modelUntested": "未テスト",
|
||||
"needKey": "先に API キーを入力してください。",
|
||||
"needAws": "先に AWS 認証情報とリージョンを入力してください。",
|
||||
"needModel": "先にモデルを追加してください。",
|
||||
"stepConnect": "接続",
|
||||
"edgeoneNoKey": "EdgeOne Pages はこのサイトのデプロイに付属するモデルサービスを使うため、API キーは不要です。",
|
||||
"stepModels": "モデル",
|
||||
"fetchAllModels": "{name} から全モデルを取得",
|
||||
"suggestedLabel": "おすすめ:",
|
||||
"orTypeModelId": "または別のモデル ID を入力",
|
||||
"add": "追加",
|
||||
"browseModels": "モデル一覧",
|
||||
"stepTest": "テスト",
|
||||
"testHint": "各モデルに短いメッセージを送り、キーとモデルが使えるか確認します。",
|
||||
"testOne": "{model} をテスト",
|
||||
"testAll": "{count} 個のモデルをすべてテスト",
|
||||
"testPassedOne": "{model} は使用できます",
|
||||
"testPassedAll": "{count} 個のモデルすべてが使用できます",
|
||||
"answeredIn": "(応答 {seconds} 秒)",
|
||||
"useInChat": "チャットで {model} を使う",
|
||||
"backToProviders": "プロバイダー一覧に戻る",
|
||||
"deleteProviderOnly": "{name} を削除",
|
||||
"addProviderEntry": "プロバイダーを追加…",
|
||||
"awsKeysRejected": "AWS がこのアクセスキーを拒否しました。2 つとも最後までコピーされているか確認してください。",
|
||||
"needAzure": "先に API キーと Azure リソースのベース URL を入力してください。",
|
||||
"validationFailedCountOne": "{count} 個のモデルがテストに失敗しました",
|
||||
"validationFailedCountOther": "{count} 個のモデルがテストに失敗しました",
|
||||
"deleteProviderNamedOne": "{name} とそのモデルを削除",
|
||||
"deleteProviderNamedOther": "{name} と {count} 個のモデルを削除",
|
||||
"serverModelsSummaryOne": "API キーは不要です。{count} 個:{names}",
|
||||
"serverModelsSummaryOther": "API キーは不要です。{count} 個:{names}",
|
||||
"noModelsReturned": "プロバイダーからモデルが返されませんでした。",
|
||||
"awsSessionToken": "AWS セッショントークン(任意)",
|
||||
"awsSessionTokenHint": "一時的な認証情報(ASIA で始まるアクセスキー)の場合だけ必要です。",
|
||||
"bedrockBothSaved": "このプロバイダーにはアクセスキーも保存されていますが、API キーがある間は使われません。",
|
||||
"removeAccessKeys": "アクセスキーを削除"
|
||||
},
|
||||
"templates": {
|
||||
"title": "マイテンプレート",
|
||||
"subtitle": "素早いダイアグラム作成のための個人的なプロンプトライブラリ",
|
||||
"emptyTitle": "テンプレートがありません",
|
||||
"emptyDescription": "最初のテンプレートを作成して、個人的なプロンプトライブラリを構築しましょう",
|
||||
"createFirst": "最初のテンプレートを作成",
|
||||
"emptyTitle": "保存したプロンプトはまだありません",
|
||||
"emptyDescription": "「…の AWS 構成図を描いて」のようによく使うプロンプトを保存すると、ここに表示されます。",
|
||||
"createFirst": "最初のプロンプトを保存",
|
||||
"neverUsed": "未使用",
|
||||
"usedCount": "{count} 回使用",
|
||||
"myTemplates": "マイテンプレート",
|
||||
"createTitle": "テンプレート作成",
|
||||
"createDescription": "再利用のためにプロンプトを保存します。テンプレートを使用すると、一般的なワークフローを素早く開始できます。",
|
||||
"myTemplates": "保存したプロンプト",
|
||||
"createTitle": "プロンプトを保存",
|
||||
"createDescription": "あとで使えるようにプロンプトを保存します。",
|
||||
"promptLabel": "プロンプト",
|
||||
"promptPlaceholder": "作成するダイアグラムを説明してください...",
|
||||
"promptRequired": "プロンプトは必須です",
|
||||
@@ -403,144 +451,145 @@
|
||||
"titlePlaceholder": "タイトルを入力",
|
||||
"titleHint": "空欄の場合はプロンプトの最初の20文字が使用されます",
|
||||
"descriptionLabel": "説明",
|
||||
"descriptionPlaceholder": "このテンプレートの説明を追加",
|
||||
"pinnedLabel": "テンプレートをピン留め",
|
||||
"pinnedHint": "ピン留めされたテンプレートはリストの上部に表示されます",
|
||||
"createButton": "テンプレート作成",
|
||||
"createFailed": "テンプレートの作成に失敗しました。もう一度お試しください。",
|
||||
"editTitle": "テンプレート編集",
|
||||
"editDescription": "テンプレートの内容と設定を更新します。",
|
||||
"updateFailed": "テンプレートの更新に失敗しました。もう一度お試しください。",
|
||||
"descriptionPlaceholder": "このプロンプトの用途",
|
||||
"pinnedLabel": "先頭に固定",
|
||||
"pinnedHint": "固定したプロンプトはリストの先頭に表示されます",
|
||||
"createButton": "保存",
|
||||
"createFailed": "プロンプトを保存できませんでした。もう一度お試しください。",
|
||||
"editTitle": "プロンプトを編集",
|
||||
"editDescription": "プロンプトと設定を変更します。",
|
||||
"updateFailed": "プロンプトを更新できませんでした。もう一度お試しください。",
|
||||
"duplicate": "複製",
|
||||
"copySuffix": "(コピー)",
|
||||
"deleteTitle": "このテンプレートを削除しますか?",
|
||||
"deleteDescription": "このテンプレートは完全に削除されます。この操作は取り消せません。",
|
||||
"deleteTitle": "このプロンプトを削除しますか?",
|
||||
"deleteDescription": "プロンプトは完全に削除されます。",
|
||||
"confirmSendTitle": "現在の入力を置き換えますか?",
|
||||
"confirmSendDescription": "未送信のコンテンツがあります。このテンプレートを送信すると置き換えられます。",
|
||||
"confirmSendButton": "テンプレートを送信",
|
||||
"searchPlaceholder": "テンプレートを検索...",
|
||||
"searchNoResults": "検索に一致するテンプレートがありません",
|
||||
"confirmSendDescription": "入力欄に未送信の内容があります。このプロンプトを送ると置き換わります。",
|
||||
"confirmSendButton": "送信",
|
||||
"searchPlaceholder": "プロンプトを検索…",
|
||||
"searchNoResults": "一致するプロンプトはありません",
|
||||
"pin": "上部にピン留め",
|
||||
"unpin": "ピン留め解除",
|
||||
"saveAsTemplate": "テンプレートとして保存",
|
||||
"exportTemplates": "テンプレートをエクスポート",
|
||||
"importTemplates": "テンプレートをインポート",
|
||||
"exportEmpty": "エクスポートするテンプレートがありません",
|
||||
"exportSuccess": "{count} 件のテンプレートをエクスポートしました",
|
||||
"saveAsTemplate": "このプロンプトを保存",
|
||||
"exportTemplates": "プロンプトをエクスポート",
|
||||
"importTemplates": "プロンプトをインポート",
|
||||
"exportEmpty": "エクスポートするプロンプトがありません",
|
||||
"exportSuccess": "{count} 件のプロンプトをエクスポートしました",
|
||||
"importNoFile": "JSON ファイルを選択してください",
|
||||
"importFailed": "インポートに失敗しました:{error}",
|
||||
"importSuccess": "{imported} 件インポート、{skipped} 件の重複をスキップしました"
|
||||
"importSuccess": "{imported} 件のプロンプトをインポートし、重複 {skipped} 件をスキップしました",
|
||||
"saveDisabledHint": "先にプロンプトを入力してください"
|
||||
},
|
||||
"admin": {
|
||||
"title": "管理者設定",
|
||||
"loginPrompt": "サーバー設定を管理するには、管理者パスワード(ADMIN_PASSWORD 環境変数)を入力してください。",
|
||||
"loginPrompt": "管理者パスワード(環境変数 ADMIN_PASSWORD)を入力してください",
|
||||
"password": "パスワード",
|
||||
"signIn": "ログイン",
|
||||
"signingIn": "ログイン中…",
|
||||
"loginFailed": "ログインに失敗しました",
|
||||
"precedence": "ファイルが環境変数を上書き · 環境変数がデフォルトを上書き",
|
||||
"notWritable": "このデプロイ環境では設定ファイルに書き込めません(サーバーレス環境には永続ディスクがありません)。設定は読み取り専用で表示されます——代わりに環境変数で構成してください。",
|
||||
"settingGroups": "設定グループ",
|
||||
"enabled": "有効",
|
||||
"disabled": "無効",
|
||||
"enableGroup": "{group} を有効化",
|
||||
"precedence": "優先順位:このページ > 環境変数 > 既定値",
|
||||
"notWritable": "この環境では設定を保存できず、表示のみです。環境変数で設定してください",
|
||||
"settingGroups": "設定の分類",
|
||||
"enabled": "オン",
|
||||
"disabled": "オフ",
|
||||
"enableGroup": "{group} をオンにする",
|
||||
"unsavedChanges": "未保存の変更があります",
|
||||
"saved": "設定を保存しました。変更は即座に反映されます。",
|
||||
"saveFailed": "保存に失敗しました。接続を確認して再試行してください。",
|
||||
"invalidSettings": "一部の設定が無効です。",
|
||||
"discard": "破棄",
|
||||
"saved": "保存しました。「再起動が必要」の項目以外はすぐに反映されます",
|
||||
"saveFailed": "保存に失敗しました。接続を確認してもう一度お試しください",
|
||||
"invalidSettings": "入力に誤りがある設定があります。項目の下の説明を確認してください",
|
||||
"discard": "変更を破棄",
|
||||
"saveChanges": "変更を保存",
|
||||
"saving": "保存中…",
|
||||
"sourceSaved": "保存済み",
|
||||
"sourceSaved": "このページ",
|
||||
"sourceEnv": "環境変数",
|
||||
"sourceSavedTitle": "管理者設定ファイルで設定",
|
||||
"sourceEnvTitle": "環境変数で設定",
|
||||
"sourceSavedTitle": "このページで設定した値",
|
||||
"sourceEnvTitle": "環境変数による設定",
|
||||
"restartRequired": "再起動が必要",
|
||||
"modified": "変更済み",
|
||||
"notSet": "未設定",
|
||||
"savedReplace": "保存済み({hint})——入力して置き換え",
|
||||
"showValue": "値を表示",
|
||||
"hideValue": "値を非表示",
|
||||
"removeValue": "値を削除",
|
||||
"removeValueTitle": "保存された値を削除",
|
||||
"savedReplace": "保存済み({hint})。新しい値を入力すると置き換わります",
|
||||
"showValue": "表示",
|
||||
"hideValue": "非表示",
|
||||
"removeValue": "クリア",
|
||||
"removeValueTitle": "保存した値をクリア",
|
||||
"resetToDefault": "デフォルトに戻す",
|
||||
"models": "モデル",
|
||||
"modelsDescription": "全ユーザーが利用できるサーバー側のプロバイダーとモデル——個人の API キーは不要です。ユーザーがモデルを選択しない場合、デフォルトプロバイダーの最初のモデルが使用されます。",
|
||||
"addProviderHint": "プロバイダーを追加して、全ユーザーにサーバー側モデルを提供します。",
|
||||
"selectProviderHint": "プロバイダーを選択または追加して、その資格情報とモデルを構成します。",
|
||||
"addProviderToOfferModels": "ユーザーにこのプロバイダーを公開するには、モデルを少なくとも 1 つ追加してください。",
|
||||
"managedViaEnv": "(環境変数で管理)",
|
||||
"envReadOnly": "AI_MODELS_CONFIG / ai-models.json で定義——ここでは読み取り専用です。変更するには環境構成を編集してください。",
|
||||
"modelsDescription": "全ユーザーが使えるモデル。個人の API キーは不要です",
|
||||
"addProviderHint": "プロバイダーを追加して、全ユーザーにモデルを提供します",
|
||||
"selectProviderHint": "プロバイダーを選択または追加し、キーとモデルを入力します",
|
||||
"addProviderToOfferModels": "モデルを 1 つ以上追加すると、ユーザーにこのプロバイダーが表示されます",
|
||||
"managedViaEnv": "(環境変数)",
|
||||
"envReadOnly": "AI_MODELS_CONFIG / ai-models.json で定義されています。ここでは表示のみで、変更はそちらで行ってください",
|
||||
"defaultModel": "デフォルトモデル",
|
||||
"noModelsConfigured": "モデルが構成されていません",
|
||||
"noModelsConfigured": "モデルはまだありません",
|
||||
"modelCount": "{count} 個のモデル",
|
||||
"modelCountPlural": "{count} 個のモデル",
|
||||
"default": "デフォルト",
|
||||
"setAsDefault": "デフォルトプロバイダーに設定",
|
||||
"defaultProvider": "デフォルトプロバイダー",
|
||||
"setAsDefault": "既定のプロバイダーにする",
|
||||
"defaultProvider": "既定のプロバイダー",
|
||||
"modelIdPlaceholder": "モデル ID…",
|
||||
"addModel": "モデルを追加",
|
||||
"suggested": "おすすめ",
|
||||
"test": "テスト",
|
||||
"testOk": "正常({ms}ms)",
|
||||
"testOk": "成功({ms} ms)",
|
||||
"testFailed": "失敗",
|
||||
"removeModel": "{model} を削除",
|
||||
"deleteProviderTitle": "{name} を削除しますか?",
|
||||
"deleteProviderDesc": "保存後、その資格情報とモデルはサーバーから削除されます。",
|
||||
"deleteProviderDesc": "保存すると、このプロバイダーのキーとモデルがサーバーから削除されます",
|
||||
"cancel": "キャンセル",
|
||||
"delete": "削除",
|
||||
"groups": {
|
||||
"generation": {
|
||||
"title": "生成",
|
||||
"description": "すべてのチャットリクエストに適用される出力パラメーター。"
|
||||
"title": "応答の設定",
|
||||
"description": "AI の応答のしかたを決めます。すべての会話に適用されます"
|
||||
},
|
||||
"access": {
|
||||
"title": "アクセス制御",
|
||||
"description": "このデプロイを使用できるユーザーを制限します。"
|
||||
"title": "アクセス権",
|
||||
"description": "このサイトを使える人を制限します"
|
||||
},
|
||||
"features": {
|
||||
"title": "機能",
|
||||
"description": "オプション機能とセキュリティの切り替え。"
|
||||
"title": "オプション機能",
|
||||
"description": "追加機能と安全のための設定"
|
||||
},
|
||||
"observability": {
|
||||
"title": "オブザーバビリティ",
|
||||
"description": "LLM 呼び出しの Langfuse トレース。"
|
||||
"title": "呼び出し記録",
|
||||
"description": "モデルの呼び出しを Langfuse に記録します"
|
||||
},
|
||||
"quota": {
|
||||
"title": "クォータとレート制限",
|
||||
"description": "IP ごとの使用制限。強制には DynamoDB テーブルが必要です。"
|
||||
"title": "使用量の制限",
|
||||
"description": "IP ごとの制限。DynamoDB テーブルがあるときだけ有効です"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"TEMPERATURE": {
|
||||
"label": "温度",
|
||||
"description": "温度を受け付けない推論モデルの場合は未設定のままにしてください。"
|
||||
"description": "高いほどランダムになります。温度に対応しない推論モデルでは空にしてください"
|
||||
},
|
||||
"MAX_OUTPUT_TOKENS": {
|
||||
"label": "最大出力トークン数"
|
||||
"label": "出力トークン上限"
|
||||
},
|
||||
"ACCESS_CODE_LIST": {
|
||||
"label": "アクセスコード",
|
||||
"description": "カンマ区切りのリスト。チャットにはいずれかの入力が必要です。空 = オープンアクセス。"
|
||||
"description": "複数はカンマ区切り。いずれかを入力しないと使えません。空なら制限なし"
|
||||
},
|
||||
"ENABLE_VLM_VALIDATION": {
|
||||
"label": "VLM 図検証",
|
||||
"description": "ビジョンモデルで生成された図を視覚的に検証します。"
|
||||
"label": "図のチェック",
|
||||
"description": "描画後、画像を読めるモデルがスクリーンショットをチェックします"
|
||||
},
|
||||
"VALIDATION_MODEL": {
|
||||
"label": "検証モデル",
|
||||
"description": "空の場合はデフォルトの AI モデルにフォールバックします。"
|
||||
"label": "チェック用モデル",
|
||||
"description": "空なら既定のモデルを使います"
|
||||
},
|
||||
"VALIDATION_TIMEOUT": {
|
||||
"label": "検証タイムアウト(ms)"
|
||||
"label": "チェックのタイムアウト(ms)"
|
||||
},
|
||||
"ENABLE_HISTORY_XML_REPLACE": {
|
||||
"label": "履歴 XML 圧縮",
|
||||
"description": "履歴内の古い図 XML をプレースホルダーで置き換えます。"
|
||||
"label": "古い図を省略",
|
||||
"description": "会話履歴の古い図は短い印だけ残します"
|
||||
},
|
||||
"ALLOW_PRIVATE_URLS": {
|
||||
"label": "プライベート URL を許可",
|
||||
"description": "オフにすると、プライベート IP や内部ホスト名へのリクエストをブロックします(SSRF 保護)。"
|
||||
"label": "内部ネットワークへのアクセス",
|
||||
"description": "オフにすると、ユーザーが指定するモデルの URL に内部アドレスを使えなくなり、安全です"
|
||||
},
|
||||
"LANGFUSE_PUBLIC_KEY": {
|
||||
"label": "Langfuse Public Key"
|
||||
@@ -549,30 +598,106 @@
|
||||
"label": "Langfuse Secret Key"
|
||||
},
|
||||
"LANGFUSE_BASEURL": {
|
||||
"label": "Langfuse Base URL"
|
||||
"label": "Langfuse の URL"
|
||||
},
|
||||
"DAILY_REQUEST_LIMIT": {
|
||||
"label": "1 日あたりのリクエスト上限",
|
||||
"description": "IP ごと 1 日あたり。"
|
||||
"label": "1 日のリクエスト数",
|
||||
"description": "IP ごとの 1 日あたりのリクエスト数の上限"
|
||||
},
|
||||
"DAILY_TOKEN_LIMIT": {
|
||||
"label": "1 日あたりのトークン上限",
|
||||
"description": "IP ごと 1 日あたり。"
|
||||
"label": "1 日のトークン数",
|
||||
"description": "IP ごとの 1 日あたりのトークン使用量の上限"
|
||||
},
|
||||
"TPM_LIMIT": {
|
||||
"label": "1 分あたりのトークン数"
|
||||
},
|
||||
"DYNAMODB_QUOTA_TABLE": {
|
||||
"label": "DynamoDB テーブル",
|
||||
"description": "空の場合、クォータの強制は無効になります。"
|
||||
"label": "DynamoDB テーブル名",
|
||||
"description": "空なら使用量を制限しません"
|
||||
},
|
||||
"DYNAMODB_REGION": {
|
||||
"label": "DynamoDB リージョン"
|
||||
},
|
||||
"QUOTA_TIMEZONE": {
|
||||
"label": "クォータタイムゾーン",
|
||||
"description": "1 日のリセット境界に使用するタイムゾーン。"
|
||||
"label": "タイムゾーン",
|
||||
"description": "1 日の使用量はこのタイムゾーンの 0 時にリセットされます"
|
||||
}
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"export": "エクスポート",
|
||||
"openFile": ".drawio ファイルを開く",
|
||||
"canvasLoading": "キャンバスを読み込み中…",
|
||||
"askAi": "ここを AI に直してもらう",
|
||||
"untitled": "無題の図",
|
||||
"mobileCanvas": "キャンバス",
|
||||
"mobileChat": "チャット"
|
||||
},
|
||||
"selection": {
|
||||
"one": "選択中:{label}",
|
||||
"many": "{count} 個の図形を選択中",
|
||||
"shape": "図形",
|
||||
"connector": "コネクタ",
|
||||
"remove": "選択した図形を送らない",
|
||||
"placeholder": "選択した図形をどう変えたいか書いてください"
|
||||
},
|
||||
"versions": {
|
||||
"strip": "バージョン",
|
||||
"created": "図を描きました",
|
||||
"edited": "図を修正しました",
|
||||
"undone": "この変更は取り消しました",
|
||||
"undo": "変更を取り消す",
|
||||
"redo": "変更をやり直す",
|
||||
"compare": "比較",
|
||||
"compareTitle": "バージョンを比較",
|
||||
"currentCanvas": "現在のキャンバス",
|
||||
"versionLabel": "バージョン {n}",
|
||||
"previous": "前のバージョン",
|
||||
"next": "次のバージョン",
|
||||
"rendering": "プレビューを作成中…",
|
||||
"showCode": "XML を表示",
|
||||
"hideCode": "XML を隠す",
|
||||
"drawing": "図を描いています…",
|
||||
"editing": "図を修正しています…",
|
||||
"loadingLibrary": "図形ライブラリを読み込み中…",
|
||||
"libraryLoaded": "図形ライブラリを読み込みました",
|
||||
"failed": "今回はうまくいきませんでした",
|
||||
"failedRetrying": "うまくいかなかったので再試行しています",
|
||||
"stopped": "停止しました",
|
||||
"truncatedHint": "図が完成する前に出力の上限に達しました。もっと簡単な図を頼むか、設定 > 描画 で最大出力トークン数を増やしてください。",
|
||||
"noChanges": "目に見える変更はありません",
|
||||
"listSeparator": "、",
|
||||
"shapesAddedOne": "図形を 1 個追加",
|
||||
"shapesAddedOther": "図形を {count} 個追加",
|
||||
"edgesAddedOne": "コネクタを 1 本追加",
|
||||
"edgesAddedOther": "コネクタを {count} 本追加",
|
||||
"shapesChangedOne": "図形を 1 個変更",
|
||||
"shapesChangedOther": "図形を {count} 個変更",
|
||||
"edgesChangedOne": "コネクタを 1 本変更",
|
||||
"edgesChangedOther": "コネクタを {count} 本変更",
|
||||
"shapesRemovedOne": "図形を 1 個削除",
|
||||
"shapesRemovedOther": "図形を {count} 個削除",
|
||||
"edgesRemovedOne": "コネクタを 1 本削除",
|
||||
"edgesRemovedOther": "コネクタを {count} 本削除",
|
||||
"totals": "{shapes}、{edges}",
|
||||
"shapesTotalOne": "図形 1 個",
|
||||
"shapesTotalOther": "図形 {count} 個",
|
||||
"edgesTotalOne": "コネクタ 1 本",
|
||||
"edgesTotalOther": "コネクタ {count} 本",
|
||||
"restoreVersion": "v{n} に戻す",
|
||||
"restoredVersion": "v{n} に戻しました",
|
||||
"undoRestore": "元に戻す",
|
||||
"noPreview": "プレビューなし",
|
||||
"compareSince": "バージョン {n} から現在までの変更:",
|
||||
"isOnCanvas": "現在のキャンバスはこのバージョンと同じです。",
|
||||
"differsElsewhere": "1 ページ目の図形と線はバージョン {n} と同じですが、重なり順、ほかのページ、またはページ設定が変わっています。"
|
||||
},
|
||||
"lobby": {
|
||||
"title": "どんな図を描きますか?",
|
||||
"lede": "図を説明するか、スクリーンショットや PDF をアップロードしてください。できあがるのは編集もエクスポートもできる draw.io の図です。",
|
||||
"placeholder": "例:SMS 認証とリトライを含むログインのシーケンス図",
|
||||
"recent": "最近の図",
|
||||
"drawYourself": "白紙のキャンバスから始める",
|
||||
"openFileHint": "手元の図の続きを編集"
|
||||
}
|
||||
}
|
||||
|
||||
+337
-212
@@ -3,22 +3,19 @@
|
||||
"save": "儲存",
|
||||
"cancel": "取消",
|
||||
"close": "關閉",
|
||||
"confirm": "確認",
|
||||
"clear": "清除",
|
||||
"edit": "編輯",
|
||||
"delete": "刪除",
|
||||
"loading": "載入中...",
|
||||
"new": "新建"
|
||||
"loading": "載入中..."
|
||||
},
|
||||
"nav": {
|
||||
"about": "關於",
|
||||
"editor": "編輯器",
|
||||
"newChat": "開始新對話",
|
||||
"newChat": "新增圖紙",
|
||||
"github": "GitHub",
|
||||
"settings": "設定",
|
||||
"hidePanel": "隱藏聊天面板 (Ctrl+B)",
|
||||
"showPanel": "顯示聊天面板 (Ctrl+B)",
|
||||
"aiChat": "AI 聊天"
|
||||
"hidePanel": "隱藏聊天面板",
|
||||
"showPanel": "顯示聊天面板",
|
||||
"aiChat": "AI 對話"
|
||||
},
|
||||
"providers": {
|
||||
"useServerDefault": "使用伺服器預設值",
|
||||
@@ -39,12 +36,11 @@
|
||||
},
|
||||
"chat": {
|
||||
"placeholder": "描述您的圖表或上傳檔案...",
|
||||
"inputLabel": "聊天輸入框",
|
||||
"send": "傳送",
|
||||
"stopGeneration": "停止產生",
|
||||
"sendMessage": "傳送訊息",
|
||||
"clearConversation": "清除對話",
|
||||
"diagramHistory": "圖表歷史",
|
||||
"saveDiagram": "儲存圖表",
|
||||
"uploadFile": "上傳檔案(圖片、PDF、文字)",
|
||||
"minimalStyle": "簡約",
|
||||
"styledMode": "精緻",
|
||||
@@ -52,44 +48,43 @@
|
||||
"regenerate": "重新產生回應",
|
||||
"copyResponse": "複製回應",
|
||||
"copied": "已複製!",
|
||||
"failedToCopy": "複製失敗",
|
||||
"failedToCopyDetail": "複製訊息失敗。請手動複製或檢查剪貼簿權限。",
|
||||
"goodResponse": "有幫助",
|
||||
"badResponse": "無幫助",
|
||||
"clickToEdit": "點擊編輯",
|
||||
"editMessage": "編輯訊息",
|
||||
"saveAndSubmit": "儲存並提交",
|
||||
"ExtractURL": "從 URL 擷取"
|
||||
"saveAndSubmit": "儲存並送出",
|
||||
"ExtractURL": "從 URL 擷取",
|
||||
"attach": "新增",
|
||||
"placeholderFollowUp": "說說想怎麼改,也可以先選取要改的圖形",
|
||||
"emptyThread": "可以直接在畫布上畫,也可以在下面說說要畫什麼。",
|
||||
"attachedImage": "附加的圖片",
|
||||
"retry": "重試"
|
||||
},
|
||||
"examples": {
|
||||
"title": "用 AI 建立圖表",
|
||||
"subtitle": "描述您想要建立的內容或上傳圖片進行複製",
|
||||
"quickExamples": "快速範例",
|
||||
"paperToDiagram": "文件轉圖表",
|
||||
"paperToDiagram": "論文轉圖表",
|
||||
"paperDescription": "上傳 .pdf, .txt, .md, .json, .csv, .py, .js, .ts 等檔案",
|
||||
"animatedDiagram": "動畫圖表",
|
||||
"animatedDescription": "繪製帶有動畫連接器的 Transformer 架構",
|
||||
"awsArchitecture": "AWS 架構",
|
||||
"awsDescription": "使用 AWS 圖示建立雲端架構圖",
|
||||
"replicateFlowchart": "複製流程圖",
|
||||
"replicateFlowchart": "複刻流程圖",
|
||||
"replicateDescription": "上傳並複製現有流程圖",
|
||||
"creativeDrawing": "創意繪圖",
|
||||
"creativeDrawing": "創意繪畫",
|
||||
"creativeDescription": "繪製有趣且富有創意的內容",
|
||||
"cachedNote": "範例已快取,可即時回應",
|
||||
"cachedNote": "範例使用保存好的答案,立即顯示,不呼叫 AI。",
|
||||
"mcpServer": "MCP 伺服器",
|
||||
"mcpDescription": "在 Claude Desktop、VS Code 和 Cursor 中使用"
|
||||
},
|
||||
"settings": {
|
||||
"title": "設定",
|
||||
"description": "配置您的應用程式設定。",
|
||||
"apiKeysModels": "API 金鑰和模型",
|
||||
"apiKeysModelsDescription": "配置 AI 提供商和 API 金鑰。",
|
||||
"accessCode": "存取碼",
|
||||
"accessCodePlaceholder": "輸入存取碼",
|
||||
"accessCodeDescription": "使用此應用程式需要存取碼。",
|
||||
"aiProvider": "AI 提供商設定",
|
||||
"aiProvider": "AI 服務商設定",
|
||||
"aiProviderDescription": "使用您自己的 API 金鑰來繞過使用限制。您的金鑰僅儲存在瀏覽器本機,不會儲存在伺服器上。",
|
||||
"provider": "提供商",
|
||||
"provider": "服務商",
|
||||
"modelId": "模型 ID",
|
||||
"apiKey": "API 金鑰",
|
||||
"apiKeyPlaceholder": "您的 API 金鑰",
|
||||
@@ -101,17 +96,10 @@
|
||||
"language": "語言",
|
||||
"languageDescription": "選擇介面語言。",
|
||||
"theme": "主題",
|
||||
"themeDescription": "介面和 DrawIO 畫布的深色/淺色模式。",
|
||||
"drawioStyle": "DrawIO 樣式",
|
||||
"drawioStyleDescription": "畫布樣式",
|
||||
"themeDefault": "預設",
|
||||
"themeDark": "深色",
|
||||
"themeMinimal": "簡約",
|
||||
"themeSketch": "草圖",
|
||||
"themeSimple": "簡單",
|
||||
"diagramStyle": "圖表樣式",
|
||||
"diagramStyleDescription": "切換簡約與精緻圖表輸出模式。",
|
||||
"sendShortcut": "傳送快捷鍵",
|
||||
"themeDescription": "介面用淺色還是深色,畫布跟隨同一主題。",
|
||||
"diagramStyle": "圖形風格",
|
||||
"diagramStyleDescription": "AI 畫新圖時的風格:精緻會用顏色和圖示,簡約只用樸素的圖形。",
|
||||
"sendShortcut": "傳送快速鍵",
|
||||
"sendShortcutDescription": "選擇傳送訊息的方式。",
|
||||
"enterToSend": "Enter 傳送",
|
||||
"ctrlEnterToSend": "Cmd/Ctrl+Enter 傳送",
|
||||
@@ -125,46 +113,49 @@
|
||||
"httpsProxy": "HTTPS 代理",
|
||||
"applyProxy": "套用",
|
||||
"proxyApplied": "代理設定已套用",
|
||||
"diagramValidation": "圖表驗證(實驗性)",
|
||||
"diagramValidationDescription": "使用視覺語言模型驗證產生的圖表。需要支援視覺的模型,如 GPT-5.2 或 Sonnet-4.5。",
|
||||
"enabled": "已啟用",
|
||||
"disabled": "已停用",
|
||||
"customSystemMessage": "自訂系統訊息",
|
||||
"diagramValidation": "用截圖檢查圖表(實驗性)",
|
||||
"diagramValidationDescription": "每次畫完後,讓能看懂圖片的模型檢查截圖並要求修正。需要能讀圖片的模型。",
|
||||
"customSystemMessage": "自訂指令",
|
||||
"customSystemMessageDescription": "新增自訂指示,將附加到 AI 的系統提示末尾。",
|
||||
"customSystemMessagePlaceholder": "例如:圖表始終使用藍色配色方案...",
|
||||
"maxOutputTokens": "最大輸出 token 數",
|
||||
"maxOutputTokens": "輸出 token 上限",
|
||||
"maxOutputTokensDescription": "單次回覆的額度,思考過程與圖表 XML 共用。若 AI 一直在思考卻沒有產生圖表,請將它調大。留空則使用預設值。",
|
||||
"panelVisibility": "大廳面板",
|
||||
"panelVisibilityDescription": "選擇在聊天大廳顯示哪些面板。",
|
||||
"showRecentChats": "最近聊天",
|
||||
"showMyTemplates": "我的範本",
|
||||
"showQuickExamples": "快速範例"
|
||||
"tabModels": "模型",
|
||||
"tabAbout": "關於",
|
||||
"themeLight": "淺色",
|
||||
"themeDarkMode": "深色",
|
||||
"themeSystem": "跟隨系統",
|
||||
"accessCodeSaved": "存取碼已儲存",
|
||||
"proxyInvalid": "代理位址必須以 http:// 或 https:// 開頭",
|
||||
"proxyFailed": "代理設定沒有生效",
|
||||
"appVersion": "版本",
|
||||
"projectWebsite": "專案網站",
|
||||
"tabGeneral": "一般",
|
||||
"tabDrawing": "繪圖",
|
||||
"sectionInterface": "介面",
|
||||
"sectionAccess": "存取"
|
||||
},
|
||||
"save": {
|
||||
"title": "儲存圖表",
|
||||
"description": "選擇格式和檔案名稱以儲存您的圖表。",
|
||||
"title": "匯出圖紙",
|
||||
"description": "選擇格式和檔案名稱。",
|
||||
"format": "格式",
|
||||
"filename": "檔案名稱",
|
||||
"filenamePlaceholder": "輸入檔案名稱",
|
||||
"formats": {
|
||||
"drawio": "Draw.io XML",
|
||||
"drawio": "draw.io 檔案",
|
||||
"png": "PNG 圖片",
|
||||
"svg": "SVG 圖片",
|
||||
"xmlsvg": "可編輯 SVG"
|
||||
"xmlsvg": "可編輯的 SVG"
|
||||
},
|
||||
"savedSuccessfully": "儲存成功!"
|
||||
},
|
||||
"history": {
|
||||
"title": "圖表歷史",
|
||||
"description": "在 AI 修改之前儲存的每個圖表。\n點擊圖表以還原它",
|
||||
"noHistory": "尚無歷史紀錄。傳送訊息以建立圖表歷史。",
|
||||
"version": "版本",
|
||||
"restoreTo": "還原到版本 {version}?"
|
||||
"savedSuccessfully": "已匯出",
|
||||
"hints": {
|
||||
"drawio": "所有內容都能繼續編輯",
|
||||
"png": "用於簡報和文件的圖片",
|
||||
"svg": "放大也不會模糊的圖片",
|
||||
"xmlsvg": "圖片,也能在 draw.io 裡開啟編輯"
|
||||
}
|
||||
},
|
||||
"dialogs": {
|
||||
"clearTitle": "清除所有內容?",
|
||||
"clearDescription": "這將清除目前對話並重設圖表。此操作無法復原。",
|
||||
"clearEverything": "清除所有內容",
|
||||
"clearSuccess": "已開始新對話"
|
||||
},
|
||||
"errors": {
|
||||
@@ -189,9 +180,18 @@
|
||||
"sessionSaveFailed": "無法儲存這個對話。瀏覽器儲存空間可能已滿,請在歷史紀錄裡刪除舊對話後重試。",
|
||||
"sessionSaveFailedLeave": "無法儲存這個對話,瀏覽器儲存空間可能已滿。可以不儲存它、直接繼續,再在新對話的列表裡刪除舊對話。",
|
||||
"continueWithoutSaving": "不儲存,繼續",
|
||||
"notADiagramFile": "{name} 不是 draw.io 圖表檔案。",
|
||||
"fileTooLong": "{name}:內容超過了 {limit}k 字元的上限({size}k 字元)",
|
||||
"fileReadFailed": "無法讀取檔案:{name}",
|
||||
"answerEndedEarly": "回答在圖畫完之前就結束了。",
|
||||
"attachmentsStillReading": "附件還在讀取,讀完後再傳送。",
|
||||
"sendInProgress": "上一則訊息還在傳送,請稍後再試。",
|
||||
"answerInProgress": "回答還在進行,等它結束後再傳送。",
|
||||
"cannotResend": "這則訊息無法重新傳送:傳送時的畫布沒有儲存下來。",
|
||||
"llm": {
|
||||
"invalid_api_key": "服務商拒絕了這個 API Key,請在模型設定中檢查。",
|
||||
"forbidden": "服務商拒絕了這次請求。這個 Key 可能沒有使用該模型或該地區的權限。",
|
||||
"server_key_forbidden": "今天的免費額度已經用完,明天會自動恢復。您也可以在模型設定中填寫自己的 API Key 繼續使用。",
|
||||
"model_not_found": "服務商找不到這個模型,請在模型設定中檢查模型 ID。",
|
||||
"insufficient_quota": "服務商帳戶的餘額或額度已經用完。",
|
||||
"rate_limited": "服務商正在限制請求頻率,請稍候再試。",
|
||||
@@ -207,30 +207,24 @@
|
||||
},
|
||||
"quota": {
|
||||
"dailyLimit": "已達每日配額",
|
||||
"tokenLimit": "已達每日令牌限制",
|
||||
"tokenLimit": "已達每日 token 上限",
|
||||
"tpmLimit": "速率限制",
|
||||
"tpmMessage": "請求過多。請稍等片刻。",
|
||||
"tpmMessageDetailed": "達到速率限制({limit} 令牌/分鐘)。請等待 {seconds} 秒後再傳送請求。",
|
||||
"messageApi": "看來您今天的體驗次數已達上限。非常高興您玩得開心,雖然本專案由字節跳動豆包慷慨贊助,但為了確保大家都能公平使用,我們不得不對使用量做一點小小的限制。",
|
||||
"tpmMessageDetailed": "達到速率限制(每分鐘 {limit} token)。請等待 {seconds} 秒後再傳送請求。",
|
||||
"messageApi": "看來您今天的體驗次數已達上限。很高興您玩得開心;為了讓大家都能公平使用,示範站對用量做了限制。",
|
||||
"messageApiSelfHosted": null,
|
||||
"messageToken": "看來您今天的 Token 用量已達上限。非常高興您玩得開心,雖然本專案由字節跳動豆包慷慨贊助,但為了確保大家都能公平使用,我們不得不對使用量做一點小小的限制。",
|
||||
"messageToken": "看來您今天的 token 用量已達上限。很高興您玩得開心;為了讓大家都能公平使用,示範站對用量做了限制。",
|
||||
"messageTokenSelfHosted": null,
|
||||
"tip": "<strong>提示:</strong>您可以使用自己的 API 金鑰(點擊設定圖示)或自行託管專案來繞過這些限制。",
|
||||
"tipSelfHosted": "<strong>提示:</strong>您可以在設定中配置自己的 API 金鑰以繼續使用服務。",
|
||||
"tip": "<strong>提示:</strong>您可以使用自己的 API Key(點擊設定圖示)或自行託管專案來繞過這些限制。",
|
||||
"tipSelfHosted": "<strong>提示:</strong>您可以在設定中配置自己的 API Key 以繼續使用服務。",
|
||||
"reset": "您的限制將在明天重設。感謝您的理解。",
|
||||
"doubaoSponsorship": "<a href=\"{link}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline hover:text-foreground\">點此註冊</a>可獲得每個模型 50 萬免費 Token(包括豆包、DeepSeek 和 Kimi),然後在模型設定中配置您的 API Key。",
|
||||
"configModel": "使用您的金鑰",
|
||||
"configModel": "使用自己的 API Key",
|
||||
"selfHost": "自行託管",
|
||||
"sponsor": "贊助",
|
||||
"learnMore": "了解更多 →",
|
||||
"usedOf": "{used}/{limit}"
|
||||
},
|
||||
"tools": {
|
||||
"generateDiagram": "產生圖表",
|
||||
"editDiagram": "編輯圖表",
|
||||
"appendDiagram": "繼續圖表",
|
||||
"complete": "完成",
|
||||
"error": "錯誤",
|
||||
"truncated": "已截斷"
|
||||
},
|
||||
"file": {
|
||||
@@ -245,7 +239,8 @@
|
||||
"extract": "擷取",
|
||||
"Cancel": "取消",
|
||||
"enterUrl": "請輸入 URL",
|
||||
"invalidFormat": "URL 格式無效"
|
||||
"invalidFormat": "URL 格式無效",
|
||||
"failed": "無法讀取這個網頁"
|
||||
},
|
||||
"reasoning": {
|
||||
"thinking": "思考中...",
|
||||
@@ -278,30 +273,29 @@
|
||||
"sessionHistory": {
|
||||
"tooltip": "聊天歷史",
|
||||
"newChat": "新對話",
|
||||
"empty": "暫無聊天紀錄",
|
||||
"empty": "還沒有圖紙",
|
||||
"emptyHint": "開始對話吧",
|
||||
"today": "今天",
|
||||
"yesterday": "昨天",
|
||||
"thisWeek": "本週",
|
||||
"earlier": "更早",
|
||||
"deleteTitle": "刪除此對話?",
|
||||
"deleteDescription": "這將永久刪除此聊天工作階段及其圖表。此操作無法復原。",
|
||||
"recentChats": "最近對話",
|
||||
"deleteTitle": "刪除這張圖紙?",
|
||||
"deleteDescription": "圖紙和它的對話會被永久刪除。",
|
||||
"justNow": "剛剛",
|
||||
"searchPlaceholder": "搜尋對話...",
|
||||
"noResults": "未找到對話"
|
||||
"searchPlaceholder": "搜尋圖紙…",
|
||||
"noResults": "未找到對話",
|
||||
"rename": "重新命名",
|
||||
"busyHint": "回答完成後才能切換"
|
||||
},
|
||||
"templates": {
|
||||
"title": "我的範本",
|
||||
"subtitle": "快速建立圖表的個人提示庫",
|
||||
"emptyTitle": "尚無範本",
|
||||
"emptyDescription": "建立您的第一個範本,開始構建您的個人提示庫",
|
||||
"createFirst": "建立第一個範本",
|
||||
"emptyTitle": "還沒有常用提示詞",
|
||||
"emptyDescription": "把經常用的提示詞存起來,比如「畫一張……的 AWS 架構圖」,之後會出現在這裡。",
|
||||
"createFirst": "儲存第一個提示詞",
|
||||
"neverUsed": "未使用過",
|
||||
"usedCount": "使用 {count} 次",
|
||||
"myTemplates": "我的範本",
|
||||
"createTitle": "建立範本",
|
||||
"createDescription": "儲存常用提示以便重複使用。範本幫助您快速開始常用工作流程。",
|
||||
"myTemplates": "常用提示詞",
|
||||
"createTitle": "儲存提示詞",
|
||||
"createDescription": "把提示詞存起來,以後再用。",
|
||||
"promptLabel": "提示",
|
||||
"promptPlaceholder": "描述您想建立的圖表...",
|
||||
"promptRequired": "提示為必填項",
|
||||
@@ -309,33 +303,34 @@
|
||||
"titlePlaceholder": "輸入標題",
|
||||
"titleHint": "留空則使用提示的前 20 個字元",
|
||||
"descriptionLabel": "描述",
|
||||
"descriptionPlaceholder": "為此範本新增描述",
|
||||
"pinnedLabel": "釘選範本",
|
||||
"pinnedHint": "釘選的範本會顯示在清單頂部",
|
||||
"createButton": "建立範本",
|
||||
"createFailed": "建立範本失敗,請重試。",
|
||||
"editTitle": "編輯範本",
|
||||
"editDescription": "更新範本內容和設定。",
|
||||
"updateFailed": "更新範本失敗,請重試。",
|
||||
"descriptionPlaceholder": "這個提示詞的用途",
|
||||
"pinnedLabel": "置頂",
|
||||
"pinnedHint": "置頂的提示詞顯示在清單最上面",
|
||||
"createButton": "儲存",
|
||||
"createFailed": "儲存提示詞失敗,請重試。",
|
||||
"editTitle": "編輯提示詞",
|
||||
"editDescription": "修改提示詞和它的設定。",
|
||||
"updateFailed": "更新提示詞失敗,請重試。",
|
||||
"duplicate": "複製",
|
||||
"copySuffix": "(副本)",
|
||||
"deleteTitle": "刪除此範本?",
|
||||
"deleteDescription": "此操作將永久刪除該範本,無法復原。",
|
||||
"deleteTitle": "刪除這個提示詞?",
|
||||
"deleteDescription": "提示詞會被永久刪除。",
|
||||
"confirmSendTitle": "取代目前輸入?",
|
||||
"confirmSendDescription": "您有未傳送的內容。傳送此範本將取代它。",
|
||||
"confirmSendButton": "傳送範本",
|
||||
"searchPlaceholder": "搜尋範本...",
|
||||
"searchNoResults": "沒有符合的範本",
|
||||
"confirmSendDescription": "輸入框裡有還沒傳送的內容,傳送這個提示詞會取代它。",
|
||||
"confirmSendButton": "傳送",
|
||||
"searchPlaceholder": "搜尋提示詞…",
|
||||
"searchNoResults": "沒有符合的提示詞",
|
||||
"pin": "置頂",
|
||||
"unpin": "取消置頂",
|
||||
"saveAsTemplate": "儲存為範本",
|
||||
"exportTemplates": "匯出範本",
|
||||
"importTemplates": "匯入範本",
|
||||
"exportEmpty": "沒有可匯出的範本",
|
||||
"exportSuccess": "成功匯出 {count} 個範本",
|
||||
"saveAsTemplate": "儲存這個提示詞",
|
||||
"exportTemplates": "匯出提示詞",
|
||||
"importTemplates": "匯入提示詞",
|
||||
"exportEmpty": "沒有可匯出的提示詞",
|
||||
"exportSuccess": "已匯出 {count} 個提示詞",
|
||||
"importNoFile": "請選擇一個 JSON 檔案",
|
||||
"importFailed": "匯入失敗:{error}",
|
||||
"importSuccess": "成功匯入 {imported} 個範本,跳過 {skipped} 個重複"
|
||||
"importSuccess": "已匯入 {imported} 個提示詞,略過 {skipped} 個重複",
|
||||
"saveDisabledHint": "先在輸入框裡寫好提示詞"
|
||||
},
|
||||
"validation": {
|
||||
"title": "驗證圖表",
|
||||
@@ -356,39 +351,30 @@
|
||||
"regenerateWithFeedback": "使用驗證回饋重新產生圖表"
|
||||
},
|
||||
"modelConfig": {
|
||||
"title": "AI 模型配置",
|
||||
"description": "配置多個 AI 提供商和模型",
|
||||
"configure": "配置",
|
||||
"addProvider": "新增提供商",
|
||||
"addProvider": "新增服務商",
|
||||
"addModel": "新增模型",
|
||||
"modelId": "模型 ID",
|
||||
"modelLabel": "顯示名稱",
|
||||
"streaming": "啟用串流輸出",
|
||||
"deleteProvider": "刪除提供商",
|
||||
"deleteProvider": "刪除服務商",
|
||||
"deleteModel": "刪除模型",
|
||||
"noModels": "尚未配置模型。新增模型以開始使用。",
|
||||
"selectProvider": "選擇一個提供商或新增",
|
||||
"configureMultiple": "配置多個 AI 提供商並輕鬆切換",
|
||||
"apiKeyStored": "API 金鑰儲存在您的瀏覽器本機",
|
||||
"test": "測試",
|
||||
"validationError": "驗證失敗",
|
||||
"addModelFirst": "請先新增至少一個模型以進行驗證",
|
||||
"providers": "提供商",
|
||||
"addProviderHint": "新增提供商即可開始使用",
|
||||
"verified": "已驗證",
|
||||
"configuration": "配置",
|
||||
"validationError": "測試沒通過",
|
||||
"addModelFirst": "先新增一個模型。",
|
||||
"displayName": "顯示名稱",
|
||||
"bedrockApiKey": "Bedrock API Key",
|
||||
"bedrockApiKeyHint": "填了 API 金鑰,下面的存取金鑰就不用填。",
|
||||
"awsAccessKeyId": "AWS 存取金鑰 ID",
|
||||
"awsSecretAccessKey": "AWS Secret Access Key",
|
||||
"awsRegion": "AWS 區域",
|
||||
"selectRegion": "選擇區域",
|
||||
"apiKey": "API 金鑰",
|
||||
"enterApiKey": "輸入您的 API 金鑰",
|
||||
"enterSecretKey": "輸入您的 Secret Key",
|
||||
"apiKey": "API Key",
|
||||
"enterApiKey": "輸入 API Key",
|
||||
"enterSecretKey": "輸入 Secret Access Key",
|
||||
"baseUrl": "基礎 URL",
|
||||
"optional": "(可選)",
|
||||
"getApiKey": "取得 API Key",
|
||||
"fetchModels": "從服務商取得模型清單",
|
||||
"noTools": "不支援工具呼叫",
|
||||
"mayNotDraw": "models.dev 顯示這個模型不支援工具呼叫,可能無法繪圖。",
|
||||
"requestUrl": "請求將傳送至 {url}",
|
||||
@@ -399,180 +385,319 @@
|
||||
"models": "模型",
|
||||
"customModelId": "自訂模型 ID...",
|
||||
"allAdded": "已全部新增",
|
||||
"suggested": "推薦",
|
||||
"noModelsConfigured": "尚未配置模型",
|
||||
"modelIdEmpty": "模型 ID 不能為空",
|
||||
"modelIdExists": "此模型 ID 已存在",
|
||||
"configureProviders": "配置 AI 提供商",
|
||||
"selectProviderHint": "從列表中選擇提供商或新增以配置 API 金鑰和模型",
|
||||
"deleteConfirmDesc": "確定要刪除 {name} 嗎?這將移除所有配置的模型且無法復原。",
|
||||
"typeToConfirm": "輸入「{name}」以確認",
|
||||
"typeProviderName": "輸入提供商名稱...",
|
||||
"modelsConfiguredCount": "已配置 {count} 個模型",
|
||||
"validationFailedCount": "{count} 個模型驗證失敗",
|
||||
"typeProviderName": "輸入服務商名稱...",
|
||||
"requestFailed": "請求失敗({status})",
|
||||
"cancel": "取消",
|
||||
"delete": "刪除",
|
||||
"clickToChange": "(點擊變更)",
|
||||
"usingServerDefault": "使用伺服器預設模型",
|
||||
"selectModel": "選擇模型",
|
||||
"searchModels": "搜尋模型...",
|
||||
"noVerifiedModels": "沒有已驗證的模型。請先測試您的模型。",
|
||||
"noModelsFound": "未找到模型。",
|
||||
"default": "預設",
|
||||
"serverDefault": "伺服器預設",
|
||||
"serverDefault": "伺服器模型",
|
||||
"serverModels": "伺服器模型",
|
||||
"userModels": "使用者模型",
|
||||
"configureModels": "配置模型...",
|
||||
"onlyVerifiedShown": "僅顯示已驗證的模型",
|
||||
"showUnvalidatedModels": "顯示未驗證的模型",
|
||||
"allModelsShown": "顯示所有模型(包括未驗證的)",
|
||||
"unvalidatedModelWarning": "此模型尚未驗證",
|
||||
"serverDefaultModel": "伺服器預設模型",
|
||||
"showValue": "顯示值",
|
||||
"hideValue": "隱藏值"
|
||||
"hideValue": "隱藏值",
|
||||
"myProviders": "我的服務商",
|
||||
"inUse": "正在使用",
|
||||
"listSeparator": "、",
|
||||
"serverModelsTitle": "伺服器提供的模型",
|
||||
"serverDefaultSummary": "不用填寫 API Key,使用伺服器設定的預設模型。",
|
||||
"statusError": "{count} 個模型出錯",
|
||||
"statusIncomplete": "還沒設定完",
|
||||
"statusUntested": "{count} 個模型未測試",
|
||||
"statusOk": "{count} 個模型可用",
|
||||
"noModelsYet": "還沒有模型",
|
||||
"keysStayLocal": "API Key 只儲存在這台裝置的瀏覽器裡,發送請求時才帶給伺服器。",
|
||||
"useOwnKey": "使用自己的 API Key",
|
||||
"useOwnKeyHint": "接入其他服務商後,就能在聊天框的模型選擇器裡換用它們的模型。選一個開始:",
|
||||
"viewAllProviders": "查看全部 {count} 個服務商",
|
||||
"searchProviders": "搜尋服務商,例如 DeepSeek、Qwen、Ollama",
|
||||
"noProvidersFound": "沒有找到這個服務商。",
|
||||
"groupVendors": "模型廠商",
|
||||
"groupAggregators": "聚合平台",
|
||||
"groupCloud": "雲端平台",
|
||||
"groupSelfHosted": "自行部署",
|
||||
"noteBedrock": "AWS 憑證",
|
||||
"noteVertex": "Express 模式 Key",
|
||||
"noteAzure": "Key 和資源位址",
|
||||
"noteEdgeone": "不用 Key",
|
||||
"noteOllama": "Key 可不填",
|
||||
"noteSglang": "填服務位址",
|
||||
"added": "已新增",
|
||||
"awsCredentials": "AWS 憑證",
|
||||
"bedrockAuthApiKey": "Bedrock API Key",
|
||||
"bedrockAuthAccessKey": "存取金鑰",
|
||||
"moreOptions": "更多選項:Base URL、顯示名稱",
|
||||
"moreOptionsName": "更多選項:顯示名稱",
|
||||
"keyRejected": "服務商拒絕了這個 API Key。檢查上面的 Key 是否複製完整。",
|
||||
"modelNotFound": "服務商找不到這個模型 ID,請檢查拼寫。",
|
||||
"modelWorks": "可用",
|
||||
"modelWorksTime": "可用 · {seconds} 秒",
|
||||
"modelFailed": "出錯",
|
||||
"modelUntested": "未測試",
|
||||
"needKey": "先填好 API Key。",
|
||||
"needAws": "先填好 AWS 憑證和區域。",
|
||||
"needModel": "先新增一個模型。",
|
||||
"stepConnect": "連線",
|
||||
"edgeoneNoKey": "EdgeOne Pages 使用這個網站部署時內建的模型服務,不用填寫 API Key。",
|
||||
"stepModels": "選擇模型",
|
||||
"fetchAllModels": "從 {name} 取得全部模型",
|
||||
"suggestedLabel": "推薦:",
|
||||
"orTypeModelId": "或者輸入其他模型 ID",
|
||||
"add": "新增",
|
||||
"browseModels": "瀏覽模型",
|
||||
"stepTest": "測試",
|
||||
"testHint": "給每個模型發一條很短的訊息,確認 Key 和模型都能用。",
|
||||
"testOne": "測試 {model}",
|
||||
"testAll": "測試全部 {count} 個模型",
|
||||
"testPassedOne": "{model} 可以用了",
|
||||
"testPassedAll": "{count} 個模型都可以用了",
|
||||
"answeredIn": "(回覆用了 {seconds} 秒)",
|
||||
"useInChat": "在聊天裡使用 {model}",
|
||||
"backToProviders": "返回服務商列表",
|
||||
"deleteProviderOnly": "刪除 {name}",
|
||||
"addProviderEntry": "新增服務商…",
|
||||
"awsKeysRejected": "AWS 拒絕了這組存取金鑰。檢查兩個金鑰是否都複製完整。",
|
||||
"needAzure": "先填好 API Key 和 Azure 資源的 Base URL。",
|
||||
"validationFailedCountOne": "{count} 個模型沒通過測試",
|
||||
"validationFailedCountOther": "{count} 個模型沒通過測試",
|
||||
"deleteProviderNamedOne": "刪除 {name} 和它的 {count} 個模型",
|
||||
"deleteProviderNamedOther": "刪除 {name} 和它的 {count} 個模型",
|
||||
"serverModelsSummaryOne": "不用填寫 API Key。共 {count} 個:{names}",
|
||||
"serverModelsSummaryOther": "不用填寫 API Key。共 {count} 個:{names}",
|
||||
"noModelsReturned": "服務商沒有回傳任何模型。",
|
||||
"awsSessionToken": "AWS Session Token(選填)",
|
||||
"awsSessionTokenHint": "只有臨時憑證才需要,也就是以 ASIA 開頭的存取金鑰。",
|
||||
"bedrockBothSaved": "這個服務商還保存著一對存取金鑰,有 API Key 時它們不會被用到。",
|
||||
"removeAccessKeys": "刪除存取金鑰"
|
||||
},
|
||||
"admin": {
|
||||
"title": "管理員設定",
|
||||
"loginPrompt": "輸入管理員密碼(即 ADMIN_PASSWORD 環境變數)以管理伺服器設定。",
|
||||
"title": "後台設定",
|
||||
"loginPrompt": "輸入管理員密碼(環境變數 ADMIN_PASSWORD)",
|
||||
"password": "密碼",
|
||||
"signIn": "登入",
|
||||
"signingIn": "正在登入…",
|
||||
"signingIn": "登入中…",
|
||||
"loginFailed": "登入失敗",
|
||||
"precedence": "檔案覆蓋環境變數 · 環境變數覆蓋預設值",
|
||||
"notWritable": "此部署環境下設定檔不可寫入(無伺服器平台沒有持久化磁碟)。設定以唯讀方式顯示——請改用環境變數進行設定。",
|
||||
"settingGroups": "設定分組",
|
||||
"enabled": "已啟用",
|
||||
"disabled": "已停用",
|
||||
"enableGroup": "啟用 {group}",
|
||||
"unsavedChanges": "有未儲存的變更",
|
||||
"saved": "設定已儲存,變更立即生效。",
|
||||
"saveFailed": "儲存失敗。請檢查網路連線後重試。",
|
||||
"invalidSettings": "部分設定無效。",
|
||||
"discard": "捨棄",
|
||||
"saveChanges": "儲存變更",
|
||||
"saving": "正在儲存…",
|
||||
"sourceSaved": "已儲存",
|
||||
"precedence": "優先順序:本頁設定 > 環境變數 > 預設值",
|
||||
"notWritable": "這裡無法儲存設定,只能檢視;請改用環境變數",
|
||||
"settingGroups": "設定分類",
|
||||
"enabled": "已開啟",
|
||||
"disabled": "已關閉",
|
||||
"enableGroup": "開啟{group}",
|
||||
"unsavedChanges": "有未儲存的修改",
|
||||
"saved": "已儲存,立即生效(需重啟的項目除外)",
|
||||
"saveFailed": "儲存失敗,請檢查網路後重試",
|
||||
"invalidSettings": "有設定填寫有誤,請依提示修改",
|
||||
"discard": "捨棄修改",
|
||||
"saveChanges": "儲存修改",
|
||||
"saving": "儲存中…",
|
||||
"sourceSaved": "本頁設定",
|
||||
"sourceEnv": "環境變數",
|
||||
"sourceSavedTitle": "在管理員設定檔中設定",
|
||||
"sourceEnvTitle": "透過環境變數設定",
|
||||
"restartRequired": "需要重新啟動",
|
||||
"sourceSavedTitle": "來自本頁設定",
|
||||
"sourceEnvTitle": "來自環境變數",
|
||||
"restartRequired": "需重啟",
|
||||
"modified": "已修改",
|
||||
"notSet": "未設定",
|
||||
"savedReplace": "已儲存({hint})——輸入以取代",
|
||||
"showValue": "顯示值",
|
||||
"hideValue": "隱藏值",
|
||||
"removeValue": "移除值",
|
||||
"removeValueTitle": "移除已儲存的值",
|
||||
"savedReplace": "已儲存({hint}),輸入新值即可取代",
|
||||
"showValue": "顯示",
|
||||
"hideValue": "隱藏",
|
||||
"removeValue": "清除",
|
||||
"removeValueTitle": "清除已儲存的值",
|
||||
"resetToDefault": "重設為預設",
|
||||
"models": "模型",
|
||||
"modelsDescription": "面向所有使用者的伺服器端 provider 與模型——無需個人 API 金鑰。當使用者未選擇模型時,使用預設 provider 的第一個模型。",
|
||||
"addProviderHint": "新增一個 provider,為所有使用者提供伺服器端模型。",
|
||||
"selectProviderHint": "選擇或新增一個 provider 以設定其憑證和模型。",
|
||||
"addProviderToOfferModels": "至少新增一個模型,才能向使用者開放此 provider。",
|
||||
"managedViaEnv": "(透過環境變數管理)",
|
||||
"envReadOnly": "在 AI_MODELS_CONFIG / ai-models.json 中定義——此處唯讀。請編輯環境設定以變更。",
|
||||
"modelsDescription": "給所有使用者用的模型,無需自備金鑰",
|
||||
"addProviderHint": "新增服務商,為所有使用者提供模型",
|
||||
"selectProviderHint": "選擇或新增服務商,填寫金鑰和模型",
|
||||
"addProviderToOfferModels": "至少新增一個模型,使用者才能看到這個服務商",
|
||||
"managedViaEnv": "(環境變數)",
|
||||
"envReadOnly": "由 AI_MODELS_CONFIG / ai-models.json 定義,這裡只能檢視,請到那裡修改",
|
||||
"defaultModel": "預設模型",
|
||||
"noModelsConfigured": "未設定模型",
|
||||
"noModelsConfigured": "尚無模型",
|
||||
"modelCount": "{count} 個模型",
|
||||
"modelCountPlural": "{count} 個模型",
|
||||
"default": "預設",
|
||||
"setAsDefault": "設為預設 provider",
|
||||
"defaultProvider": "預設 provider",
|
||||
"setAsDefault": "設為預設服務商",
|
||||
"defaultProvider": "預設服務商",
|
||||
"modelIdPlaceholder": "模型 ID…",
|
||||
"addModel": "新增模型",
|
||||
"suggested": "推薦",
|
||||
"test": "測試",
|
||||
"testOk": "正常({ms} 毫秒)",
|
||||
"testOk": "通過({ms} 毫秒)",
|
||||
"testFailed": "失敗",
|
||||
"removeModel": "移除 {model}",
|
||||
"removeModel": "刪除 {model}",
|
||||
"deleteProviderTitle": "刪除 {name}?",
|
||||
"deleteProviderDesc": "儲存後,其憑證和模型將從伺服器上移除。",
|
||||
"deleteProviderDesc": "儲存後,它的金鑰和模型會從伺服器刪除",
|
||||
"cancel": "取消",
|
||||
"delete": "刪除",
|
||||
"groups": {
|
||||
"generation": {
|
||||
"title": "生成",
|
||||
"description": "套用於所有聊天請求的輸出參數。"
|
||||
"title": "回覆設定",
|
||||
"description": "控制 AI 怎麼回覆,對所有對話生效"
|
||||
},
|
||||
"access": {
|
||||
"title": "存取控制",
|
||||
"description": "限制誰可以使用此部署。"
|
||||
"title": "存取權限",
|
||||
"description": "限制誰可以使用這個網站"
|
||||
},
|
||||
"features": {
|
||||
"title": "功能",
|
||||
"description": "選用功能和安全開關。"
|
||||
"title": "選用功能",
|
||||
"description": "附加功能和安全選項"
|
||||
},
|
||||
"observability": {
|
||||
"title": "可觀測性",
|
||||
"description": "對 LLM 呼叫進行 Langfuse 追蹤。"
|
||||
"title": "呼叫記錄",
|
||||
"description": "用 Langfuse 記錄模型呼叫"
|
||||
},
|
||||
"quota": {
|
||||
"title": "配額與速率限制",
|
||||
"description": "按 IP 的用量限制。強制執行需要 DynamoDB 表。"
|
||||
"title": "用量限制",
|
||||
"description": "按 IP 限制用量,需要 DynamoDB 資料表才生效"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"TEMPERATURE": {
|
||||
"label": "溫度",
|
||||
"description": "對於拒絕溫度參數的推理模型,請留空。"
|
||||
"description": "越高越隨機;不支援溫度的推理模型請留空"
|
||||
},
|
||||
"MAX_OUTPUT_TOKENS": {
|
||||
"label": "最大輸出 token 數"
|
||||
"label": "輸出 token 上限"
|
||||
},
|
||||
"ACCESS_CODE_LIST": {
|
||||
"label": "存取碼",
|
||||
"description": "以逗號分隔的清單。使用者需輸入其中之一才能聊天。留空 = 開放存取。"
|
||||
"description": "逗號分隔多個;輸入其中一個才能用;留空則不限"
|
||||
},
|
||||
"ENABLE_VLM_VALIDATION": {
|
||||
"label": "VLM 圖表驗證",
|
||||
"description": "使用視覺模型對產生的圖表進行視覺化驗證。"
|
||||
"label": "圖表檢查",
|
||||
"description": "畫完後讓能看圖的模型檢查截圖"
|
||||
},
|
||||
"VALIDATION_MODEL": {
|
||||
"label": "驗證模型",
|
||||
"description": "留空時回退到預設 AI 模型。"
|
||||
"label": "檢查模型",
|
||||
"description": "留空則用預設模型"
|
||||
},
|
||||
"VALIDATION_TIMEOUT": {
|
||||
"label": "驗證逾時(毫秒)"
|
||||
"label": "檢查逾時(毫秒)"
|
||||
},
|
||||
"ENABLE_HISTORY_XML_REPLACE": {
|
||||
"label": "歷史 XML 壓縮",
|
||||
"description": "用占位符取代歷史記錄中的舊圖表 XML。"
|
||||
"label": "精簡舊圖",
|
||||
"description": "對話歷史裡的舊圖表只留簡短標記"
|
||||
},
|
||||
"ALLOW_PRIVATE_URLS": {
|
||||
"label": "允許私有 URL",
|
||||
"description": "關閉以阻擋對私有 IP 和內部主機名的請求(SSRF 防護)。"
|
||||
"label": "存取內網",
|
||||
"description": "關閉後,自訂模型位址不能指向內網,更安全"
|
||||
},
|
||||
"LANGFUSE_PUBLIC_KEY": {
|
||||
"label": "Langfuse Public Key"
|
||||
"label": "Langfuse 公鑰"
|
||||
},
|
||||
"LANGFUSE_SECRET_KEY": {
|
||||
"label": "Langfuse Secret Key"
|
||||
"label": "Langfuse 金鑰"
|
||||
},
|
||||
"LANGFUSE_BASEURL": {
|
||||
"label": "Langfuse Base URL"
|
||||
"label": "Langfuse 位址"
|
||||
},
|
||||
"DAILY_REQUEST_LIMIT": {
|
||||
"label": "每日請求上限",
|
||||
"description": "每個 IP 每天。"
|
||||
"label": "每日請求",
|
||||
"description": "每個 IP 每天的請求次數上限"
|
||||
},
|
||||
"DAILY_TOKEN_LIMIT": {
|
||||
"label": "每日 token 上限",
|
||||
"description": "每個 IP 每天。"
|
||||
"label": "每日 token",
|
||||
"description": "每個 IP 每天的 token 用量上限"
|
||||
},
|
||||
"TPM_LIMIT": {
|
||||
"label": "每分鐘 token 數"
|
||||
"label": "每分鐘 token"
|
||||
},
|
||||
"DYNAMODB_QUOTA_TABLE": {
|
||||
"label": "DynamoDB 表",
|
||||
"description": "留空時配額強制執行被停用。"
|
||||
"label": "DynamoDB 資料表名稱",
|
||||
"description": "留空則不限制用量"
|
||||
},
|
||||
"DYNAMODB_REGION": {
|
||||
"label": "DynamoDB 區域"
|
||||
},
|
||||
"QUOTA_TIMEZONE": {
|
||||
"label": "配額時區",
|
||||
"description": "每日重置邊界所用的時區。"
|
||||
"label": "時區",
|
||||
"description": "每日用量按這個時區的零點重置"
|
||||
}
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"export": "匯出",
|
||||
"openFile": "開啟 .drawio 檔案",
|
||||
"canvasLoading": "正在載入畫布…",
|
||||
"askAi": "讓 AI 改這裡",
|
||||
"untitled": "未命名圖紙",
|
||||
"mobileCanvas": "畫布",
|
||||
"mobileChat": "對話"
|
||||
},
|
||||
"selection": {
|
||||
"one": "已選取:{label}",
|
||||
"many": "已選取 {count} 個圖形",
|
||||
"shape": "圖形",
|
||||
"connector": "連線",
|
||||
"remove": "不傳送選取的圖形",
|
||||
"placeholder": "說說要怎麼改選取的圖形"
|
||||
},
|
||||
"versions": {
|
||||
"strip": "版本",
|
||||
"created": "畫好了圖表",
|
||||
"edited": "改好了圖表",
|
||||
"undone": "這次修改已復原",
|
||||
"undo": "復原修改",
|
||||
"redo": "重做修改",
|
||||
"compare": "比較",
|
||||
"compareTitle": "比較版本",
|
||||
"currentCanvas": "現在的畫布",
|
||||
"versionLabel": "第 {n} 版",
|
||||
"previous": "上一版",
|
||||
"next": "下一版",
|
||||
"rendering": "正在產生預覽…",
|
||||
"showCode": "檢視 XML",
|
||||
"hideCode": "收起 XML",
|
||||
"drawing": "正在畫圖…",
|
||||
"editing": "正在修改圖表…",
|
||||
"loadingLibrary": "正在讀取圖形庫…",
|
||||
"libraryLoaded": "讀取了圖形庫",
|
||||
"failed": "這次沒有成功",
|
||||
"failedRetrying": "這次沒有成功,正在重試",
|
||||
"stopped": "已停止",
|
||||
"truncatedHint": "回覆達到輸出長度上限,圖表沒有畫完。可以要一張簡單些的圖,或在 設定 > 繪圖 中調高最大輸出長度。",
|
||||
"noChanges": "沒有可見的變化",
|
||||
"listSeparator": ",",
|
||||
"shapesAddedOne": "新增 1 個圖形",
|
||||
"shapesAddedOther": "新增 {count} 個圖形",
|
||||
"edgesAddedOne": "新增 1 條連線",
|
||||
"edgesAddedOther": "新增 {count} 條連線",
|
||||
"shapesChangedOne": "改了 1 個圖形",
|
||||
"shapesChangedOther": "改了 {count} 個圖形",
|
||||
"edgesChangedOne": "改了 1 條連線",
|
||||
"edgesChangedOther": "改了 {count} 條連線",
|
||||
"shapesRemovedOne": "刪了 1 個圖形",
|
||||
"shapesRemovedOther": "刪了 {count} 個圖形",
|
||||
"edgesRemovedOne": "刪了 1 條連線",
|
||||
"edgesRemovedOther": "刪了 {count} 條連線",
|
||||
"totals": "共 {shapes}、{edges}",
|
||||
"shapesTotalOne": "1 個圖形",
|
||||
"shapesTotalOther": "{count} 個圖形",
|
||||
"edgesTotalOne": "1 條連線",
|
||||
"edgesTotalOther": "{count} 條連線",
|
||||
"restoreVersion": "還原到 v{n}",
|
||||
"restoredVersion": "已還原到 v{n}",
|
||||
"undoRestore": "復原",
|
||||
"noPreview": "沒有預覽",
|
||||
"compareSince": "從第 {n} 版到現在,畫布上:",
|
||||
"isOnCanvas": "畫布現在顯示的就是這一版。",
|
||||
"differsElsewhere": "第一頁的形狀和連線與第 {n} 版相同,疊放順序、其他頁面或頁面設定有改動。"
|
||||
},
|
||||
"lobby": {
|
||||
"title": "說說你要畫什麼",
|
||||
"lede": "描述一張圖,或上傳截圖、PDF。得到的是可以繼續編輯和匯出的 draw.io 圖。",
|
||||
"placeholder": "例如:使用者登入的時序圖,包含簡訊驗證碼和失敗重試",
|
||||
"recent": "最近的圖紙",
|
||||
"drawYourself": "從空白畫布開始",
|
||||
"openFileHint": "接著編輯已有的圖"
|
||||
}
|
||||
}
|
||||
|
||||
+335
-210
@@ -3,22 +3,19 @@
|
||||
"save": "保存",
|
||||
"cancel": "取消",
|
||||
"close": "关闭",
|
||||
"confirm": "确认",
|
||||
"clear": "清除",
|
||||
"edit": "编辑",
|
||||
"delete": "删除",
|
||||
"loading": "加载中...",
|
||||
"new": "新建"
|
||||
"loading": "加载中..."
|
||||
},
|
||||
"nav": {
|
||||
"about": "关于",
|
||||
"editor": "编辑器",
|
||||
"newChat": "开始新对话",
|
||||
"newChat": "新建图纸",
|
||||
"github": "GitHub",
|
||||
"settings": "设置",
|
||||
"hidePanel": "隐藏聊天面板 (Ctrl+B)",
|
||||
"showPanel": "显示聊天面板 (Ctrl+B)",
|
||||
"aiChat": "AI 聊天"
|
||||
"hidePanel": "隐藏聊天面板",
|
||||
"showPanel": "显示聊天面板",
|
||||
"aiChat": "AI 对话"
|
||||
},
|
||||
"providers": {
|
||||
"useServerDefault": "使用服务器默认值",
|
||||
@@ -39,12 +36,11 @@
|
||||
},
|
||||
"chat": {
|
||||
"placeholder": "描述您的图表或上传文件...",
|
||||
"inputLabel": "聊天输入框",
|
||||
"send": "发送",
|
||||
"stopGeneration": "停止生成",
|
||||
"sendMessage": "发送消息",
|
||||
"clearConversation": "清除对话",
|
||||
"diagramHistory": "图表历史",
|
||||
"saveDiagram": "保存图表",
|
||||
"uploadFile": "上传文件(图片、PDF、文本)",
|
||||
"minimalStyle": "简约",
|
||||
"styledMode": "精致",
|
||||
@@ -52,44 +48,43 @@
|
||||
"regenerate": "重新生成响应",
|
||||
"copyResponse": "复制响应",
|
||||
"copied": "已复制!",
|
||||
"failedToCopy": "复制失败",
|
||||
"failedToCopyDetail": "复制消息失败。请手动复制或检查剪贴板权限。",
|
||||
"goodResponse": "有帮助",
|
||||
"badResponse": "无帮助",
|
||||
"clickToEdit": "点击编辑",
|
||||
"editMessage": "编辑消息",
|
||||
"saveAndSubmit": "保存并提交",
|
||||
"ExtractURL": "从 URL 提取"
|
||||
"ExtractURL": "从 URL 提取",
|
||||
"attach": "添加",
|
||||
"placeholderFollowUp": "说说想怎么改,也可以先选中要改的图形",
|
||||
"emptyThread": "可以直接在画布上画,也可以在下面说说要画什么。",
|
||||
"attachedImage": "附带的图片",
|
||||
"retry": "重试"
|
||||
},
|
||||
"examples": {
|
||||
"title": "用 AI 创建图表",
|
||||
"subtitle": "描述您想要创建的内容或上传图片进行复制",
|
||||
"quickExamples": "快速示例",
|
||||
"paperToDiagram": "文档转图表",
|
||||
"paperToDiagram": "论文转图表",
|
||||
"paperDescription": "上传 .pdf, .txt, .md, .json, .csv, .py, .js, .ts 等文件",
|
||||
"animatedDiagram": "动画图表",
|
||||
"animatedDescription": "绘制带有动画连接器的 Transformer 架构",
|
||||
"awsArchitecture": "AWS 架构",
|
||||
"awsDescription": "使用 AWS 图标创建云架构图",
|
||||
"replicateFlowchart": "复制流程图",
|
||||
"replicateFlowchart": "复刻流程图",
|
||||
"replicateDescription": "上传并复制现有流程图",
|
||||
"creativeDrawing": "创意绘图",
|
||||
"creativeDrawing": "创意绘画",
|
||||
"creativeDescription": "绘制有趣且富有创意的内容",
|
||||
"cachedNote": "示例已缓存,可即时响应",
|
||||
"cachedNote": "示例使用保存好的答案,立即显示,不调用 AI。",
|
||||
"mcpServer": "MCP 服务器",
|
||||
"mcpDescription": "在 Claude Desktop、VS Code 和 Cursor 中使用"
|
||||
},
|
||||
"settings": {
|
||||
"title": "设置",
|
||||
"description": "配置您的应用程序设置。",
|
||||
"apiKeysModels": "API 密钥和模型",
|
||||
"apiKeysModelsDescription": "配置 AI 提供商和 API 密钥。",
|
||||
"accessCode": "访问码",
|
||||
"accessCodePlaceholder": "输入访问码",
|
||||
"accessCodeDescription": "使用此应用程序需要访问码。",
|
||||
"aiProvider": "AI 提供商设置",
|
||||
"aiProvider": "AI 服务商设置",
|
||||
"aiProviderDescription": "使用您自己的 API 密钥来绕过使用限制。您的密钥仅存储在浏览器本地,不会存储在服务器上。",
|
||||
"provider": "提供商",
|
||||
"provider": "服务商",
|
||||
"modelId": "模型 ID",
|
||||
"apiKey": "API 密钥",
|
||||
"apiKeyPlaceholder": "您的 API 密钥",
|
||||
@@ -101,16 +96,9 @@
|
||||
"language": "语言",
|
||||
"languageDescription": "选择界面语言。",
|
||||
"theme": "主题",
|
||||
"themeDescription": "界面和 DrawIO 画布的深色/浅色模式。",
|
||||
"drawioStyle": "DrawIO 样式",
|
||||
"drawioStyleDescription": "画布样式",
|
||||
"themeDefault": "默认",
|
||||
"themeDark": "深色",
|
||||
"themeMinimal": "简约",
|
||||
"themeSketch": "草图",
|
||||
"themeSimple": "简单",
|
||||
"diagramStyle": "图表样式",
|
||||
"diagramStyleDescription": "切换简约与精致图表输出模式。",
|
||||
"themeDescription": "界面用浅色还是深色,画布跟随同一主题。",
|
||||
"diagramStyle": "图形风格",
|
||||
"diagramStyleDescription": "AI 画新图时的风格:精致会用颜色和图标,简约只用朴素的图形。",
|
||||
"sendShortcut": "发送快捷键",
|
||||
"sendShortcutDescription": "选择发送消息的方式。",
|
||||
"enterToSend": "回车发送",
|
||||
@@ -125,46 +113,49 @@
|
||||
"httpsProxy": "HTTPS 代理",
|
||||
"applyProxy": "应用",
|
||||
"proxyApplied": "代理设置已应用",
|
||||
"diagramValidation": "图表验证(实验性)",
|
||||
"diagramValidationDescription": "使用视觉语言模型验证生成的图表。需要支持视觉的模型,如 GPT-5.2 或 Sonnet-4.5。",
|
||||
"enabled": "已启用",
|
||||
"disabled": "已禁用",
|
||||
"customSystemMessage": "自定义系统消息",
|
||||
"diagramValidation": "用截图检查图表(实验性)",
|
||||
"diagramValidationDescription": "每次画完后,让能看懂图片的模型检查截图并要求修正。需要能读图片的模型。",
|
||||
"customSystemMessage": "自定义指令",
|
||||
"customSystemMessageDescription": "添加自定义指令,将附加到 AI 的系统提示末尾。",
|
||||
"customSystemMessagePlaceholder": "例如:图表始终使用蓝色配色方案...",
|
||||
"maxOutputTokens": "最大输出 token 数",
|
||||
"maxOutputTokens": "输出 token 上限",
|
||||
"maxOutputTokensDescription": "单次回复的额度,思考过程和图表 XML 共用。如果 AI 一直在思考却没有生成图表,请把它调大。留空则使用默认值。",
|
||||
"panelVisibility": "大厅面板",
|
||||
"panelVisibilityDescription": "选择在聊天大厅显示哪些面板。",
|
||||
"showRecentChats": "最近聊天",
|
||||
"showMyTemplates": "我的模板",
|
||||
"showQuickExamples": "快速示例"
|
||||
"tabModels": "模型",
|
||||
"tabAbout": "关于",
|
||||
"themeLight": "浅色",
|
||||
"themeDarkMode": "深色",
|
||||
"themeSystem": "跟随系统",
|
||||
"accessCodeSaved": "访问码已保存",
|
||||
"proxyInvalid": "代理地址必须以 http:// 或 https:// 开头",
|
||||
"proxyFailed": "代理设置没有生效",
|
||||
"appVersion": "版本",
|
||||
"projectWebsite": "项目网站",
|
||||
"tabGeneral": "通用",
|
||||
"tabDrawing": "绘图",
|
||||
"sectionInterface": "界面",
|
||||
"sectionAccess": "访问"
|
||||
},
|
||||
"save": {
|
||||
"title": "保存图表",
|
||||
"description": "选择格式和文件名以保存您的图表。",
|
||||
"title": "导出图纸",
|
||||
"description": "选择格式和文件名。",
|
||||
"format": "格式",
|
||||
"filename": "文件名",
|
||||
"filenamePlaceholder": "输入文件名",
|
||||
"formats": {
|
||||
"drawio": "Draw.io XML",
|
||||
"drawio": "draw.io 文件",
|
||||
"png": "PNG 图片",
|
||||
"svg": "SVG 图片",
|
||||
"xmlsvg": "可编辑 SVG"
|
||||
"xmlsvg": "可编辑的 SVG"
|
||||
},
|
||||
"savedSuccessfully": "保存成功!"
|
||||
},
|
||||
"history": {
|
||||
"title": "图表历史",
|
||||
"description": "在 AI 修改之前保存的每个图表。\n点击图表以恢复它",
|
||||
"noHistory": "尚无历史记录。发送消息以创建图表历史。",
|
||||
"version": "版本",
|
||||
"restoreTo": "恢复到版本 {version}?"
|
||||
"savedSuccessfully": "已导出",
|
||||
"hints": {
|
||||
"drawio": "所有内容都能继续编辑",
|
||||
"png": "用于幻灯片和文档的图片",
|
||||
"svg": "放大也不会模糊的图片",
|
||||
"xmlsvg": "图片,也能在 draw.io 里打开编辑"
|
||||
}
|
||||
},
|
||||
"dialogs": {
|
||||
"clearTitle": "清除所有内容?",
|
||||
"clearDescription": "这将清除当前对话并重置图表。此操作无法撤消。",
|
||||
"clearEverything": "清除所有内容",
|
||||
"clearSuccess": "已开始新对话"
|
||||
},
|
||||
"errors": {
|
||||
@@ -189,9 +180,18 @@
|
||||
"sessionSaveFailed": "无法保存这个对话。浏览器存储空间可能已满,请在历史记录里删除旧对话后重试。",
|
||||
"sessionSaveFailedLeave": "无法保存这个对话,浏览器存储空间可能已满。可以不保存它、直接继续,再在新对话的列表里删除旧对话。",
|
||||
"continueWithoutSaving": "不保存,继续",
|
||||
"notADiagramFile": "{name} 不是 draw.io 图表文件。",
|
||||
"fileTooLong": "{name}:内容超过了 {limit}k 字符的上限({size}k 字符)",
|
||||
"fileReadFailed": "无法读取文件:{name}",
|
||||
"answerEndedEarly": "回答在图画完之前就结束了。",
|
||||
"attachmentsStillReading": "附件还在读取,读完后再发送。",
|
||||
"sendInProgress": "上一条消息还在发送,请稍后再试。",
|
||||
"answerInProgress": "回答还在进行,等它结束后再发送。",
|
||||
"cannotResend": "这条消息无法重新发送:发送时的画布没有保存下来。",
|
||||
"llm": {
|
||||
"invalid_api_key": "服务商拒绝了这个 API Key,请在模型设置里检查。",
|
||||
"forbidden": "服务商拒绝了这次请求。这个 Key 可能没有使用该模型或该地区的权限。",
|
||||
"server_key_forbidden": "今天的免费额度已经用完,明天会自动恢复。您也可以在模型设置里填写自己的 API Key 继续使用。",
|
||||
"model_not_found": "服务商找不到这个模型,请在模型设置里检查模型 ID。",
|
||||
"insufficient_quota": "服务商账户的余额或额度已经用完。",
|
||||
"rate_limited": "服务商正在限制请求频率,请稍等片刻再试。",
|
||||
@@ -207,30 +207,24 @@
|
||||
},
|
||||
"quota": {
|
||||
"dailyLimit": "已达每日配额",
|
||||
"tokenLimit": "已达每日令牌限制",
|
||||
"tokenLimit": "已达每日 token 上限",
|
||||
"tpmLimit": "速率限制",
|
||||
"tpmMessage": "请求过多。请稍等片刻。",
|
||||
"tpmMessageDetailed": "达到速率限制({limit} 令牌/分钟)。请等待 {seconds} 秒后再发送请求。",
|
||||
"messageApi": "看来您今天的体验次数已达上限。非常高兴您玩得开心,虽然本项目由字节跳动豆包慷慨赞助,但为了确保大家都能公平使用,我们不得不对使用量做一点小小的限制。",
|
||||
"tpmMessageDetailed": "达到速率限制(每分钟 {limit} token)。请等待 {seconds} 秒后再发送请求。",
|
||||
"messageApi": "看来您今天的体验次数已达上限。很高兴您玩得开心;为了让大家都能公平使用,演示站对用量做了限制。",
|
||||
"messageApiSelfHosted": null,
|
||||
"messageToken": "看来您今天的 Token 用量已达上限。非常高兴您玩得开心,虽然本项目由字节跳动豆包慷慨赞助,但为了确保大家都能公平使用,我们不得不对使用量做一点小小的限制。",
|
||||
"messageToken": "看来您今天的 token 用量已达上限。很高兴您玩得开心;为了让大家都能公平使用,演示站对用量做了限制。",
|
||||
"messageTokenSelfHosted": null,
|
||||
"tip": "<strong>提示:</strong>您可以使用自己的 API 密钥(点击设置图标)或自托管项目来绕过这些限制。",
|
||||
"tipSelfHosted": "<strong>提示:</strong>您可以在设置中配置自己的 API 密钥以继续使用服务。",
|
||||
"tip": "<strong>提示:</strong>您可以使用自己的 API Key(点击设置图标)或自托管项目来绕过这些限制。",
|
||||
"tipSelfHosted": "<strong>提示:</strong>您可以在设置中配置自己的 API Key 以继续使用服务。",
|
||||
"reset": "您的限制将在明天重置。感谢您的理解。",
|
||||
"doubaoSponsorship": "<a href=\"{link}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline hover:text-foreground\">点击此处注册</a>可获得每个模型 50 万免费 Token(包括豆包、DeepSeek 和 Kimi),然后在模型设置中配置您的 API Key。",
|
||||
"configModel": "使用您的密钥",
|
||||
"configModel": "使用自己的 API Key",
|
||||
"selfHost": "自托管",
|
||||
"sponsor": "赞助",
|
||||
"learnMore": "了解更多 →",
|
||||
"usedOf": "{used}/{limit}"
|
||||
},
|
||||
"tools": {
|
||||
"generateDiagram": "生成图表",
|
||||
"editDiagram": "编辑图表",
|
||||
"appendDiagram": "继续图表",
|
||||
"complete": "完成",
|
||||
"error": "错误",
|
||||
"truncated": "已截断"
|
||||
},
|
||||
"file": {
|
||||
@@ -245,7 +239,8 @@
|
||||
"extract": "提取",
|
||||
"Cancel": "取消",
|
||||
"enterUrl": "请输入 URL",
|
||||
"invalidFormat": "URL 格式无效"
|
||||
"invalidFormat": "URL 格式无效",
|
||||
"failed": "无法读取这个网页"
|
||||
},
|
||||
"reasoning": {
|
||||
"thinking": "思考中...",
|
||||
@@ -278,30 +273,29 @@
|
||||
"sessionHistory": {
|
||||
"tooltip": "聊天历史",
|
||||
"newChat": "新对话",
|
||||
"empty": "暂无聊天记录",
|
||||
"empty": "还没有图纸",
|
||||
"emptyHint": "开始对话吧",
|
||||
"today": "今天",
|
||||
"yesterday": "昨天",
|
||||
"thisWeek": "本周",
|
||||
"earlier": "更早",
|
||||
"deleteTitle": "删除此对话?",
|
||||
"deleteDescription": "这将永久删除此聊天会话及其图表。此操作无法撤消。",
|
||||
"recentChats": "最近对话",
|
||||
"deleteTitle": "删除这张图纸?",
|
||||
"deleteDescription": "图纸和它的对话会被永久删除。",
|
||||
"justNow": "刚刚",
|
||||
"searchPlaceholder": "搜索对话...",
|
||||
"noResults": "未找到对话"
|
||||
"searchPlaceholder": "搜索图纸…",
|
||||
"noResults": "未找到对话",
|
||||
"rename": "重命名",
|
||||
"busyHint": "回答完成后才能切换"
|
||||
},
|
||||
"templates": {
|
||||
"title": "我的模板库",
|
||||
"subtitle": "您的个人 prompt 库,快速创建图表",
|
||||
"emptyTitle": "暂无模板",
|
||||
"emptyDescription": "创建您的第一个模板,开始构建个人 prompt 库",
|
||||
"createFirst": "创建第一个模板",
|
||||
"emptyTitle": "还没有常用提示词",
|
||||
"emptyDescription": "把经常用的提示词存起来,比如“画一张……的 AWS 架构图”,之后会出现在这里。",
|
||||
"createFirst": "保存第一个提示词",
|
||||
"neverUsed": "未使用过",
|
||||
"usedCount": "使用 {count} 次",
|
||||
"myTemplates": "我的模板",
|
||||
"createTitle": "创建模板",
|
||||
"createDescription": "保存常用 prompt 以便重复使用。模板帮助您快速开始常用工作流。",
|
||||
"myTemplates": "常用提示词",
|
||||
"createTitle": "保存提示词",
|
||||
"createDescription": "把提示词存起来,以后再用。",
|
||||
"promptLabel": "提示词",
|
||||
"promptPlaceholder": "描述您想要创建的图表...",
|
||||
"promptRequired": "提示词不能为空",
|
||||
@@ -309,33 +303,34 @@
|
||||
"titlePlaceholder": "输入标题",
|
||||
"titleHint": "留空则使用提示词前 20 个字符作为标题",
|
||||
"descriptionLabel": "描述",
|
||||
"descriptionPlaceholder": "为此模板添加描述",
|
||||
"pinnedLabel": "置顶模板",
|
||||
"pinnedHint": "置顶的模板会显示在列表顶部",
|
||||
"createButton": "创建模板",
|
||||
"createFailed": "创建模板失败,请重试。",
|
||||
"editTitle": "编辑模板",
|
||||
"editDescription": "更新模板内容和设置。",
|
||||
"updateFailed": "更新模板失败,请重试。",
|
||||
"descriptionPlaceholder": "这个提示词的用途",
|
||||
"pinnedLabel": "置顶",
|
||||
"pinnedHint": "置顶的提示词显示在列表最上面",
|
||||
"createButton": "保存",
|
||||
"createFailed": "保存提示词失败,请重试。",
|
||||
"editTitle": "编辑提示词",
|
||||
"editDescription": "修改提示词和它的设置。",
|
||||
"updateFailed": "更新提示词失败,请重试。",
|
||||
"duplicate": "复制",
|
||||
"copySuffix": "(副本)",
|
||||
"deleteTitle": "删除此模板?",
|
||||
"deleteDescription": "此操作将永久删除该模板,无法撤销。",
|
||||
"deleteTitle": "删除这个提示词?",
|
||||
"deleteDescription": "提示词会被永久删除。",
|
||||
"confirmSendTitle": "替换当前输入?",
|
||||
"confirmSendDescription": "您有未发送的内容。发送此模板将替换它。",
|
||||
"confirmSendButton": "发送模板",
|
||||
"searchPlaceholder": "搜索模板...",
|
||||
"searchNoResults": "没有匹配的模板",
|
||||
"confirmSendDescription": "输入框里有还没发送的内容,发送这个提示词会替换它。",
|
||||
"confirmSendButton": "发送",
|
||||
"searchPlaceholder": "搜索提示词…",
|
||||
"searchNoResults": "没有匹配的提示词",
|
||||
"pin": "置顶",
|
||||
"unpin": "取消置顶",
|
||||
"saveAsTemplate": "保存为模板",
|
||||
"exportTemplates": "导出模板",
|
||||
"importTemplates": "导入模板",
|
||||
"exportEmpty": "没有可导出的模板",
|
||||
"exportSuccess": "成功导出 {count} 个模板",
|
||||
"saveAsTemplate": "保存这个提示词",
|
||||
"exportTemplates": "导出提示词",
|
||||
"importTemplates": "导入提示词",
|
||||
"exportEmpty": "没有可导出的提示词",
|
||||
"exportSuccess": "已导出 {count} 个提示词",
|
||||
"importNoFile": "请选择一个 JSON 文件",
|
||||
"importFailed": "导入失败:{error}",
|
||||
"importSuccess": "成功导入 {imported} 个模板,跳过 {skipped} 个重复"
|
||||
"importSuccess": "已导入 {imported} 个提示词,跳过 {skipped} 个重复",
|
||||
"saveDisabledHint": "先在输入框里写好提示词"
|
||||
},
|
||||
"validation": {
|
||||
"title": "验证图表",
|
||||
@@ -356,39 +351,30 @@
|
||||
"regenerateWithFeedback": "使用验证反馈重新生成图表"
|
||||
},
|
||||
"modelConfig": {
|
||||
"title": "AI 模型配置",
|
||||
"description": "配置多个 AI 提供商和模型",
|
||||
"configure": "配置",
|
||||
"addProvider": "添加提供商",
|
||||
"addProvider": "添加服务商",
|
||||
"addModel": "添加模型",
|
||||
"modelId": "模型 ID",
|
||||
"modelLabel": "显示名称",
|
||||
"streaming": "启用流式输出",
|
||||
"deleteProvider": "删除提供商",
|
||||
"deleteProvider": "删除服务商",
|
||||
"deleteModel": "删除模型",
|
||||
"noModels": "尚未配置模型。添加模型以开始使用。",
|
||||
"selectProvider": "选择一个提供商或添加新的",
|
||||
"configureMultiple": "配置多个 AI 提供商并轻松切换",
|
||||
"apiKeyStored": "API 密钥存储在您的浏览器本地",
|
||||
"test": "测试",
|
||||
"validationError": "验证失败",
|
||||
"addModelFirst": "请先添加至少一个模型以进行验证",
|
||||
"providers": "提供商",
|
||||
"addProviderHint": "添加提供商即可开始使用",
|
||||
"verified": "已验证",
|
||||
"configuration": "配置",
|
||||
"validationError": "测试没通过",
|
||||
"addModelFirst": "先添加一个模型。",
|
||||
"displayName": "显示名称",
|
||||
"bedrockApiKey": "Bedrock API Key",
|
||||
"bedrockApiKeyHint": "填了 API 密钥,下面的访问密钥就不用填。",
|
||||
"awsAccessKeyId": "AWS 访问密钥 ID",
|
||||
"awsSecretAccessKey": "AWS Secret Access Key",
|
||||
"awsRegion": "AWS 区域",
|
||||
"selectRegion": "选择区域",
|
||||
"apiKey": "API 密钥",
|
||||
"enterApiKey": "输入您的 API 密钥",
|
||||
"enterSecretKey": "输入您的 Secret Key",
|
||||
"apiKey": "API Key",
|
||||
"enterApiKey": "输入 API Key",
|
||||
"enterSecretKey": "输入 Secret Access Key",
|
||||
"baseUrl": "基础 URL",
|
||||
"optional": "(可选)",
|
||||
"getApiKey": "获取 API Key",
|
||||
"fetchModels": "从服务商获取模型列表",
|
||||
"noTools": "不支持工具调用",
|
||||
"mayNotDraw": "models.dev 显示这个模型不支持工具调用,可能无法画图。",
|
||||
"requestUrl": "请求将发往 {url}",
|
||||
@@ -399,180 +385,319 @@
|
||||
"models": "模型",
|
||||
"customModelId": "自定义模型 ID...",
|
||||
"allAdded": "已全部添加",
|
||||
"suggested": "推荐",
|
||||
"noModelsConfigured": "尚未配置模型",
|
||||
"modelIdEmpty": "模型 ID 不能为空",
|
||||
"modelIdExists": "此模型 ID 已存在",
|
||||
"configureProviders": "配置 AI 提供商",
|
||||
"selectProviderHint": "从列表中选择提供商或添加新的以配置 API 密钥和模型",
|
||||
"deleteConfirmDesc": "确定要删除 {name} 吗?这将移除所有配置的模型且无法撤销。",
|
||||
"typeToConfirm": "输入 \"{name}\" 以确认",
|
||||
"typeProviderName": "输入提供商名称...",
|
||||
"modelsConfiguredCount": "已配置 {count} 个模型",
|
||||
"validationFailedCount": "{count} 个模型验证失败",
|
||||
"typeProviderName": "输入服务商名称...",
|
||||
"requestFailed": "请求失败({status})",
|
||||
"cancel": "取消",
|
||||
"delete": "删除",
|
||||
"clickToChange": "(点击更改)",
|
||||
"usingServerDefault": "使用服务器默认模型",
|
||||
"selectModel": "选择模型",
|
||||
"searchModels": "搜索模型...",
|
||||
"noVerifiedModels": "没有已验证的模型。请先测试您的模型。",
|
||||
"noModelsFound": "未找到模型。",
|
||||
"default": "默认",
|
||||
"serverDefault": "服务器默认",
|
||||
"serverDefault": "服务器模型",
|
||||
"serverModels": "服务器模型",
|
||||
"userModels": "用户模型",
|
||||
"configureModels": "配置模型...",
|
||||
"onlyVerifiedShown": "仅显示已验证的模型",
|
||||
"showUnvalidatedModels": "显示未验证的模型",
|
||||
"allModelsShown": "显示所有模型(包括未验证的)",
|
||||
"unvalidatedModelWarning": "此模型尚未验证",
|
||||
"serverDefaultModel": "服务器默认模型",
|
||||
"showValue": "显示值",
|
||||
"hideValue": "隐藏值"
|
||||
"hideValue": "隐藏值",
|
||||
"myProviders": "我的服务商",
|
||||
"inUse": "正在使用",
|
||||
"listSeparator": "、",
|
||||
"serverModelsTitle": "服务器提供的模型",
|
||||
"serverDefaultSummary": "不用填写 API Key,使用服务器配置的默认模型。",
|
||||
"statusError": "{count} 个模型出错",
|
||||
"statusIncomplete": "还没设置完",
|
||||
"statusUntested": "{count} 个模型未测试",
|
||||
"statusOk": "{count} 个模型可用",
|
||||
"noModelsYet": "还没有模型",
|
||||
"keysStayLocal": "API Key 只保存在这台设备的浏览器里,发请求时才带给服务器。",
|
||||
"useOwnKey": "用自己的 API Key",
|
||||
"useOwnKeyHint": "接入其他服务商后,就能在聊天框的模型选择器里换用它们的模型。选一个开始:",
|
||||
"viewAllProviders": "查看全部 {count} 个服务商",
|
||||
"searchProviders": "搜索服务商,比如 DeepSeek、Qwen、Ollama",
|
||||
"noProvidersFound": "没有找到这个服务商。",
|
||||
"groupVendors": "模型厂商",
|
||||
"groupAggregators": "聚合平台",
|
||||
"groupCloud": "云平台",
|
||||
"groupSelfHosted": "自己部署",
|
||||
"noteBedrock": "AWS 凭证",
|
||||
"noteVertex": "Express 模式 Key",
|
||||
"noteAzure": "Key 和资源地址",
|
||||
"noteEdgeone": "不用 Key",
|
||||
"noteOllama": "Key 可不填",
|
||||
"noteSglang": "填服务地址",
|
||||
"added": "已添加",
|
||||
"awsCredentials": "AWS 凭证",
|
||||
"bedrockAuthApiKey": "Bedrock API Key",
|
||||
"bedrockAuthAccessKey": "访问密钥",
|
||||
"moreOptions": "更多选项:Base URL、显示名称",
|
||||
"moreOptionsName": "更多选项:显示名称",
|
||||
"keyRejected": "服务商拒绝了这个 API Key。检查上面的 Key 是否复制完整。",
|
||||
"modelNotFound": "服务商找不到这个模型 ID,请检查拼写。",
|
||||
"modelWorks": "可用",
|
||||
"modelWorksTime": "可用 · {seconds} 秒",
|
||||
"modelFailed": "出错",
|
||||
"modelUntested": "未测试",
|
||||
"needKey": "先填好 API Key。",
|
||||
"needAws": "先填好 AWS 凭证和区域。",
|
||||
"needModel": "先添加一个模型。",
|
||||
"stepConnect": "连接",
|
||||
"edgeoneNoKey": "EdgeOne Pages 使用这个网站部署时自带的模型服务,不用填写 API Key。",
|
||||
"stepModels": "选择模型",
|
||||
"fetchAllModels": "从 {name} 获取全部模型",
|
||||
"suggestedLabel": "推荐:",
|
||||
"orTypeModelId": "或者输入其他模型 ID",
|
||||
"add": "添加",
|
||||
"browseModels": "浏览模型",
|
||||
"stepTest": "测试",
|
||||
"testHint": "给每个模型发一条很短的消息,确认 Key 和模型都能用。",
|
||||
"testOne": "测试 {model}",
|
||||
"testAll": "测试全部 {count} 个模型",
|
||||
"testPassedOne": "{model} 可以用了",
|
||||
"testPassedAll": "{count} 个模型都可以用了",
|
||||
"answeredIn": "(回复用了 {seconds} 秒)",
|
||||
"useInChat": "在聊天里使用 {model}",
|
||||
"backToProviders": "返回服务商列表",
|
||||
"deleteProviderOnly": "删除 {name}",
|
||||
"addProviderEntry": "添加服务商…",
|
||||
"awsKeysRejected": "AWS 拒绝了这组访问密钥。检查两个密钥是否都复制完整。",
|
||||
"needAzure": "先填好 API Key 和 Azure 资源的 Base URL。",
|
||||
"validationFailedCountOne": "{count} 个模型没通过测试",
|
||||
"validationFailedCountOther": "{count} 个模型没通过测试",
|
||||
"deleteProviderNamedOne": "删除 {name} 和它的 {count} 个模型",
|
||||
"deleteProviderNamedOther": "删除 {name} 和它的 {count} 个模型",
|
||||
"serverModelsSummaryOne": "不用填写 API Key。共 {count} 个:{names}",
|
||||
"serverModelsSummaryOther": "不用填写 API Key。共 {count} 个:{names}",
|
||||
"noModelsReturned": "服务商没有返回任何模型。",
|
||||
"awsSessionToken": "AWS Session Token(可选)",
|
||||
"awsSessionTokenHint": "只有临时凭证才需要,也就是以 ASIA 开头的访问密钥。",
|
||||
"bedrockBothSaved": "这个服务商还保存着一对访问密钥,有 API Key 时它们不会被用到。",
|
||||
"removeAccessKeys": "删除访问密钥"
|
||||
},
|
||||
"admin": {
|
||||
"title": "管理员设置",
|
||||
"loginPrompt": "输入管理员密码(即 ADMIN_PASSWORD 环境变量)以管理服务器设置。",
|
||||
"title": "后台设置",
|
||||
"loginPrompt": "输入管理员密码(环境变量 ADMIN_PASSWORD)",
|
||||
"password": "密码",
|
||||
"signIn": "登录",
|
||||
"signingIn": "正在登录…",
|
||||
"signingIn": "登录中…",
|
||||
"loginFailed": "登录失败",
|
||||
"precedence": "文件覆盖环境变量 · 环境变量覆盖默认值",
|
||||
"notWritable": "此部署环境下设置文件不可写(无服务器平台没有持久化磁盘)。设置以只读方式显示——请改用环境变量进行配置。",
|
||||
"settingGroups": "设置分组",
|
||||
"enabled": "已启用",
|
||||
"disabled": "已禁用",
|
||||
"enableGroup": "启用 {group}",
|
||||
"unsavedChanges": "有未保存的更改",
|
||||
"saved": "设置已保存,更改立即生效。",
|
||||
"saveFailed": "保存失败。请检查网络连接后重试。",
|
||||
"invalidSettings": "部分设置无效。",
|
||||
"discard": "放弃",
|
||||
"saveChanges": "保存更改",
|
||||
"saving": "正在保存…",
|
||||
"sourceSaved": "已保存",
|
||||
"precedence": "优先级:本页设置 > 环境变量 > 默认值",
|
||||
"notWritable": "这里无法保存设置,只能查看;请改用环境变量",
|
||||
"settingGroups": "设置分类",
|
||||
"enabled": "已开启",
|
||||
"disabled": "已关闭",
|
||||
"enableGroup": "开启{group}",
|
||||
"unsavedChanges": "有未保存的修改",
|
||||
"saved": "已保存,立即生效(需重启的项除外)",
|
||||
"saveFailed": "保存失败,请检查网络后重试",
|
||||
"invalidSettings": "有设置填写有误,请按提示修改",
|
||||
"discard": "放弃修改",
|
||||
"saveChanges": "保存修改",
|
||||
"saving": "保存中…",
|
||||
"sourceSaved": "本页设置",
|
||||
"sourceEnv": "环境变量",
|
||||
"sourceSavedTitle": "在管理员设置文件中设置",
|
||||
"sourceEnvTitle": "通过环境变量设置",
|
||||
"restartRequired": "需要重启",
|
||||
"sourceSavedTitle": "来自本页设置",
|
||||
"sourceEnvTitle": "来自环境变量",
|
||||
"restartRequired": "需重启",
|
||||
"modified": "已修改",
|
||||
"notSet": "未设置",
|
||||
"savedReplace": "已保存({hint})——输入以替换",
|
||||
"showValue": "显示值",
|
||||
"hideValue": "隐藏值",
|
||||
"removeValue": "移除值",
|
||||
"removeValueTitle": "移除已保存的值",
|
||||
"savedReplace": "已保存({hint}),输入新值可替换",
|
||||
"showValue": "显示",
|
||||
"hideValue": "隐藏",
|
||||
"removeValue": "清除",
|
||||
"removeValueTitle": "清除已保存的值",
|
||||
"resetToDefault": "恢复默认",
|
||||
"models": "模型",
|
||||
"modelsDescription": "面向所有用户的服务端 provider 和模型——无需个人 API 密钥。当用户未选择模型时,使用默认 provider 的第一个模型。",
|
||||
"addProviderHint": "添加一个 provider,为所有用户提供服务端模型。",
|
||||
"selectProviderHint": "选择或添加一个 provider 以配置其凭证和模型。",
|
||||
"addProviderToOfferModels": "至少添加一个模型,才能向用户开放此 provider。",
|
||||
"managedViaEnv": "(通过环境变量管理)",
|
||||
"envReadOnly": "在 AI_MODELS_CONFIG / ai-models.json 中定义——此处只读。请编辑环境配置以更改。",
|
||||
"modelsDescription": "给所有用户用的模型,无需自带密钥",
|
||||
"addProviderHint": "添加服务商,为所有用户提供模型",
|
||||
"selectProviderHint": "选择或添加服务商,填写密钥和模型",
|
||||
"addProviderToOfferModels": "至少添加一个模型,用户才能看到这个服务商",
|
||||
"managedViaEnv": "(环境变量)",
|
||||
"envReadOnly": "由 AI_MODELS_CONFIG / ai-models.json 定义,这里只能查看,请到那里修改",
|
||||
"defaultModel": "默认模型",
|
||||
"noModelsConfigured": "未配置模型",
|
||||
"noModelsConfigured": "暂无模型",
|
||||
"modelCount": "{count} 个模型",
|
||||
"modelCountPlural": "{count} 个模型",
|
||||
"default": "默认",
|
||||
"setAsDefault": "设为默认 provider",
|
||||
"defaultProvider": "默认 provider",
|
||||
"setAsDefault": "设为默认服务商",
|
||||
"defaultProvider": "默认服务商",
|
||||
"modelIdPlaceholder": "模型 ID…",
|
||||
"addModel": "添加模型",
|
||||
"suggested": "推荐",
|
||||
"test": "测试",
|
||||
"testOk": "正常({ms} 毫秒)",
|
||||
"testOk": "通过({ms} 毫秒)",
|
||||
"testFailed": "失败",
|
||||
"removeModel": "移除 {model}",
|
||||
"removeModel": "删除 {model}",
|
||||
"deleteProviderTitle": "删除 {name}?",
|
||||
"deleteProviderDesc": "保存后,其凭证和模型将从服务器上移除。",
|
||||
"deleteProviderDesc": "保存后,它的密钥和模型会从服务器删除",
|
||||
"cancel": "取消",
|
||||
"delete": "删除",
|
||||
"groups": {
|
||||
"generation": {
|
||||
"title": "生成",
|
||||
"description": "应用于所有聊天请求的输出参数。"
|
||||
"title": "回复设置",
|
||||
"description": "控制 AI 怎么回复,对所有对话生效"
|
||||
},
|
||||
"access": {
|
||||
"title": "访问控制",
|
||||
"description": "限制谁可以使用此部署。"
|
||||
"title": "访问权限",
|
||||
"description": "限制谁可以使用这个站点"
|
||||
},
|
||||
"features": {
|
||||
"title": "功能",
|
||||
"description": "可选功能和安全开关。"
|
||||
"title": "可选功能",
|
||||
"description": "附加功能和安全选项"
|
||||
},
|
||||
"observability": {
|
||||
"title": "可观测性",
|
||||
"description": "对 LLM 调用进行 Langfuse 追踪。"
|
||||
"title": "调用记录",
|
||||
"description": "用 Langfuse 记录模型调用"
|
||||
},
|
||||
"quota": {
|
||||
"title": "配额与速率限制",
|
||||
"description": "按 IP 的用量限制。强制执行需要 DynamoDB 表。"
|
||||
"title": "用量限制",
|
||||
"description": "按 IP 限制用量,需要 DynamoDB 表才生效"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"TEMPERATURE": {
|
||||
"label": "温度",
|
||||
"description": "对于拒绝温度参数的推理模型,请留空。"
|
||||
"description": "越高越随机;不支持温度的推理模型请留空"
|
||||
},
|
||||
"MAX_OUTPUT_TOKENS": {
|
||||
"label": "最大输出 token 数"
|
||||
"label": "输出 token 上限"
|
||||
},
|
||||
"ACCESS_CODE_LIST": {
|
||||
"label": "访问码",
|
||||
"description": "以逗号分隔的列表。用户需输入其中之一才能聊天。留空 = 开放访问。"
|
||||
"description": "逗号分隔多个;输入其中一个才能用;留空则不限"
|
||||
},
|
||||
"ENABLE_VLM_VALIDATION": {
|
||||
"label": "VLM 图表验证",
|
||||
"description": "使用视觉模型对生成的图表进行可视化验证。"
|
||||
"label": "图表检查",
|
||||
"description": "画完后让能看图的模型检查截图"
|
||||
},
|
||||
"VALIDATION_MODEL": {
|
||||
"label": "验证模型",
|
||||
"description": "留空时回退到默认 AI 模型。"
|
||||
"label": "检查模型",
|
||||
"description": "留空则用默认模型"
|
||||
},
|
||||
"VALIDATION_TIMEOUT": {
|
||||
"label": "验证超时(毫秒)"
|
||||
"label": "检查超时(毫秒)"
|
||||
},
|
||||
"ENABLE_HISTORY_XML_REPLACE": {
|
||||
"label": "历史 XML 压缩",
|
||||
"description": "用占位符替换历史记录中的旧图表 XML。"
|
||||
"label": "精简旧图",
|
||||
"description": "对话历史里的旧图表只留简短标记"
|
||||
},
|
||||
"ALLOW_PRIVATE_URLS": {
|
||||
"label": "允许私有 URL",
|
||||
"description": "关闭以阻止对私有 IP 和内部主机名的请求(SSRF 防护)。"
|
||||
"label": "访问内网",
|
||||
"description": "关闭后,自定义模型地址不能指向内网,更安全"
|
||||
},
|
||||
"LANGFUSE_PUBLIC_KEY": {
|
||||
"label": "Langfuse Public Key"
|
||||
"label": "Langfuse 公钥"
|
||||
},
|
||||
"LANGFUSE_SECRET_KEY": {
|
||||
"label": "Langfuse Secret Key"
|
||||
"label": "Langfuse 密钥"
|
||||
},
|
||||
"LANGFUSE_BASEURL": {
|
||||
"label": "Langfuse Base URL"
|
||||
"label": "Langfuse 地址"
|
||||
},
|
||||
"DAILY_REQUEST_LIMIT": {
|
||||
"label": "每日请求上限",
|
||||
"description": "每个 IP 每天。"
|
||||
"label": "每日请求",
|
||||
"description": "每个 IP 每天的请求次数上限"
|
||||
},
|
||||
"DAILY_TOKEN_LIMIT": {
|
||||
"label": "每日 token 上限",
|
||||
"description": "每个 IP 每天。"
|
||||
"label": "每日 token",
|
||||
"description": "每个 IP 每天的 token 用量上限"
|
||||
},
|
||||
"TPM_LIMIT": {
|
||||
"label": "每分钟 token 数"
|
||||
"label": "每分钟 token"
|
||||
},
|
||||
"DYNAMODB_QUOTA_TABLE": {
|
||||
"label": "DynamoDB 表",
|
||||
"description": "留空时配额强制执行被禁用。"
|
||||
"label": "DynamoDB 表名",
|
||||
"description": "留空则不限制用量"
|
||||
},
|
||||
"DYNAMODB_REGION": {
|
||||
"label": "DynamoDB 区域"
|
||||
},
|
||||
"QUOTA_TIMEZONE": {
|
||||
"label": "配额时区",
|
||||
"description": "每日重置边界所用的时区。"
|
||||
"label": "时区",
|
||||
"description": "每日用量按这个时区的零点重置"
|
||||
}
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"export": "导出",
|
||||
"openFile": "打开 .drawio 文件",
|
||||
"canvasLoading": "正在加载画布…",
|
||||
"askAi": "让 AI 改这里",
|
||||
"untitled": "未命名图纸",
|
||||
"mobileCanvas": "画布",
|
||||
"mobileChat": "对话"
|
||||
},
|
||||
"selection": {
|
||||
"one": "已选:{label}",
|
||||
"many": "已选 {count} 个图形",
|
||||
"shape": "图形",
|
||||
"connector": "连线",
|
||||
"remove": "不发送选中的图形",
|
||||
"placeholder": "说说要怎么改选中的图形"
|
||||
},
|
||||
"versions": {
|
||||
"strip": "版本",
|
||||
"created": "画好了图表",
|
||||
"edited": "改好了图表",
|
||||
"undone": "这次修改已撤销",
|
||||
"undo": "撤销修改",
|
||||
"redo": "重做修改",
|
||||
"compare": "对比",
|
||||
"compareTitle": "对比版本",
|
||||
"currentCanvas": "现在的画布",
|
||||
"versionLabel": "第 {n} 版",
|
||||
"previous": "上一版",
|
||||
"next": "下一版",
|
||||
"rendering": "正在生成预览…",
|
||||
"showCode": "查看 XML",
|
||||
"hideCode": "收起 XML",
|
||||
"drawing": "正在画图…",
|
||||
"editing": "正在修改图表…",
|
||||
"loadingLibrary": "正在读取图形库…",
|
||||
"libraryLoaded": "读取了图形库",
|
||||
"failed": "这次没有成功",
|
||||
"failedRetrying": "这次没有成功,正在重试",
|
||||
"stopped": "已停止",
|
||||
"truncatedHint": "回复达到了输出长度上限,图表没有画完。可以要一张简单些的图,或者在 设置 > 绘图 里调高最大输出长度。",
|
||||
"noChanges": "没有可见的变化",
|
||||
"listSeparator": ",",
|
||||
"shapesAddedOne": "新增 1 个图形",
|
||||
"shapesAddedOther": "新增 {count} 个图形",
|
||||
"edgesAddedOne": "新增 1 条连线",
|
||||
"edgesAddedOther": "新增 {count} 条连线",
|
||||
"shapesChangedOne": "改了 1 个图形",
|
||||
"shapesChangedOther": "改了 {count} 个图形",
|
||||
"edgesChangedOne": "改了 1 条连线",
|
||||
"edgesChangedOther": "改了 {count} 条连线",
|
||||
"shapesRemovedOne": "删了 1 个图形",
|
||||
"shapesRemovedOther": "删了 {count} 个图形",
|
||||
"edgesRemovedOne": "删了 1 条连线",
|
||||
"edgesRemovedOther": "删了 {count} 条连线",
|
||||
"totals": "共 {shapes}、{edges}",
|
||||
"shapesTotalOne": "1 个图形",
|
||||
"shapesTotalOther": "{count} 个图形",
|
||||
"edgesTotalOne": "1 条连线",
|
||||
"edgesTotalOther": "{count} 条连线",
|
||||
"restoreVersion": "恢复到 v{n}",
|
||||
"restoredVersion": "已恢复到 v{n}",
|
||||
"undoRestore": "撤销",
|
||||
"noPreview": "没有预览",
|
||||
"compareSince": "从第 {n} 版到现在,画布上:",
|
||||
"isOnCanvas": "画布现在显示的就是这一版。",
|
||||
"differsElsewhere": "第一页的形状和连线与第 {n} 版相同,叠放顺序、其他页面或页面设置有改动。"
|
||||
},
|
||||
"lobby": {
|
||||
"title": "说说你要画什么",
|
||||
"lede": "描述一张图,或上传截图、PDF。得到的是可以继续编辑和导出的 draw.io 图。",
|
||||
"placeholder": "比如:用户登录的时序图,包含短信验证码和失败重试",
|
||||
"recent": "最近的图纸",
|
||||
"drawYourself": "从空白画布开始",
|
||||
"openFileHint": "接着编辑已有的图"
|
||||
}
|
||||
}
|
||||
|
||||
+9
-1
@@ -24,6 +24,8 @@ export type LLMErrorCode =
|
||||
| "provider_unavailable"
|
||||
| "cannot_connect"
|
||||
| "timeout"
|
||||
// A 403 on the server's own key, e.g. a daily spend cap blocked it
|
||||
| "server_key_forbidden"
|
||||
| "unknown"
|
||||
|
||||
export interface LLMError {
|
||||
@@ -130,7 +132,13 @@ export function streamErrorText(error: unknown, hideDetails = false): string {
|
||||
const classified = classifyLLMError(error)
|
||||
if (hideDetails) {
|
||||
console.error("[chat] Provider error:", error)
|
||||
classified.message = "The provider returned an error."
|
||||
if (classified.code === "forbidden") {
|
||||
// The hint says all the user can do; there is no message to add
|
||||
classified.code = "server_key_forbidden"
|
||||
classified.message = ""
|
||||
} else {
|
||||
classified.message = "The provider returned an error."
|
||||
}
|
||||
}
|
||||
return JSON.stringify(classified)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/** True on macOS and iOS, where shortcuts use ⌘ instead of Ctrl */
|
||||
export const isMac =
|
||||
typeof navigator !== "undefined" &&
|
||||
/Mac|iPhone|iPad/.test(navigator.userAgent)
|
||||
|
||||
/** Prefix for shortcut labels: "⌘" on Apple platforms, "Ctrl+" elsewhere */
|
||||
export const modKey = isMac ? "⌘" : "Ctrl+"
|
||||
@@ -0,0 +1,138 @@
|
||||
// What the model settings show about providers: the groups of the provider
|
||||
// picker, and how far a provider's setup has come
|
||||
|
||||
import {
|
||||
PROVIDER_INFO,
|
||||
type ProviderConfig,
|
||||
type ProviderName,
|
||||
} from "@/lib/types/model-config"
|
||||
|
||||
export type ProviderGroupId = "vendors" | "aggregators" | "cloud" | "selfHosted"
|
||||
|
||||
/** The provider picker's groups, each provider in exactly one */
|
||||
export const PROVIDER_GROUPS: {
|
||||
id: ProviderGroupId
|
||||
providers: ProviderName[]
|
||||
}[] = [
|
||||
{
|
||||
id: "vendors",
|
||||
providers: [
|
||||
"openai",
|
||||
"anthropic",
|
||||
"google",
|
||||
"deepseek",
|
||||
"qwen",
|
||||
"doubao",
|
||||
"glm",
|
||||
"kimi",
|
||||
"minimax",
|
||||
"mimo",
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "aggregators",
|
||||
providers: [
|
||||
"openrouter",
|
||||
"aihubmix",
|
||||
"siliconflow",
|
||||
"modelscope",
|
||||
"novita",
|
||||
"atlascloud",
|
||||
"qiniu",
|
||||
"gateway",
|
||||
],
|
||||
},
|
||||
{ id: "cloud", providers: ["bedrock", "vertexai", "azure", "edgeone"] },
|
||||
{ id: "selfHosted", providers: ["ollama", "sglang"] },
|
||||
]
|
||||
|
||||
/** Shown when the user has no provider yet */
|
||||
export const POPULAR_PROVIDERS: ProviderName[] = [
|
||||
"openai",
|
||||
"anthropic",
|
||||
"google",
|
||||
"deepseek",
|
||||
"openrouter",
|
||||
"qwen",
|
||||
]
|
||||
|
||||
/** Providers that need something other than a plain API key */
|
||||
export const PROVIDER_NOTE_KEYS: Partial<Record<ProviderName, string>> = {
|
||||
bedrock: "noteBedrock",
|
||||
vertexai: "noteVertex",
|
||||
azure: "noteAzure",
|
||||
edgeone: "noteEdgeone",
|
||||
ollama: "noteOllama",
|
||||
sglang: "noteSglang",
|
||||
}
|
||||
|
||||
/**
|
||||
* Providers whose base URL usually needs changing (Azure's default is only
|
||||
* an example; Ollama's is its cloud, SGLang's a local server) or comes with
|
||||
* a hint (MiniMax, MiMo): their folded options start open
|
||||
*/
|
||||
export const OPTIONS_OPEN: ProviderName[] = [
|
||||
"azure",
|
||||
"ollama",
|
||||
"sglang",
|
||||
"minimax",
|
||||
"mimo",
|
||||
]
|
||||
|
||||
/** The groups with only the providers whose name matches the search */
|
||||
export function filterProviderGroups(query: string) {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (!q) return PROVIDER_GROUPS
|
||||
return PROVIDER_GROUPS.map((group) => ({
|
||||
...group,
|
||||
providers: group.providers.filter(
|
||||
(p) =>
|
||||
PROVIDER_INFO[p].label.toLowerCase().includes(q) ||
|
||||
p.includes(q),
|
||||
),
|
||||
})).filter((group) => group.providers.length > 0)
|
||||
}
|
||||
|
||||
/** The credentials a test or a chat request needs are filled in */
|
||||
export function hasCredentials(p: ProviderConfig): boolean {
|
||||
switch (p.provider) {
|
||||
case "bedrock":
|
||||
return (
|
||||
(!!p.apiKey ||
|
||||
(!!p.awsAccessKeyId && !!p.awsSecretAccessKey)) &&
|
||||
!!p.awsRegion
|
||||
)
|
||||
case "vertexai":
|
||||
return !!p.vertexApiKey
|
||||
// Its default base URL names no real resource
|
||||
case "azure":
|
||||
return (
|
||||
!!p.apiKey &&
|
||||
!!p.baseUrl &&
|
||||
p.baseUrl !== PROVIDER_INFO.azure.defaultBaseUrl
|
||||
)
|
||||
case "edgeone":
|
||||
case "ollama":
|
||||
return true
|
||||
default:
|
||||
return !!p.apiKey
|
||||
}
|
||||
}
|
||||
|
||||
export type ProviderStatus =
|
||||
| { kind: "error"; count: number }
|
||||
| { kind: "incomplete" }
|
||||
| { kind: "untested"; count: number }
|
||||
| { kind: "ok"; count: number }
|
||||
|
||||
/** The one thing about a provider that most needs the user's attention */
|
||||
export function providerStatus(p: ProviderConfig): ProviderStatus {
|
||||
const failed = p.models.filter((m) => m.validated === false).length
|
||||
if (failed > 0) return { kind: "error", count: failed }
|
||||
if (!hasCredentials(p) || p.models.length === 0) {
|
||||
return { kind: "incomplete" }
|
||||
}
|
||||
const untested = p.models.filter((m) => m.validated !== true).length
|
||||
if (untested > 0) return { kind: "untested", count: untested }
|
||||
return { kind: "ok", count: p.models.length }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** "3 min ago", "yesterday", or a short date, in the UI language */
|
||||
export function formatRelativeTime(
|
||||
timestamp: number,
|
||||
locale: string,
|
||||
justNow: string,
|
||||
): string {
|
||||
const diffMs = Date.now() - timestamp
|
||||
const minutes = Math.floor(diffMs / 60_000)
|
||||
if (minutes < 1) return justNow
|
||||
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" })
|
||||
if (minutes < 60) return rtf.format(-minutes, "minute")
|
||||
const hours = Math.floor(minutes / 60)
|
||||
if (hours < 24) return rtf.format(-hours, "hour")
|
||||
const days = Math.floor(hours / 24)
|
||||
if (days < 7) return rtf.format(-days, "day")
|
||||
return new Date(timestamp).toLocaleDateString(locale, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
}
|
||||
+30
-6
@@ -1,6 +1,7 @@
|
||||
import { type DBSchema, type IDBPDatabase, openDB } from "idb"
|
||||
import { nanoid } from "nanoid"
|
||||
import { toast } from "sonner"
|
||||
import type { DiagramVersion } from "@/stores/versions-store"
|
||||
import type { Template } from "./template-storage"
|
||||
|
||||
// Constants
|
||||
@@ -20,13 +21,18 @@ export interface ChatSession {
|
||||
xmlSnapshots: [number, string][]
|
||||
diagramXml: string
|
||||
thumbnailDataUrl?: string // Small PNG preview of the diagram
|
||||
diagramHistory?: { svg: string; xml: string }[] // Version history of diagram edits
|
||||
// Old version list (before AI versions existed); read once, then replaced
|
||||
diagramHistory?: { svg: string; xml: string }[]
|
||||
// Diagram states produced by AI changes, shown as cards in the chat
|
||||
versions?: DiagramVersion[]
|
||||
}
|
||||
|
||||
export interface StoredMessage {
|
||||
id: string
|
||||
role: "user" | "assistant" | "system"
|
||||
parts: Array<{ type: string; [key: string]: unknown }>
|
||||
// e.g. the shapes selected when a user message was sent
|
||||
metadata?: unknown
|
||||
}
|
||||
|
||||
export interface SessionMetadata {
|
||||
@@ -214,13 +220,17 @@ export async function readSessionCount(): Promise<number | null> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteOldestSession(): Promise<void> {
|
||||
// keepId: a chat being opened, which stays
|
||||
export async function deleteOldestSession(keepId?: string): Promise<void> {
|
||||
if (!isIndexedDBAvailable()) return
|
||||
try {
|
||||
const db = await getDB()
|
||||
const tx = db.transaction(STORE_NAME, "readwrite")
|
||||
const index = tx.store.index("by-updated")
|
||||
const cursor = await index.openCursor()
|
||||
let cursor = await index.openCursor()
|
||||
while (cursor && cursor.value.id === keepId) {
|
||||
cursor = await cursor.continue()
|
||||
}
|
||||
if (cursor) {
|
||||
await cursor.delete()
|
||||
}
|
||||
@@ -230,17 +240,30 @@ export async function deleteOldestSession(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
// Enforce max sessions limit
|
||||
export async function enforceSessionLimit(): Promise<void> {
|
||||
// Enforce max sessions limit. keep: the chat being opened, asked for right
|
||||
// before each deletion (it can be clicked while the count is read)
|
||||
export async function enforceSessionLimit(
|
||||
keep?: () => string | undefined,
|
||||
): Promise<void> {
|
||||
const count = await getSessionCount()
|
||||
if (count > MAX_SESSIONS) {
|
||||
const toDelete = count - MAX_SESSIONS
|
||||
for (let i = 0; i < toDelete; i++) {
|
||||
await deleteOldestSession()
|
||||
await deleteOldestSession(keep?.())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function renameSession(
|
||||
id: string,
|
||||
title: string,
|
||||
): Promise<ChatSession | null> {
|
||||
const session = await getSession(id)
|
||||
if (!session) return null
|
||||
const updated = { ...session, title, updatedAt: Date.now() }
|
||||
return (await saveSession(updated)) ? updated : null
|
||||
}
|
||||
|
||||
// Helper: Create a new empty session
|
||||
export function createEmptySession(): ChatSession {
|
||||
return {
|
||||
@@ -300,6 +323,7 @@ export function sanitizeMessage(message: unknown): StoredMessage | null {
|
||||
id: msg.id as string,
|
||||
role: role as "user" | "assistant" | "system",
|
||||
parts,
|
||||
...(msg.metadata !== undefined && { metadata: msg.metadata }),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-20
@@ -1,26 +1,19 @@
|
||||
// Centralized localStorage keys for quota tracking and settings
|
||||
// Chat data is now stored in IndexedDB via session-storage.ts
|
||||
// Centralized localStorage keys for settings.
|
||||
// Chat data is stored in IndexedDB via session-storage.ts
|
||||
|
||||
export const STORAGE_KEYS = {
|
||||
// Quota tracking
|
||||
requestCount: "next-ai-draw-io-request-count",
|
||||
requestDate: "next-ai-draw-io-request-date",
|
||||
tokenCount: "next-ai-draw-io-token-count",
|
||||
tokenDate: "next-ai-draw-io-token-date",
|
||||
tpmCount: "next-ai-draw-io-tpm-count",
|
||||
tpmMinute: "next-ai-draw-io-tpm-minute",
|
||||
|
||||
// Settings
|
||||
// Access code for password-protected deployments
|
||||
accessCode: "next-ai-draw-io-access-code",
|
||||
accessCodeRequired: "next-ai-draw-io-access-code-required",
|
||||
aiProvider: "next-ai-draw-io-ai-provider",
|
||||
aiBaseUrl: "next-ai-draw-io-ai-base-url",
|
||||
aiApiKey: "next-ai-draw-io-ai-api-key",
|
||||
aiModel: "next-ai-draw-io-ai-model",
|
||||
|
||||
// Multi-model configuration
|
||||
modelConfigs: "next-ai-draw-io-model-configs",
|
||||
selectedModelId: "next-ai-draw-io-selected-model-id",
|
||||
|
||||
// Appearance
|
||||
darkMode: "next-ai-draw-io-dark-mode",
|
||||
locale: "next-ai-draw-io-locale",
|
||||
minimalStyle: "next-ai-draw-io-minimal-style",
|
||||
panelWidth: "next-ai-draw-io-panel-width",
|
||||
|
||||
// Chat input preferences
|
||||
sendShortcut: "next-ai-draw-io-send-shortcut",
|
||||
@@ -34,8 +27,6 @@ export const STORAGE_KEYS = {
|
||||
// Output token budget per turn (empty = server default)
|
||||
maxOutputTokens: "next-ai-draw-io-max-output-tokens",
|
||||
|
||||
// Panel visibility
|
||||
showRecentChats: "next-ai-draw-io-show-recent-chats",
|
||||
showMyTemplates: "next-ai-draw-io-show-my-templates",
|
||||
showQuickExamples: "next-ai-draw-io-show-quick-examples",
|
||||
// Langfuse session id
|
||||
sessionId: "next-ai-draw-io-session-id",
|
||||
} as const
|
||||
|
||||
+29
-31
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
STYLE_CLASS_EXAMPLE,
|
||||
SWIMLANE_EXAMPLE,
|
||||
TWO_EDGES_EXAMPLE,
|
||||
WAYPOINT_EXAMPLE,
|
||||
@@ -100,45 +101,41 @@ Note that:
|
||||
|
||||
When using edit_diagram tool:
|
||||
- Use operations: update (modify cell by id), add (new cell), delete (remove cell by id)
|
||||
- For update/add: provide cell_id and complete new_xml (full mxCell element including mxGeometry)
|
||||
- For update/add: provide cell_id and the complete new_xml in the same compact form (a shape with x, y, w, h; an edge with source and target)
|
||||
- For delete: only cell_id is needed
|
||||
- Named styles are not available in edit_diagram: write each cell's complete style
|
||||
- Find the cell_id from "Current diagram XML" in system context
|
||||
- Example update: {"operations": [{"operation": "update", "cell_id": "3", "new_xml": "<mxCell id=\\"3\\" value=\\"New Label\\" style=\\"rounded=1;\\" vertex=\\"1\\" parent=\\"1\\">\\n <mxGeometry x=\\"100\\" y=\\"100\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/>\\n</mxCell>"}]}
|
||||
- Example update: {"operations": [{"operation": "update", "cell_id": "3", "new_xml": "<mxCell id=\\"3\\" value=\\"New Label\\" style=\\"rounded=1;\\" x=\\"100\\" y=\\"100\\" w=\\"120\\" h=\\"60\\"/>"}]}
|
||||
- Example delete: {"operations": [{"operation": "delete", "cell_id": "5"}]}
|
||||
- Example add: {"operations": [{"operation": "add", "cell_id": "new1", "new_xml": "<mxCell id=\\"new1\\" value=\\"New Box\\" style=\\"rounded=1;\\" vertex=\\"1\\" parent=\\"1\\">\\n <mxGeometry x=\\"400\\" y=\\"200\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/>\\n</mxCell>"}]}
|
||||
- Example add: {"operations": [{"operation": "add", "cell_id": "new1", "new_xml": "<mxCell id=\\"new1\\" value=\\"New Box\\" style=\\"rounded=1;\\" x=\\"400\\" y=\\"200\\" w=\\"120\\" h=\\"60\\"/>"}]}
|
||||
|
||||
⚠️ JSON ESCAPING: Every " inside new_xml MUST be escaped as \\". Example: id=\\"5\\" value=\\"Label\\"
|
||||
|
||||
## Draw.io XML Structure Reference
|
||||
|
||||
**IMPORTANT:** You only generate the mxCell elements. The wrapper structure and root cells (id="0", id="1") are added automatically.
|
||||
**IMPORTANT:** You only generate the named styles and the mxCell elements. The wrapper structure and root cells (id="0", id="1") are added automatically. A named style is written before the cells as <mxStyle name="n" value="...style pairs..."/>; a cell uses it by putting the name among its style tokens (see Styles). A shape is one self-closing mxCell with x, y, w and h; an edge is one with source and target (a cell with source or target is always an edge). vertex="1", edge="1", parent="1" and the mxGeometry element are added automatically. Write parent only for a shape inside a container, and an mxGeometry element only for edge waypoints or for a separate label cell placed on an edge: <mxCell id="9" value="yes" style="edgeLabel;" parent="<edge id>" connectable="0"><mxGeometry x="-0.5" relative="1" as="geometry"/></mxCell>. An edge's own text simply goes in its value.
|
||||
|
||||
Example - generate ONLY this:
|
||||
\`\`\`xml
|
||||
<mxCell id="2" value="Label" style="rounded=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="2" value="Label" style="rounded=1;" x="100" y="100" w="120" h="60"/>
|
||||
\`\`\`
|
||||
|
||||
CRITICAL RULES:
|
||||
1. Generate ONLY mxCell elements - NO wrapper tags (<mxfile>, <mxGraphModel>, <root>)
|
||||
1. Generate ONLY mxStyle definitions and mxCell elements - NO wrapper tags (<mxfile>, <mxGraphModel>, <root>)
|
||||
2. Do NOT include root cells (id="0" or id="1") - they are added automatically
|
||||
3. ALL mxCell elements must be siblings - NEVER nest mxCell inside another mxCell
|
||||
4. Use unique sequential IDs starting from "2"
|
||||
5. Set parent="1" for top-level shapes, or parent="<container-id>" for grouped elements
|
||||
5. Write parent="<container-id>" only for shapes inside a container; top-level cells need no parent
|
||||
|
||||
Shape (vertex) example:
|
||||
\`\`\`xml
|
||||
<mxCell id="2" value="Label" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="2" value="Label" style="rounded=1;" x="100" y="100" w="120" h="60"/>
|
||||
\`\`\`
|
||||
|
||||
Connector (edge) example:
|
||||
\`\`\`xml
|
||||
<mxCell id="3" style="endArrow=classic;html=1;" edge="1" parent="1" source="2" target="4">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="3" style="edgeStyle=orthogonalEdgeStyle;" source="2" target="4"/>
|
||||
\`\`\`
|
||||
|
||||
### Edge Routing Rules:
|
||||
When creating edges/connectors, you MUST follow these rules to avoid overlapping lines:
|
||||
@@ -153,7 +150,7 @@ When creating edges/connectors, you MUST follow these rules to avoid overlapping
|
||||
|
||||
**Rule 3: Always specify exitX, exitY, entryX, entryY explicitly**
|
||||
- Every edge MUST have these 4 attributes set in the style
|
||||
- Example: style="edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.3;entryX=0;entryY=0.3;endArrow=classic;"
|
||||
- Example: style="edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.3;entryX=0;entryY=0.3;"
|
||||
|
||||
**Rule 4: Route edges AROUND intermediate shapes (obstacle avoidance) - CRITICAL!**
|
||||
- Before creating an edge, identify ALL shapes positioned between source and target
|
||||
@@ -188,17 +185,18 @@ When creating edges/connectors, you MUST follow these rules to avoid overlapping
|
||||
3. "Are any connection points at corners (both X and Y are 0 or 1)?" → If yes, use edge centers instead
|
||||
4. "Could I rearrange shapes to reduce edge crossings?" → If yes, revise layout
|
||||
|
||||
|
||||
\`\`\`
|
||||
|
||||
`
|
||||
|
||||
// Style instructions - only included when minimalStyle is false
|
||||
const STYLE_INSTRUCTIONS = `
|
||||
Common styles:
|
||||
- Shapes: rounded=1 (rounded corners), fillColor=#hex, strokeColor=#hex
|
||||
- Edges: endArrow=classic/block/open/none, startArrow=none/classic, curved=1, edgeStyle=orthogonalEdgeStyle
|
||||
- Text: fontSize=14, fontStyle=1 (bold), align=center/left/right
|
||||
## Styles
|
||||
Define each style used by several cells ONCE, as a named style before the cells, and use the name in the cells like a CSS class. A cell's style can combine a shape token, a name and overrides; later pairs win. Name only styles that two or more cells share; a style used by one cell stays inline. Names must not be draw.io's own style names: shapes such as text, ellipse, rhombus, swimlane, label, image, and colors such as blue, green, red, gray, yellow, orange, purple, pink. A definition applies to the call it is in: each display_diagram call defines the names it uses. The app expands the names, so the saved file is standard draw.io XML.
|
||||
\`\`\`xml
|
||||
${STYLE_CLASS_EXAMPLE}
|
||||
\`\`\`
|
||||
- NEVER write html=1 or whiteSpace=wrap: the app adds html=1 to every cell and whiteSpace=wrap to shapes. Labels are HTML: use <br> for a line break and <b> for bold, never \\n; a literal < or > in a label is written &lt; or &gt;.
|
||||
- Do NOT repeat what draw.io already uses. For a plain shape: rounded=0, align=center, verticalAlign=middle, fontSize=12, strokeWidth=1, fillColor=#ffffff, strokeColor=#000000, fontColor=#000000. For an edge: endArrow=classic, strokeColor=#000000. Writing one of them is right only when it overrides what a name or the shape sets: an edge is rounded by default, so rounded=0 on an edge is a real setting, and a text cell is left/top aligned by default, so there align=center or verticalAlign=middle are real settings.
|
||||
- Keys: shapes rounded=1, fillColor=#hex, strokeColor=#hex; edges endArrow=block/open/none, startArrow=classic, curved=1, dashed=1, edgeStyle=orthogonalEdgeStyle; text fontSize=14, fontStyle=1 (bold), align=center/right.
|
||||
`
|
||||
|
||||
// Minimal style instruction - skip styling and focus on layout (prepended to prompt for emphasis)
|
||||
@@ -208,13 +206,13 @@ const MINIMAL_STYLE_INSTRUCTION = `
|
||||
### No Styling - Plain Black/White Only
|
||||
- NO fillColor, NO strokeColor, NO rounded, NO fontSize, NO fontStyle
|
||||
- NO color attributes (no hex colors like #ff69b4)
|
||||
- Style: "whiteSpace=wrap;html=1;" for shapes, "html=1;endArrow=classic;" for edges
|
||||
- Shapes: no style, or only the shape (ellipse, rhombus). Edges: edgeStyle=orthogonalEdgeStyle plus the exit/entry points from the Edge Routing Rules, nothing else. html=1 and whiteSpace=wrap are added automatically.
|
||||
- IGNORE all color/style examples below
|
||||
|
||||
### Container/Group Shapes - MUST be Transparent
|
||||
- For container shapes (boxes that contain other shapes): use "fillColor=none;" to make background transparent
|
||||
- This prevents containers from covering child elements
|
||||
- Example: style="whiteSpace=wrap;html=1;fillColor=none;" for container rectangles
|
||||
- Example: style="fillColor=none;" for container rectangles
|
||||
|
||||
### Focus on Layout Quality
|
||||
Since we skip styling, STRICTLY follow the "Edge Routing Rules" section below:
|
||||
@@ -235,10 +233,10 @@ const EXTENDED_ADDITIONS = `
|
||||
### display_diagram Details
|
||||
|
||||
**VALIDATION RULES** (XML will be rejected if violated):
|
||||
1. Generate ONLY mxCell elements - wrapper tags and root cells are added automatically
|
||||
1. Generate ONLY mxStyle definitions and mxCell elements - wrapper tags and root cells are added automatically
|
||||
2. All mxCell elements must be siblings - never nested inside other mxCell elements
|
||||
3. Every mxCell needs a unique id attribute (start from "2")
|
||||
4. Every mxCell needs a valid parent attribute (use "1" for top-level, or container-id for grouped)
|
||||
4. parent defaults to "1"; write it only for a shape inside a container (the container's id)
|
||||
5. Edge source/target attributes must reference existing cell IDs
|
||||
6. Escape special characters in values: < for <, > for >, & for &, " for "
|
||||
|
||||
@@ -257,7 +255,7 @@ ${SWIMLANE_EXAMPLE}
|
||||
3. Complete the remaining mxCell elements
|
||||
4. If still truncated, call append_diagram again with the next fragment
|
||||
|
||||
**Example:** If previous output ended with \`<mxCell id="x" style="rounded=1\`, continue with \`;" vertex="1">...\` and complete the remaining elements.
|
||||
**Example:** If previous output ended with \`<mxCell id="x" style="rounded=1\`, continue with \`;" x="40" y="40" w="120" h="60"/>\` and complete the remaining elements.
|
||||
|
||||
### edit_diagram Details
|
||||
|
||||
@@ -283,12 +281,12 @@ edit_diagram uses ID-based operations to modify cells directly by their id attri
|
||||
|
||||
Change label:
|
||||
\`\`\`json
|
||||
{"operations": [{"operation": "update", "cell_id": "3", "new_xml": "<mxCell id=\\"3\\" value=\\"New Label\\" style=\\"rounded=1;\\" vertex=\\"1\\" parent=\\"1\\">\\n <mxGeometry x=\\"100\\" y=\\"100\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/>\\n</mxCell>"}]}
|
||||
{"operations": [{"operation": "update", "cell_id": "3", "new_xml": "<mxCell id=\\"3\\" value=\\"New Label\\" style=\\"rounded=1;\\" x=\\"100\\" y=\\"100\\" w=\\"120\\" h=\\"60\\"/>"}]}
|
||||
\`\`\`
|
||||
|
||||
Add new shape:
|
||||
\`\`\`json
|
||||
{"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;\\" x=\\"400\\" y=\\"200\\" w=\\"120\\" h=\\"60\\"/>"}]}
|
||||
\`\`\`
|
||||
|
||||
Delete container (children & edges auto-deleted):
|
||||
@@ -312,7 +310,7 @@ ${TWO_EDGES_EXAMPLE}
|
||||
|
||||
### Edge with single waypoint (simple detour):
|
||||
\`\`\`xml
|
||||
<mxCell id="edge1" style="edgeStyle=orthogonalEdgeStyle;exitX=0.5;exitY=1;entryX=0.5;entryY=0;endArrow=classic;" edge="1" parent="1" source="a" target="b">
|
||||
<mxCell id="edge1" style="edgeStyle=orthogonalEdgeStyle;exitX=0.5;exitY=1;entryX=0.5;entryY=0;" edge="1" parent="1" source="a" target="b">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="300" y="150"/>
|
||||
|
||||
@@ -60,7 +60,9 @@ export interface MultiModelConfig {
|
||||
version: 1
|
||||
providers: ProviderConfig[]
|
||||
selectedModelId?: string // Currently selected model's UUID
|
||||
showUnvalidatedModels?: boolean // Show models that haven't been validated
|
||||
// Older versions saved here whether untested models were listed in the
|
||||
// model picker; they always are now
|
||||
showUnvalidatedModels?: boolean
|
||||
}
|
||||
|
||||
// Flattened model for dropdown display
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import {
|
||||
extractPdfText,
|
||||
extractTextFileContent,
|
||||
@@ -16,11 +17,24 @@ export interface FileData {
|
||||
isExtracting: boolean
|
||||
}
|
||||
|
||||
/** Toast texts; {name}, {limit} and {size} are filled in */
|
||||
export interface FileProcessorMessages {
|
||||
tooLong: string
|
||||
readFailed: string
|
||||
}
|
||||
|
||||
const DEFAULT_MESSAGES: FileProcessorMessages = {
|
||||
tooLong: "{name}: Content exceeds {limit}k character limit ({size}k chars)",
|
||||
readFailed: "Failed to read file: {name}",
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for processing file uploads, especially PDFs and text files.
|
||||
* Handles text extraction, character limit validation, and cleanup.
|
||||
*/
|
||||
export function useFileProcessor() {
|
||||
export function useFileProcessor(
|
||||
messages: FileProcessorMessages = DEFAULT_MESSAGES,
|
||||
) {
|
||||
const [files, setFiles] = useState<File[]>([])
|
||||
const [pdfData, setPdfData] = useState<Map<File, FileData>>(new Map())
|
||||
|
||||
@@ -58,9 +72,12 @@ export function useFileProcessor() {
|
||||
|
||||
// Check character limit
|
||||
if (text.length > MAX_EXTRACTED_CHARS) {
|
||||
const limitK = MAX_EXTRACTED_CHARS / 1000
|
||||
toast.error(
|
||||
`${file.name}: Content exceeds ${limitK}k character limit (${(text.length / 1000).toFixed(1)}k chars)`,
|
||||
formatMessage(messages.tooLong, {
|
||||
name: file.name,
|
||||
limit: MAX_EXTRACTED_CHARS / 1000,
|
||||
size: (text.length / 1000).toFixed(1),
|
||||
}),
|
||||
)
|
||||
setPdfData((prev) => {
|
||||
const next = new Map(prev)
|
||||
@@ -85,7 +102,9 @@ export function useFileProcessor() {
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to extract text:", error)
|
||||
toast.error(`Failed to read file: ${file.name}`)
|
||||
toast.error(
|
||||
formatMessage(messages.readFailed, { name: file.name }),
|
||||
)
|
||||
setPdfData((prev) => {
|
||||
const next = new Map(prev)
|
||||
next.delete(file)
|
||||
|
||||
+11
-2
@@ -2,10 +2,19 @@
|
||||
* Generate a userId from request for tracking purposes.
|
||||
* Uses base64url encoding of IP for URL-safe identifier.
|
||||
* Note: base64 is reversible - this is NOT privacy protection.
|
||||
*
|
||||
* The first X-Forwarded-For entry is whatever the visitor sent, so behind a
|
||||
* CDN set CLIENT_IP_HEADER to the header it fills with the real IP (e.g.
|
||||
* cf-connecting-ip), and ORIGIN_SECRET so requests that skip the CDN are
|
||||
* refused (see proxy.ts).
|
||||
*/
|
||||
export function getUserIdFromRequest(req: Request): string {
|
||||
const forwardedFor = req.headers.get("x-forwarded-for")
|
||||
const rawIp = forwardedFor?.split(",")[0]?.trim() || "anonymous"
|
||||
const ipHeader = process.env.CLIENT_IP_HEADER
|
||||
const rawIp =
|
||||
(ipHeader
|
||||
? req.headers.get(ipHeader)?.trim()
|
||||
: req.headers.get("x-forwarded-for")?.split(",")[0]?.trim()) ||
|
||||
"anonymous"
|
||||
return rawIp === "anonymous"
|
||||
? rawIp
|
||||
: `user-${Buffer.from(rawIp).toString("base64url")}`
|
||||
|
||||
+47
-19
@@ -2,6 +2,8 @@ import { type ClassValue, clsx } from "clsx"
|
||||
import * as pako from "pako"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { hasCells } from "@/packages/mcp-server/src/pages.ts"
|
||||
import { readStyleClasses } from "@/packages/mcp-server/src/style-classes.ts"
|
||||
import { repairQuoteBeforeSlash } from "@/packages/mcp-server/src/xml-validation.ts"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
@@ -41,7 +43,12 @@ export function isRealDiagram(xml: string | undefined | null): boolean {
|
||||
* @returns true if XML appears complete, false if truncated or empty
|
||||
*/
|
||||
export function isMxCellXmlComplete(xml: string | undefined | null): boolean {
|
||||
const trimmed = xml?.trim() || ""
|
||||
// Named style definitions before the cells are not cells: output cut off
|
||||
// right after them is incomplete. A compact cell whose last quote is
|
||||
// missing is complete; prepareNewDiagram repairs it.
|
||||
const trimmed = repairQuoteBeforeSlash(
|
||||
readStyleClasses(xml || "").xml,
|
||||
).trim()
|
||||
if (!trimmed) return false
|
||||
|
||||
// Find position of last complete mxCell ending (either /> or </mxCell>)
|
||||
@@ -89,7 +96,9 @@ export function extractCompleteMxCells(xml: string | undefined | null): string {
|
||||
// Match self-closing <mxCell ... /> or <mxCell ...>...</mxCell>, in document order.
|
||||
// The lazy [^>]*? tries "/>" first, so a self-closing cell never swallows
|
||||
// the following cells up to the next </mxCell>.
|
||||
const cellPattern = /<mxCell\b[^>]*?(?:\/>|>[\s\S]*?<\/mxCell>)/g
|
||||
// Quoted values may hold ">", so the tag ends at the first ">" outside them
|
||||
const cellPattern =
|
||||
/<mxCell\b(?:[^<>"']|"[^"]*"|'[^']*')*?(?:\/>|>[\s\S]*?<\/mxCell>)/g
|
||||
|
||||
return (xml.match(cellPattern) || []).join("\n")
|
||||
}
|
||||
@@ -152,7 +161,8 @@ export function formatXML(xml: string, indent: string = " "): string {
|
||||
export function convertToLegalXml(xmlString: string): string {
|
||||
// This regex will match either self-closing <mxCell .../> or a block element
|
||||
// <mxCell ...> ... </mxCell>. Unfinished ones are left out because they don't match.
|
||||
const regex = /<mxCell\b[^>]*(?:\/>|>([\s\S]*?)<\/mxCell>)/g
|
||||
const regex =
|
||||
/<mxCell\b(?:[^<>"']|"[^"]*"|'[^']*')*?(?:\/>|>([\s\S]*?)<\/mxCell>)/g
|
||||
let match: RegExpExecArray | null
|
||||
let result = "<root>\n"
|
||||
|
||||
@@ -217,12 +227,18 @@ export function convertToLegalXml(xmlString: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace nodes in a Draw.io XML diagram
|
||||
* Replace the cells of one page of a Draw.io XML document
|
||||
* @param currentXML - The original Draw.io XML string
|
||||
* @param nodes - The XML string containing new nodes to replace in the diagram
|
||||
* @param pageId - The page whose cells are replaced; the first page when
|
||||
* missing or not found
|
||||
* @returns The updated XML string with replaced nodes
|
||||
*/
|
||||
export function replaceNodes(currentXML: string, nodes: string): string {
|
||||
export function replaceNodes(
|
||||
currentXML: string,
|
||||
nodes: string,
|
||||
pageId?: string | null,
|
||||
): string {
|
||||
// Check for valid inputs
|
||||
if (!currentXML || !nodes) {
|
||||
throw new Error("Both currentXML and nodes must be provided")
|
||||
@@ -241,16 +257,23 @@ export function replaceNodes(currentXML: string, nodes: string): string {
|
||||
|
||||
const nodesDoc = parser.parseFromString(nodesString, "text/xml")
|
||||
|
||||
// The page to draw on, when the document has it
|
||||
const page = pageId
|
||||
? Array.from(currentDoc.getElementsByTagName("diagram")).find(
|
||||
(diagram) => diagram.getAttribute("id") === pageId,
|
||||
)
|
||||
: undefined
|
||||
const scope: ParentNode = page ?? currentDoc
|
||||
// Find the root element in the current document
|
||||
let currentRoot = currentDoc.querySelector("mxGraphModel > root")
|
||||
let currentRoot = scope.querySelector("mxGraphModel > root")
|
||||
if (!currentRoot) {
|
||||
// If no root element is found, create the proper structure
|
||||
const mxGraphModel =
|
||||
currentDoc.querySelector("mxGraphModel") ||
|
||||
scope.querySelector("mxGraphModel") ||
|
||||
currentDoc.createElement("mxGraphModel")
|
||||
|
||||
if (!currentDoc.contains(mxGraphModel)) {
|
||||
currentDoc.appendChild(mxGraphModel)
|
||||
;(page ?? currentDoc).appendChild(mxGraphModel)
|
||||
}
|
||||
|
||||
currentRoot = currentDoc.createElement("root")
|
||||
@@ -320,10 +343,13 @@ export function replaceNodes(currentXML: string, nodes: string): string {
|
||||
|
||||
/**
|
||||
* Decode an xmlsvg export (SVG data URL) into uncompressed diagram XML.
|
||||
* Only the first page is returned; for the full multi-page document use the
|
||||
* autosaved chartXML instead.
|
||||
* One page is returned: the one with the given id, else the first; for the
|
||||
* full multi-page document use the autosaved chartXML instead.
|
||||
*/
|
||||
export function extractDiagramXML(xml_svg_string: string): string {
|
||||
export function extractDiagramXML(
|
||||
xml_svg_string: string,
|
||||
pageId?: string | null,
|
||||
): string {
|
||||
try {
|
||||
// 1. Parse the SVG string (using built-in DOMParser in a browser-like environment)
|
||||
const svgString = atob(xml_svg_string.slice(26))
|
||||
@@ -341,17 +367,19 @@ export function extractDiagramXML(xml_svg_string: string): string {
|
||||
throw new Error("SVG element does not have a 'content' attribute.")
|
||||
}
|
||||
|
||||
// 3. Decode HTML entities (using a minimal function)
|
||||
function decodeHtmlEntities(str: string) {
|
||||
const textarea = document.createElement("textarea") // Use built-in element
|
||||
textarea.innerHTML = str
|
||||
return textarea.value
|
||||
}
|
||||
const xmlContent = decodeHtmlEntities(encodedContent)
|
||||
// 3. getAttribute already decoded the entities: decoding again
|
||||
// would break values that hold them (a page named "R & D")
|
||||
const xmlContent = encodedContent
|
||||
|
||||
// 4. Parse the XML content
|
||||
const xmlDoc = parser.parseFromString(xmlContent, "text/xml")
|
||||
const diagramElement = xmlDoc.querySelector("diagram")
|
||||
const diagrams = Array.from(xmlDoc.getElementsByTagName("diagram"))
|
||||
const diagramElement =
|
||||
(pageId &&
|
||||
diagrams.find(
|
||||
(diagram) => diagram.getAttribute("id") === pageId,
|
||||
)) ||
|
||||
diagrams[0]
|
||||
|
||||
if (!diagramElement) {
|
||||
throw new Error("No diagram element found")
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { ChangeSummary } from "@/lib/diagram-diff"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
|
||||
type VersionDict = Record<string, string>
|
||||
|
||||
const PARTS: [keyof ChangeSummary, string][] = [
|
||||
["shapesAdded", "shapesAdded"],
|
||||
["edgesAdded", "edgesAdded"],
|
||||
["shapesChanged", "shapesChanged"],
|
||||
["edgesChanged", "edgesChanged"],
|
||||
["shapesRemoved", "shapesRemoved"],
|
||||
["edgesRemoved", "edgesRemoved"],
|
||||
]
|
||||
|
||||
/**
|
||||
* "Added 2 shapes, changed 1 connector". Each dictionary entry has a
|
||||
* singular (...One) and plural (...Other) form; languages without plurals
|
||||
* use the same text for both.
|
||||
*/
|
||||
export function describeChanges(
|
||||
summary: ChangeSummary,
|
||||
t: VersionDict,
|
||||
): string {
|
||||
const pieces = PARTS.filter(([field]) => summary[field] > 0).map(
|
||||
([field, key]) => {
|
||||
const count = summary[field]
|
||||
const template = count === 1 ? t[`${key}One`] : t[`${key}Other`]
|
||||
return formatMessage(template ?? "", { count })
|
||||
},
|
||||
)
|
||||
if (pieces.length === 0) return t.noChanges ?? ""
|
||||
const text = pieces.join(t.listSeparator ?? ", ")
|
||||
// Sentence case for scripts with letter case
|
||||
return text.charAt(0).toUpperCase() + text.slice(1)
|
||||
}
|
||||
|
||||
/** "3 shapes, 1 connector": what a diagram drawn from scratch holds */
|
||||
export function describeTotals(summary: ChangeSummary, t: VersionDict): string {
|
||||
const count = (n: number, key: string) =>
|
||||
formatMessage((n === 1 ? t[`${key}One`] : t[`${key}Other`]) ?? "", {
|
||||
count: n,
|
||||
})
|
||||
return formatMessage(t.totals ?? "", {
|
||||
shapes: count(summary.shapesAdded, "shapesTotal"),
|
||||
edges: count(summary.edgesAdded, "edgesTotal"),
|
||||
})
|
||||
}
|
||||
Generated
+1071
-2616
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user