mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-10-12 20:49:53 +08:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d87c3c0bab | ||
|
|
1333ed68c6 | ||
|
|
9a6a808187 | ||
|
|
fb87291cde | ||
|
|
14f29af939 | ||
|
|
fc8ffc5655 | ||
|
|
165175be20 | ||
|
|
06621764b2 | ||
|
|
3a9168e5b3 | ||
|
|
8ca2d03e7f | ||
|
|
610ba6872d | ||
|
|
a3664367ce | ||
|
|
4c7b2cc0c5 | ||
|
|
07f3e3c2a3 | ||
|
|
8ab837679e | ||
|
|
cb066a4825 | ||
|
|
77be43d996 | ||
|
|
c774a39c33 | ||
|
|
3d1a020b35 | ||
|
|
8d690503d4 | ||
|
|
4b4f36e374 | ||
|
|
a9091e96f1 | ||
|
|
213b672e92 | ||
|
|
d1ee1594f1 | ||
|
|
cd5352ca88 | ||
|
|
498ee628f1 | ||
|
|
a6e812d3a5 | ||
|
|
02eaa0bd22 | ||
|
|
4cba863fd9 | ||
|
|
7682e479e3 | ||
|
|
a7ae114edf | ||
|
|
e117095c7b | ||
|
|
f0f0bc0dc0 | ||
|
|
d5096b9628 |
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"extends": ["next/core-web-vitals", "next/typescript"]
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Type check
|
||||
run: npx tsc --noEmit
|
||||
|
||||
- name: Lint check
|
||||
run: npm run check
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
@@ -4,14 +4,11 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
- dev
|
||||
tags:
|
||||
- 'v*'
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
|
||||
@@ -86,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
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
name: Publish MCP Server
|
||||
|
||||
# Publishes @next-ai-drawio/mcp-server to npm via OIDC trusted publishing
|
||||
# (no token, no OTP). Triggers when packages/mcp-server changes on main;
|
||||
# (no token, no OTP). Triggers when packages/mcp-server or the web app code
|
||||
# bundled into the canvas shell (scripts/build-shell.mjs) changes on main;
|
||||
# skips silently if the package.json version is already on npm — so a
|
||||
# release is just "bump the version in a PR and merge".
|
||||
on:
|
||||
@@ -10,6 +11,16 @@ on:
|
||||
- main
|
||||
paths:
|
||||
- "packages/mcp-server/**"
|
||||
# The canvas shell is bundled from these with the root's lockfile
|
||||
- "components/**"
|
||||
- "contexts/**"
|
||||
- "hooks/**"
|
||||
- "lib/**"
|
||||
- "stores/**"
|
||||
- "app/globals.css"
|
||||
- "package-lock.json"
|
||||
# The package's build scripts import the root's scripts/drawio-zip.mjs
|
||||
- "scripts/**"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -35,7 +46,9 @@ jobs:
|
||||
with:
|
||||
node-version: 24
|
||||
cache: "npm"
|
||||
cache-dependency-path: packages/mcp-server/package-lock.json
|
||||
cache-dependency-path: |
|
||||
package-lock.json
|
||||
packages/mcp-server/package-lock.json
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
# Trusted publishing requires npm >= 11.5.1
|
||||
@@ -54,6 +67,13 @@ jobs:
|
||||
echo "publish=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# The canvas shell (scripts/build-shell.mjs) is bundled from the web
|
||||
# app's components with the root's esbuild, Tailwind and React
|
||||
- name: Install repository dependencies
|
||||
if: steps.version.outputs.publish == 'true'
|
||||
working-directory: .
|
||||
run: npm ci
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.version.outputs.publish == 'true'
|
||||
run: npm ci
|
||||
@@ -62,6 +82,9 @@ jobs:
|
||||
if: steps.version.outputs.publish == 'true'
|
||||
run: npm test
|
||||
|
||||
# The build downloads the pinned draw.war from GitHub releases
|
||||
# (scripts/fetch-drawio.mjs) and bundles a trimmed draw.io into
|
||||
# dist/drawio; check-package confirms it is in the tarball
|
||||
- name: Build and check package contents
|
||||
if: steps.version.outputs.publish == 'true'
|
||||
run: npm run build && npm run check-package
|
||||
|
||||
+101
-7
@@ -6,6 +6,13 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
lint-and-unit:
|
||||
name: Lint & Unit Tests
|
||||
@@ -16,32 +23,119 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "24"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Type check
|
||||
run: npx tsc --noEmit
|
||||
|
||||
- name: Run lint
|
||||
run: npm run check
|
||||
|
||||
- name: Run unit tests
|
||||
run: npm run test -- --run
|
||||
|
||||
# The MCP server package ships its own vitest because its DOM polyfill
|
||||
# (linkedom) needs `environment: node`, while the root vitest uses jsdom
|
||||
# for the Next.js app. Install + run its tests separately so CI catches
|
||||
# multi-page mxfile regressions.
|
||||
# The MCP server package: its own vitest (its DOM polyfill, linkedom, needs
|
||||
# `environment: node`, while the root vitest uses jsdom for the Next.js
|
||||
# app), the npm package as it is built, the draw.io file list, and the
|
||||
# canvas shell in a browser.
|
||||
mcp-shell:
|
||||
name: MCP Server & Shell
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
# HEAD^1 is the base branch for the version bump reminder below
|
||||
fetch-depth: 2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: |
|
||||
package-lock.json
|
||||
packages/mcp-server/package-lock.json
|
||||
|
||||
# The shell is bundled from the web app's components with the root's
|
||||
# esbuild, Tailwind and React; Playwright comes from the root too
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install MCP server dependencies
|
||||
run: npm --prefix packages/mcp-server ci
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
id: playwright-cache
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
|
||||
|
||||
- name: Install Playwright browsers
|
||||
if: steps.playwright-cache.outputs.cache-hit != 'true'
|
||||
run: npx playwright install chromium --with-deps
|
||||
|
||||
- name: Install Playwright deps (cached)
|
||||
if: steps.playwright-cache.outputs.cache-hit == 'true'
|
||||
run: npx playwright install-deps chromium
|
||||
|
||||
- name: Run MCP server unit tests
|
||||
run: npm --prefix packages/mcp-server test
|
||||
|
||||
# Tests run from src/, so check the built npm package separately
|
||||
# Tests run from src/, so check the built npm package separately. The
|
||||
# build downloads the pinned draw.war and bundles a trimmed draw.io.
|
||||
- name: Build MCP server and check package contents
|
||||
run: npm --prefix packages/mcp-server run build && npm --prefix packages/mcp-server run check-package
|
||||
|
||||
# The trimmed draw.io is cut from this list; the guard drives the full
|
||||
# copy (public/drawio) in Chromium and fails when the editor requests a
|
||||
# file the list does not have
|
||||
- name: Download the full draw.io
|
||||
run: node scripts/fetch-drawio.mjs
|
||||
|
||||
- name: Check the MCP draw.io file list
|
||||
run: npm --prefix packages/mcp-server run check-drawio
|
||||
|
||||
# The canvas shell in a browser, from the package as npm installs it:
|
||||
# the packed tarball goes into an empty directory, its dist/index.js is
|
||||
# started over stdio and headless Chromium opens the URL start_session
|
||||
# returns (packages/mcp-server/tests/e2e)
|
||||
- name: Run the MCP shell E2E tests on the packed tarball
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/mcp-pack" "$RUNNER_TEMP/mcp-install"
|
||||
npm pack ./packages/mcp-server --pack-destination "$RUNNER_TEMP/mcp-pack"
|
||||
npm --prefix "$RUNNER_TEMP/mcp-install" install "$RUNNER_TEMP"/mcp-pack/*.tgz
|
||||
MCP_SERVER_ENTRY="$RUNNER_TEMP/mcp-install/node_modules/@next-ai-drawio/mcp-server/dist/index.js" \
|
||||
npm --prefix packages/mcp-server run test:e2e
|
||||
env:
|
||||
CI: true
|
||||
|
||||
# The shell bundles the web app's canvas and the root's dependencies,
|
||||
# so a change under these paths (the ones publish-mcp.yml triggers on)
|
||||
# reaches users with the next MCP release, and publish-mcp.yml only
|
||||
# publishes a new version number
|
||||
- name: Remind to bump the MCP version when bundled code changed
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
changed=$(git diff --name-only HEAD^1 HEAD -- components contexts hooks lib stores app/globals.css package-lock.json scripts packages/mcp-server)
|
||||
base_version=$(git show HEAD^1:packages/mcp-server/package.json | node -p "JSON.parse(require('fs').readFileSync(0, 'utf8')).version")
|
||||
head_version=$(node -p "require('./packages/mcp-server/package.json').version")
|
||||
if [ -n "$changed" ] && [ "$base_version" = "$head_version" ]; then
|
||||
echo "::warning::Code bundled into the MCP server changed without a version bump in packages/mcp-server/package.json (still ${head_version}). Bump it if the change should be published."
|
||||
fi
|
||||
|
||||
- name: Upload test results
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report-mcp-shell
|
||||
path: packages/mcp-server/test-results/
|
||||
retention-days: 7
|
||||
|
||||
e2e:
|
||||
# Six jobs at once, each with a sixth of the tests and one worker: the
|
||||
# same conditions per test, a fraction of the time
|
||||
@@ -57,7 +151,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "24"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Issues labelled "wait for confrim" are waiting for the reporter. After 15
|
||||
# days without activity the issue gets a reminder and the "no response"
|
||||
# label; after 15 more days it is closed. A reply from the reporter removes
|
||||
# both labels, so the issue shows up as needing the maintainer again.
|
||||
name: Wait for confirmation
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 3 * * *"
|
||||
workflow_dispatch:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
remind-and-close:
|
||||
if: github.event_name != 'issue_comment'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
only-issue-labels: "wait for confrim"
|
||||
days-before-issue-stale: 15
|
||||
days-before-issue-close: 15
|
||||
days-before-pr-stale: -1
|
||||
days-before-pr-close: -1
|
||||
stale-issue-label: "no response"
|
||||
stale-issue-message: >-
|
||||
Still there? We asked for more information 15 days ago. A reply
|
||||
would help; if we hear nothing in another 15 days this issue will
|
||||
be closed. It can be reopened any time.
|
||||
close-issue-message: >-
|
||||
No reply in 30 days, so this issue is closed for now. If the
|
||||
problem is still there, reply or reopen it.
|
||||
close-issue-reason: not_planned
|
||||
remove-stale-when-updated: true
|
||||
|
||||
reporter-replied:
|
||||
if: >-
|
||||
github.event_name == 'issue_comment' &&
|
||||
contains(github.event.issue.labels.*.name, 'wait for confrim') &&
|
||||
github.event.comment.user.type != 'Bot' &&
|
||||
!contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.comment.author_association)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: The reporter answered, so the issue is the maintainer's again
|
||||
run: >-
|
||||
gh issue edit "$NUMBER" --repo "$REPO"
|
||||
--remove-label "wait for confrim" --remove-label "no response"
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
NUMBER: ${{ github.event.issue.number }}
|
||||
REPO: ${{ github.repository }}
|
||||
@@ -16,6 +16,8 @@ packages/*/dist
|
||||
/coverage
|
||||
/playwright-report/
|
||||
/test-results/
|
||||
packages/*/playwright-report/
|
||||
packages/*/test-results/
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
|
||||
@@ -1,121 +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.)
|
||||
- **Versions and Undo**: Every AI change shows up in the chat as a version with a thumbnail. Compare it with the canvas, restore it, or undo it; Ctrl+Z on the canvas also takes back an AI change in one step. Shapes the AI just changed are highlighted.
|
||||
- **Ask About a Selection**: Select shapes on the canvas and ask the AI to change just those.
|
||||
- **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
|
||||
{
|
||||
@@ -128,165 +105,64 @@ 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)
|
||||
- The preview is the same canvas as the web app: the AI's changes are outlined, one Ctrl+Z takes them back, and the AI can read the shapes you select
|
||||
- The draw.io editor ships inside the package, so after install the preview works offline (`DRAWIO_BASE_URL` points it at an external draw.io instead)
|
||||
- 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
|
||||
- Ask the AI to undo, and keep your own drawing rules in `~/.next-ai-drawio/instructions.md`
|
||||
|
||||
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
|
||||
- **draw.io**: The editor runs from a copy bundled into `public/drawio` (downloaded by `npm run dev` / `npm run build`), so the app can drive it directly
|
||||
|
||||
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>
|
||||
|
||||
@@ -1,405 +0,0 @@
|
||||
import type { Metadata } from "next"
|
||||
import Link from "next/link"
|
||||
import { FaGithub } from "react-icons/fa"
|
||||
import Image from "@/components/image-with-basepath"
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "关于 - Next AI Draw.io",
|
||||
description:
|
||||
"AI驱动的图表创建工具 - 对话、绘制、可视化。使用自然语言创建AWS、GCP和Azure架构图。",
|
||||
keywords: ["AI图表", "draw.io", "AWS架构", "GCP图表", "Azure图表", "LLM"],
|
||||
}
|
||||
|
||||
export default function AboutCN() {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* Navigation */}
|
||||
<header className="bg-white border-b border-gray-200">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-xl font-bold text-gray-900 hover:text-gray-700"
|
||||
>
|
||||
Next AI Draw.io
|
||||
</Link>
|
||||
<nav className="flex items-center gap-6 text-sm">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
编辑器
|
||||
</Link>
|
||||
<Link
|
||||
href="/about/cn"
|
||||
className="text-blue-600 font-semibold"
|
||||
>
|
||||
关于
|
||||
</Link>
|
||||
<a
|
||||
href="https://github.com/DayuanJiang/next-ai-draw-io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
aria-label="在GitHub上查看"
|
||||
>
|
||||
<FaGithub className="w-5 h-5" />
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
|
||||
<article className="prose prose-lg max-w-none">
|
||||
{/* Title */}
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-4xl font-bold text-gray-900 mb-2">
|
||||
Next AI Draw.io
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 font-medium">
|
||||
AI驱动的图表创建工具 - 对话、绘制、可视化
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">
|
||||
<div className="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">
|
||||
使用自己的 API Key
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-2 max-w-md mx-auto">
|
||||
您也可以使用自己的 API
|
||||
Key,支持多种服务商。点击聊天面板中的设置图标即可配置。
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
您的 Key
|
||||
仅保存在浏览器本地,不会被存储在服务器上。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-700">
|
||||
一个集成了AI功能的Next.js网页应用,与draw.io图表无缝结合。通过自然语言命令和AI辅助可视化来创建、修改和增强图表。
|
||||
</p>
|
||||
|
||||
{/* Features */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
功能特性
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-2">
|
||||
<li>
|
||||
<strong>LLM驱动的图表创建</strong>
|
||||
:利用大语言模型通过自然语言命令直接创建和操作draw.io图表
|
||||
</li>
|
||||
<li>
|
||||
<strong>基于图像的图表复制</strong>
|
||||
:上传现有图表或图像,让AI自动复制和增强
|
||||
</li>
|
||||
<li>
|
||||
<strong>版本与撤销</strong>
|
||||
:AI
|
||||
的每次修改都会成为聊天里的一个版本,可以对比、恢复或撤销;在画布上按
|
||||
Ctrl+Z 也能撤回
|
||||
</li>
|
||||
<li>
|
||||
<strong>交互式聊天界面</strong>
|
||||
:与AI实时对话来完善您的图表
|
||||
</li>
|
||||
<li>
|
||||
<strong>AWS架构图支持</strong>
|
||||
:专门支持生成AWS架构图
|
||||
</li>
|
||||
<li>
|
||||
<strong>动画连接器</strong>
|
||||
:在图表元素之间创建动态动画连接器,实现更好的可视化效果
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
{/* Examples */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
示例
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-6">
|
||||
以下是一些示例提示词及其生成的图表:
|
||||
</p>
|
||||
|
||||
<div className="space-y-8">
|
||||
{/* ResNet50 Architecture */}
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
ResNet50模型架构动画
|
||||
</h3>
|
||||
<p className="text-gray-600 mb-4">
|
||||
<strong>Prompt:</strong> Give me an{" "}
|
||||
<strong>animated</strong> architecture diagram
|
||||
of the ResNet50 model.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 inline-block">
|
||||
<Image
|
||||
src="/resnet50.svg"
|
||||
alt="ResNet50模型架构图"
|
||||
width={480}
|
||||
height={360}
|
||||
className="mx-auto"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Diagram Grid */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
RAG技术图
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate a RAG
|
||||
architecture diagram for{" "}
|
||||
<strong>chat application</strong>. Use
|
||||
connected diagram for data ingestion
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/rag_prod.svg"
|
||||
alt="RAG架构图"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
React和AWS认证流程
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate
|
||||
authentication process using React with{" "}
|
||||
<strong>AWS</strong>. Use Serverless
|
||||
architecture.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/auth.svg"
|
||||
alt="认证架构图"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
敏捷Scrum流程
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate agile
|
||||
scrum workflow diagram for software
|
||||
development team.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/agile_scrum.svg"
|
||||
alt="敏捷Scrum流程图"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
开放式创新
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Create
|
||||
visualization of Henry Chesbrough's
|
||||
Open Innovation model.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/inno.svg"
|
||||
alt="开放式创新图"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* How It Works */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
工作原理
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4">本应用使用以下技术:</p>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-2">
|
||||
<li>
|
||||
<strong>Next.js</strong>:用于前端框架和路由
|
||||
</li>
|
||||
<li>
|
||||
<strong>Vercel AI SDK</strong>(<code>ai</code> +{" "}
|
||||
<code>@ai-sdk/*</code>
|
||||
):用于流式AI响应和多提供商支持
|
||||
</li>
|
||||
<li>
|
||||
<strong>draw.io</strong>
|
||||
:内置在应用里的编辑器,应用可以直接控制它
|
||||
</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
图表以XML格式表示,可在draw.io中渲染。AI处理您的命令并相应地生成或修改此XML。
|
||||
</p>
|
||||
|
||||
{/* Multi-Provider Support */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
多提供商支持
|
||||
</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>AWS Bedrock(默认)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI兼容API(通过{" "}
|
||||
<code>OPENAI_BASE_URL</code>)
|
||||
</li>
|
||||
<li>Anthropic</li>
|
||||
<li>Google AI</li>
|
||||
<li>Google Vertex AI</li>
|
||||
<li>Azure OpenAI</li>
|
||||
<li>Ollama</li>
|
||||
<li>OpenRouter</li>
|
||||
<li>DeepSeek</li>
|
||||
<li>SiliconFlow</li>
|
||||
<li>ModelScope</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
注意:<code>claude-sonnet-4-5</code>{" "}
|
||||
已在带有AWS标志的draw.io图表上进行训练,因此如果您想创建AWS架构图,这是最佳选择。
|
||||
</p>
|
||||
|
||||
{/* Support */}
|
||||
<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
|
||||
href="https://github.com/sponsors/DayuanJiang"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
赞助
|
||||
</a>{" "}
|
||||
来帮助托管在线演示站点!
|
||||
</p>
|
||||
<p className="text-gray-700 mt-2">
|
||||
如需支持或咨询,请在{" "}
|
||||
<a
|
||||
href="https://github.com/DayuanJiang/next-ai-draw-io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
GitHub仓库
|
||||
</a>{" "}
|
||||
上提交issue或联系:me[at]jiang.jp
|
||||
</p>
|
||||
|
||||
{/* CTA */}
|
||||
<div className="mt-12 text-center">
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-block bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
打开编辑器
|
||||
</Link>
|
||||
</div>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="bg-white border-t border-gray-200 mt-16">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<p className="text-center text-gray-600 text-sm">
|
||||
Next AI Draw.io - 开源AI驱动的图表生成器
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,402 +0,0 @@
|
||||
import type { Metadata } from "next"
|
||||
import Link from "next/link"
|
||||
import { FaGithub } from "react-icons/fa"
|
||||
import Image from "@/components/image-with-basepath"
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "概要 - Next AI Draw.io",
|
||||
description:
|
||||
"AI搭載のダイアグラム作成ツール - チャット、描画、可視化。自然言語でAWS、GCP、Azureアーキテクチャ図を作成。",
|
||||
keywords: [
|
||||
"AIダイアグラム",
|
||||
"draw.io",
|
||||
"AWSアーキテクチャ",
|
||||
"GCPダイアグラム",
|
||||
"Azureダイアグラム",
|
||||
"LLM",
|
||||
],
|
||||
}
|
||||
|
||||
export default function AboutJA() {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* Navigation */}
|
||||
<header className="bg-white border-b border-gray-200">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-xl font-bold text-gray-900 hover:text-gray-700"
|
||||
>
|
||||
Next AI Draw.io
|
||||
</Link>
|
||||
<nav className="flex items-center gap-6 text-sm">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
エディタ
|
||||
</Link>
|
||||
<Link
|
||||
href="/about/ja"
|
||||
className="text-blue-600 font-semibold"
|
||||
>
|
||||
概要
|
||||
</Link>
|
||||
<a
|
||||
href="https://github.com/DayuanJiang/next-ai-draw-io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
aria-label="GitHubで見る"
|
||||
>
|
||||
<FaGithub className="w-5 h-5" />
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
|
||||
<article className="prose prose-lg max-w-none">
|
||||
{/* Title */}
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-4xl font-bold text-gray-900 mb-2">
|
||||
Next AI Draw.io
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 font-medium">
|
||||
AI搭載のダイアグラム作成ツール -
|
||||
チャット、描画、可視化
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">
|
||||
<div className="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">
|
||||
自分のAPIキーを使用
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-2 max-w-md mx-auto">
|
||||
お好みのプロバイダーで自分のAPIキーを使用することもできます。チャットパネルの設定アイコンをクリックして設定してください。
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
キーはブラウザのローカルに保存され、サーバーには保存されません。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-700">
|
||||
AI機能とdraw.ioダイアグラムを統合したNext.jsウェブアプリケーションです。自然言語コマンドとAI支援の可視化により、ダイアグラムを作成、修正、強化できます。
|
||||
</p>
|
||||
|
||||
{/* Features */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
機能
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-2">
|
||||
<li>
|
||||
<strong>LLM搭載のダイアグラム作成</strong>
|
||||
:大規模言語モデルを活用して、自然言語コマンドで直接draw.ioダイアグラムを作成・操作
|
||||
</li>
|
||||
<li>
|
||||
<strong>画像ベースのダイアグラム複製</strong>
|
||||
:既存のダイアグラムや画像をアップロードし、AIが自動的に複製・強化
|
||||
</li>
|
||||
<li>
|
||||
<strong>バージョンと取り消し</strong>
|
||||
:AI
|
||||
の変更はそれぞれチャット内のバージョンになり、比較・復元・取り消しができます。キャンバスで
|
||||
Ctrl+Z を押しても元に戻せます
|
||||
</li>
|
||||
<li>
|
||||
<strong>
|
||||
インタラクティブなチャットインターフェース
|
||||
</strong>
|
||||
:AIとリアルタイムでコミュニケーションしてダイアグラムを改善
|
||||
</li>
|
||||
<li>
|
||||
<strong>
|
||||
AWSアーキテクチャダイアグラムサポート
|
||||
</strong>
|
||||
:AWSアーキテクチャダイアグラムの生成を専門的にサポート
|
||||
</li>
|
||||
<li>
|
||||
<strong>アニメーションコネクタ</strong>
|
||||
:より良い可視化のためにダイアグラム要素間に動的でアニメーション化されたコネクタを作成
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
{/* Examples */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
例
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-6">
|
||||
以下はいくつかのプロンプト例と生成されたダイアグラムです:
|
||||
</p>
|
||||
|
||||
<div className="space-y-8">
|
||||
{/* ResNet50 Architecture */}
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
ResNet50モデルアーキテクチャアニメーション
|
||||
</h3>
|
||||
<p className="text-gray-600 mb-4">
|
||||
<strong>Prompt:</strong> Give me an{" "}
|
||||
<strong>animated</strong> architecture diagram
|
||||
of the ResNet50 model.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 inline-block">
|
||||
<Image
|
||||
src="/resnet50.svg"
|
||||
alt="ResNet50モデルアーキテクチャ図"
|
||||
width={480}
|
||||
height={360}
|
||||
className="mx-auto"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Diagram Grid */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
RAG技術ダイアグラム
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate a RAG
|
||||
architecture diagram for{" "}
|
||||
<strong>chat application</strong>. Use
|
||||
connected diagram for data ingestion
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/rag_prod.svg"
|
||||
alt="RAGアーキテクチャ図"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
ReactとAWSによる認証
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate
|
||||
authentication process using React with{" "}
|
||||
<strong>AWS</strong>. Use Serverless
|
||||
architecture.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/auth.svg"
|
||||
alt="認証アーキテクチャ図"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
アジャイルスクラムプロセス
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate agile
|
||||
scrum workflow diagram for software
|
||||
development team.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/agile_scrum.svg"
|
||||
alt="アジャイルスクラム図"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
オープンイノベーション
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Create
|
||||
visualization of Henry Chesbrough's
|
||||
Open Innovation model.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/inno.svg"
|
||||
alt="オープンイノベーション図"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* How It Works */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
仕組み
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4">
|
||||
本アプリケーションは以下の技術を使用しています:
|
||||
</p>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-2">
|
||||
<li>
|
||||
<strong>Next.js</strong>
|
||||
:フロントエンドフレームワークとルーティング
|
||||
</li>
|
||||
<li>
|
||||
<strong>Vercel AI SDK</strong>(<code>ai</code> +{" "}
|
||||
<code>@ai-sdk/*</code>
|
||||
):ストリーミングAIレスポンスとマルチプロバイダーサポート
|
||||
</li>
|
||||
<li>
|
||||
<strong>draw.io</strong>
|
||||
:アプリに同梱されたエディター。アプリから直接操作できます
|
||||
</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
ダイアグラムはdraw.ioでレンダリングできるXMLとして表現されます。AIがコマンドを処理し、それに応じてこのXMLを生成または変更します。
|
||||
</p>
|
||||
|
||||
{/* Multi-Provider Support */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
マルチプロバイダーサポート
|
||||
</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>AWS Bedrock(デフォルト)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI互換API(<code>OPENAI_BASE_URL</code>
|
||||
経由)
|
||||
</li>
|
||||
<li>Anthropic</li>
|
||||
<li>Google AI</li>
|
||||
<li>Google Vertex AI</li>
|
||||
<li>Azure OpenAI</li>
|
||||
<li>Ollama</li>
|
||||
<li>OpenRouter</li>
|
||||
<li>DeepSeek</li>
|
||||
<li>SiliconFlow</li>
|
||||
<li>ModelScope</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
注:<code>claude-sonnet-4-5</code>
|
||||
はAWSロゴ付きのdraw.ioダイアグラムで学習されているため、AWSアーキテクチャダイアグラムを作成したい場合は最適な選択です。
|
||||
</p>
|
||||
|
||||
{/* Support */}
|
||||
<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
|
||||
href="https://github.com/sponsors/DayuanJiang"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
スポンサー
|
||||
</a>{" "}
|
||||
をご検討ください!
|
||||
</p>
|
||||
<p className="text-gray-700 mt-2">
|
||||
サポートやお問い合わせについては、{" "}
|
||||
<a
|
||||
href="https://github.com/DayuanJiang/next-ai-draw-io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
GitHubリポジトリ
|
||||
</a>{" "}
|
||||
でissueを開くか、ご連絡ください:me[at]jiang.jp
|
||||
</p>
|
||||
|
||||
{/* CTA */}
|
||||
<div className="mt-12 text-center">
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-block bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
エディタを開く
|
||||
</Link>
|
||||
</div>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="bg-white border-t border-gray-200 mt-16">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<p className="text-center text-gray-600 text-sm">
|
||||
Next AI Draw.io -
|
||||
オープンソースAI搭載ダイアグラムジェネレーター
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+468
-225
@@ -1,9 +1,52 @@
|
||||
import type { Metadata } from "next"
|
||||
import Link from "next/link"
|
||||
import { FaGithub } from "react-icons/fa"
|
||||
import type { ReactNode } from "react"
|
||||
import { GitHubIcon } from "@/components/icons/github"
|
||||
import Image from "@/components/image-with-basepath"
|
||||
import type { Locale } from "@/lib/i18n/config"
|
||||
import { hasLocale } from "@/lib/i18n/dictionaries"
|
||||
|
||||
export const metadata: Metadata = {
|
||||
type ExampleId = "resnet50" | "rag" | "auth" | "scrum" | "inno"
|
||||
|
||||
type AboutTexts = {
|
||||
title: string
|
||||
description: string
|
||||
keywords: string[]
|
||||
nav: { editor: string; about: string; github: string }
|
||||
tagline: string
|
||||
byok: { title: string; body: string; note: string }
|
||||
intro: string
|
||||
// Punctuation differs between Latin and CJK text
|
||||
colon: string
|
||||
parenOpen: string
|
||||
parenClose: string
|
||||
featuresHeading: string
|
||||
features: { title: string; text: string }[]
|
||||
examplesHeading: string
|
||||
examplesIntro: string
|
||||
examples: Record<ExampleId, { title: string; alt: string }>
|
||||
howHeading: string
|
||||
howIntro: string
|
||||
tech: { nextjs: string; aiSdk: string; drawio: string }
|
||||
howOutro: string
|
||||
providersHeading: string
|
||||
doubao: string
|
||||
bedrock: string
|
||||
// Text around the OPENAI_BASE_URL code span
|
||||
openai: { before: string; after: string }
|
||||
// Text around the claude-sonnet-4-5 code span
|
||||
modelNote: { before: string; after: string }
|
||||
supportHeading: string
|
||||
// Text around the sponsor link
|
||||
sponsor: { before: string; link: string; after: string }
|
||||
// Text around the GitHub repository link
|
||||
contact: { before: string; link: string; after: string }
|
||||
openEditor: string
|
||||
footer: string
|
||||
}
|
||||
|
||||
const texts: Record<"en" | "zh" | "ja", AboutTexts> = {
|
||||
en: {
|
||||
title: "About - Next AI Draw.io",
|
||||
description:
|
||||
"AI-Powered Diagram Creation Tool - Chat, Draw, Visualize. Create AWS, GCP, and Azure architecture diagrams with natural language.",
|
||||
@@ -15,9 +58,363 @@ export const metadata: Metadata = {
|
||||
"Azure diagram",
|
||||
"LLM",
|
||||
],
|
||||
nav: { editor: "Editor", about: "About", github: "View on GitHub" },
|
||||
tagline: "AI-Powered Diagram Creation Tool - Chat, Draw, Visualize",
|
||||
byok: {
|
||||
title: "Bring Your Own API Key",
|
||||
body: "You can also use your own API key with any supported provider. Click the Settings icon in the chat panel to configure your provider and API key.",
|
||||
note: "Your key is stored locally in your browser and is never stored on the server.",
|
||||
},
|
||||
intro: "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.",
|
||||
colon: ": ",
|
||||
parenOpen: " (",
|
||||
parenClose: ")",
|
||||
featuresHeading: "Features",
|
||||
features: [
|
||||
{
|
||||
title: "LLM-Powered Diagram Creation",
|
||||
text: "Leverage Large Language Models to create and manipulate draw.io diagrams directly through natural language commands",
|
||||
},
|
||||
{
|
||||
title: "Image-Based Diagram Replication",
|
||||
text: "Upload existing diagrams or images and have the AI replicate and enhance them automatically",
|
||||
},
|
||||
{
|
||||
title: "Versions and Undo",
|
||||
text: "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",
|
||||
},
|
||||
{
|
||||
title: "Interactive Chat Interface",
|
||||
text: "Communicate with AI to refine your diagrams in real-time",
|
||||
},
|
||||
{
|
||||
title: "AWS Architecture Diagram Support",
|
||||
text: "Specialized support for generating AWS architecture diagrams",
|
||||
},
|
||||
{
|
||||
title: "Animated Connectors",
|
||||
text: "Create dynamic and animated connectors between diagram elements for better visualization",
|
||||
},
|
||||
],
|
||||
examplesHeading: "Examples",
|
||||
examplesIntro:
|
||||
"Here are some example prompts and their generated diagrams:",
|
||||
examples: {
|
||||
resnet50: {
|
||||
title: "Animated ResNet50 Model Architecture",
|
||||
alt: "Architecture diagram for ResNet50 model",
|
||||
},
|
||||
rag: {
|
||||
title: "RAG Technique Diagram",
|
||||
alt: "RAG Architecture Diagram",
|
||||
},
|
||||
auth: {
|
||||
title: "Authentication using React and AWS",
|
||||
alt: "Authentication Architecture Diagram",
|
||||
},
|
||||
scrum: { title: "Agile Scrum Process", alt: "Agile Scrum Diagram" },
|
||||
inno: { title: "Open Innovation", alt: "Open Innovation Diagram" },
|
||||
},
|
||||
howHeading: "How It Works",
|
||||
howIntro: "The application uses the following technologies:",
|
||||
tech: {
|
||||
nextjs: "For the frontend framework and routing",
|
||||
aiSdk: "For streaming AI responses and multi-provider support",
|
||||
drawio: "The editor, bundled with the app so it can be driven directly",
|
||||
},
|
||||
howOutro:
|
||||
"Diagrams are represented as XML that can be rendered in draw.io. The AI processes your commands and generates or modifies this XML accordingly.",
|
||||
providersHeading: "Multi-Provider Support",
|
||||
doubao: "ByteDance Doubao",
|
||||
bedrock: "AWS Bedrock (default)",
|
||||
openai: { before: "OpenAI / OpenAI-compatible APIs (via ", after: ")" },
|
||||
modelNote: {
|
||||
before: "Note that ",
|
||||
after: " has trained on draw.io diagrams with AWS logos, so if you want to create AWS architecture diagrams, this is the best choice.",
|
||||
},
|
||||
supportHeading: "Support & Contact",
|
||||
sponsor: {
|
||||
before: "If you find this project useful, please consider",
|
||||
link: "sponsoring",
|
||||
after: "to help host the live demo site!",
|
||||
},
|
||||
contact: {
|
||||
before: "For support or inquiries, please open an issue on the",
|
||||
link: "GitHub repository",
|
||||
after: "or contact: me[at]jiang.jp",
|
||||
},
|
||||
openEditor: "Open Editor",
|
||||
footer: "Next AI Draw.io - Open Source AI-Powered Diagram Generator",
|
||||
},
|
||||
zh: {
|
||||
title: "关于 - Next AI Draw.io",
|
||||
description:
|
||||
"AI驱动的图表创建工具 - 对话、绘制、可视化。使用自然语言创建AWS、GCP和Azure架构图。",
|
||||
keywords: [
|
||||
"AI图表",
|
||||
"draw.io",
|
||||
"AWS架构",
|
||||
"GCP图表",
|
||||
"Azure图表",
|
||||
"LLM",
|
||||
],
|
||||
nav: { editor: "编辑器", about: "关于", github: "在GitHub上查看" },
|
||||
tagline: "AI驱动的图表创建工具 - 对话、绘制、可视化",
|
||||
byok: {
|
||||
title: "使用自己的 API Key",
|
||||
body: "您也可以使用自己的 API Key,支持多种服务商。点击聊天面板中的设置图标即可配置。",
|
||||
note: "您的 Key 仅保存在浏览器本地,不会被存储在服务器上。",
|
||||
},
|
||||
intro: "一个集成了AI功能的Next.js网页应用,与draw.io图表无缝结合。通过自然语言命令和AI辅助可视化来创建、修改和增强图表。",
|
||||
colon: ":",
|
||||
parenOpen: "(",
|
||||
parenClose: ")",
|
||||
featuresHeading: "功能特性",
|
||||
features: [
|
||||
{
|
||||
title: "LLM驱动的图表创建",
|
||||
text: "利用大语言模型通过自然语言命令直接创建和操作draw.io图表",
|
||||
},
|
||||
{
|
||||
title: "基于图像的图表复制",
|
||||
text: "上传现有图表或图像,让AI自动复制和增强",
|
||||
},
|
||||
{
|
||||
title: "版本与撤销",
|
||||
text: "AI 的每次修改都会成为聊天里的一个版本,可以对比、恢复或撤销;在画布上按 Ctrl+Z 也能撤回",
|
||||
},
|
||||
{
|
||||
title: "交互式聊天界面",
|
||||
text: "与AI实时对话来完善您的图表",
|
||||
},
|
||||
{ title: "AWS架构图支持", text: "专门支持生成AWS架构图" },
|
||||
{
|
||||
title: "动画连接器",
|
||||
text: "在图表元素之间创建动态动画连接器,实现更好的可视化效果",
|
||||
},
|
||||
],
|
||||
examplesHeading: "示例",
|
||||
examplesIntro: "以下是一些示例提示词及其生成的图表:",
|
||||
examples: {
|
||||
resnet50: {
|
||||
title: "ResNet50模型架构动画",
|
||||
alt: "ResNet50模型架构图",
|
||||
},
|
||||
rag: { title: "RAG技术图", alt: "RAG架构图" },
|
||||
auth: { title: "React和AWS认证流程", alt: "认证架构图" },
|
||||
scrum: { title: "敏捷Scrum流程", alt: "敏捷Scrum流程图" },
|
||||
inno: { title: "开放式创新", alt: "开放式创新图" },
|
||||
},
|
||||
howHeading: "工作原理",
|
||||
howIntro: "本应用使用以下技术:",
|
||||
tech: {
|
||||
nextjs: "用于前端框架和路由",
|
||||
aiSdk: "用于流式AI响应和多提供商支持",
|
||||
drawio: "内置在应用里的编辑器,应用可以直接控制它",
|
||||
},
|
||||
howOutro:
|
||||
"图表以XML格式表示,可在draw.io中渲染。AI处理您的命令并相应地生成或修改此XML。",
|
||||
providersHeading: "多提供商支持",
|
||||
doubao: "字节跳动豆包",
|
||||
bedrock: "AWS Bedrock(默认)",
|
||||
openai: { before: "OpenAI / OpenAI兼容API(通过 ", after: ")" },
|
||||
modelNote: {
|
||||
before: "注意:",
|
||||
after: " 已在带有AWS标志的draw.io图表上进行训练,因此如果您想创建AWS架构图,这是最佳选择。",
|
||||
},
|
||||
supportHeading: "支持与联系",
|
||||
sponsor: {
|
||||
before: "如果您觉得这个项目有用,请考虑",
|
||||
link: "赞助",
|
||||
after: "来帮助托管在线演示站点!",
|
||||
},
|
||||
contact: {
|
||||
before: "如需支持或咨询,请在",
|
||||
link: "GitHub仓库",
|
||||
after: "上提交issue或联系:me[at]jiang.jp",
|
||||
},
|
||||
openEditor: "打开编辑器",
|
||||
footer: "Next AI Draw.io - 开源AI驱动的图表生成器",
|
||||
},
|
||||
ja: {
|
||||
title: "概要 - Next AI Draw.io",
|
||||
description:
|
||||
"AI搭載のダイアグラム作成ツール - チャット、描画、可視化。自然言語でAWS、GCP、Azureアーキテクチャ図を作成。",
|
||||
keywords: [
|
||||
"AIダイアグラム",
|
||||
"draw.io",
|
||||
"AWSアーキテクチャ",
|
||||
"GCPダイアグラム",
|
||||
"Azureダイアグラム",
|
||||
"LLM",
|
||||
],
|
||||
nav: { editor: "エディタ", about: "概要", github: "GitHubで見る" },
|
||||
tagline: "AI搭載のダイアグラム作成ツール - チャット、描画、可視化",
|
||||
byok: {
|
||||
title: "自分のAPIキーを使用",
|
||||
body: "お好みのプロバイダーで自分のAPIキーを使用することもできます。チャットパネルの設定アイコンをクリックして設定してください。",
|
||||
note: "キーはブラウザのローカルに保存され、サーバーには保存されません。",
|
||||
},
|
||||
intro: "AI機能とdraw.ioダイアグラムを統合したNext.jsウェブアプリケーションです。自然言語コマンドとAI支援の可視化により、ダイアグラムを作成、修正、強化できます。",
|
||||
colon: ":",
|
||||
parenOpen: "(",
|
||||
parenClose: ")",
|
||||
featuresHeading: "機能",
|
||||
features: [
|
||||
{
|
||||
title: "LLM搭載のダイアグラム作成",
|
||||
text: "大規模言語モデルを活用して、自然言語コマンドで直接draw.ioダイアグラムを作成・操作",
|
||||
},
|
||||
{
|
||||
title: "画像ベースのダイアグラム複製",
|
||||
text: "既存のダイアグラムや画像をアップロードし、AIが自動的に複製・強化",
|
||||
},
|
||||
{
|
||||
title: "バージョンと取り消し",
|
||||
text: "AI の変更はそれぞれチャット内のバージョンになり、比較・復元・取り消しができます。キャンバスで Ctrl+Z を押しても元に戻せます",
|
||||
},
|
||||
{
|
||||
title: "インタラクティブなチャットインターフェース",
|
||||
text: "AIとリアルタイムでコミュニケーションしてダイアグラムを改善",
|
||||
},
|
||||
{
|
||||
title: "AWSアーキテクチャダイアグラムサポート",
|
||||
text: "AWSアーキテクチャダイアグラムの生成を専門的にサポート",
|
||||
},
|
||||
{
|
||||
title: "アニメーションコネクタ",
|
||||
text: "より良い可視化のためにダイアグラム要素間に動的でアニメーション化されたコネクタを作成",
|
||||
},
|
||||
],
|
||||
examplesHeading: "例",
|
||||
examplesIntro:
|
||||
"以下はいくつかのプロンプト例と生成されたダイアグラムです:",
|
||||
examples: {
|
||||
resnet50: {
|
||||
title: "ResNet50モデルアーキテクチャアニメーション",
|
||||
alt: "ResNet50モデルアーキテクチャ図",
|
||||
},
|
||||
rag: { title: "RAG技術ダイアグラム", alt: "RAGアーキテクチャ図" },
|
||||
auth: {
|
||||
title: "ReactとAWSによる認証",
|
||||
alt: "認証アーキテクチャ図",
|
||||
},
|
||||
scrum: {
|
||||
title: "アジャイルスクラムプロセス",
|
||||
alt: "アジャイルスクラム図",
|
||||
},
|
||||
inno: {
|
||||
title: "オープンイノベーション",
|
||||
alt: "オープンイノベーション図",
|
||||
},
|
||||
},
|
||||
howHeading: "仕組み",
|
||||
howIntro: "本アプリケーションは以下の技術を使用しています:",
|
||||
tech: {
|
||||
nextjs: "フロントエンドフレームワークとルーティング",
|
||||
aiSdk: "ストリーミングAIレスポンスとマルチプロバイダーサポート",
|
||||
drawio: "アプリに同梱されたエディター。アプリから直接操作できます",
|
||||
},
|
||||
howOutro:
|
||||
"ダイアグラムはdraw.ioでレンダリングできるXMLとして表現されます。AIがコマンドを処理し、それに応じてこのXMLを生成または変更します。",
|
||||
providersHeading: "マルチプロバイダーサポート",
|
||||
doubao: "ByteDance Doubao",
|
||||
bedrock: "AWS Bedrock(デフォルト)",
|
||||
openai: { before: "OpenAI / OpenAI互換API(", after: "経由)" },
|
||||
modelNote: {
|
||||
before: "注:",
|
||||
after: "はAWSロゴ付きのdraw.ioダイアグラムで学習されているため、AWSアーキテクチャダイアグラムを作成したい場合は最適な選択です。",
|
||||
},
|
||||
supportHeading: "サポート&お問い合わせ",
|
||||
sponsor: {
|
||||
before: "このプロジェクトが役に立ったら、ライブデモサイトのホスティングを支援するために",
|
||||
link: "スポンサー",
|
||||
after: "をご検討ください!",
|
||||
},
|
||||
contact: {
|
||||
before: "サポートやお問い合わせについては、",
|
||||
link: "GitHubリポジトリ",
|
||||
after: "でissueを開くか、ご連絡ください:me[at]jiang.jp",
|
||||
},
|
||||
openEditor: "エディタを開く",
|
||||
footer: "Next AI Draw.io - オープンソースAI搭載ダイアグラムジェネレーター",
|
||||
},
|
||||
}
|
||||
|
||||
export default function About() {
|
||||
// The example prompts stay in English in every language
|
||||
const examples: { id: ExampleId; src: string; prompt: ReactNode }[] = [
|
||||
{
|
||||
id: "resnet50",
|
||||
src: "/resnet50.svg",
|
||||
prompt: (
|
||||
<>
|
||||
Give me an <strong>animated</strong> architecture diagram of the
|
||||
ResNet50 model.
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "rag",
|
||||
src: "/rag_prod.svg",
|
||||
prompt: (
|
||||
<>
|
||||
Generate a RAG architecture diagram for{" "}
|
||||
<strong>chat application</strong>. Use connected diagram for
|
||||
data ingestion
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "auth",
|
||||
src: "/auth.svg",
|
||||
prompt: (
|
||||
<>
|
||||
Generate authentication process using React with{" "}
|
||||
<strong>AWS</strong>. Use Serverless architecture.
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "scrum",
|
||||
src: "/agile_scrum.svg",
|
||||
prompt: (
|
||||
<>
|
||||
Generate agile scrum workflow diagram for software development
|
||||
team.
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "inno",
|
||||
src: "/inno.svg",
|
||||
prompt: (
|
||||
<>
|
||||
Create visualization of Henry Chesbrough's Open Innovation
|
||||
model.
|
||||
</>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
// Traditional Chinese has no About text of its own and shows the Simplified one
|
||||
function textsFor(rawLang: string): AboutTexts {
|
||||
const lang: Locale = hasLocale(rawLang) ? rawLang : "en"
|
||||
return texts[lang === "zh-Hant" ? "zh" : lang]
|
||||
}
|
||||
|
||||
type Props = { params: Promise<{ lang: string }> }
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const { lang } = await params
|
||||
const t = textsFor(lang)
|
||||
return { title: t.title, description: t.description, keywords: t.keywords }
|
||||
}
|
||||
|
||||
export default async function About({ params }: Props) {
|
||||
const { lang } = await params
|
||||
const t = textsFor(lang)
|
||||
const [hero, ...grid] = examples
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* Navigation */}
|
||||
@@ -25,32 +422,32 @@ export default function About() {
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Link
|
||||
href="/"
|
||||
href={`/${lang}`}
|
||||
className="text-xl font-bold text-gray-900 hover:text-gray-700"
|
||||
>
|
||||
Next AI Draw.io
|
||||
</Link>
|
||||
<nav className="flex items-center gap-6 text-sm">
|
||||
<Link
|
||||
href="/"
|
||||
href={`/${lang}`}
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
Editor
|
||||
{t.nav.editor}
|
||||
</Link>
|
||||
<Link
|
||||
href="/about"
|
||||
href={`/${lang}/about`}
|
||||
className="text-blue-600 font-semibold"
|
||||
>
|
||||
About
|
||||
{t.nav.about}
|
||||
</Link>
|
||||
<a
|
||||
href="https://github.com/DayuanJiang/next-ai-draw-io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
aria-label="View on GitHub"
|
||||
aria-label={t.nav.github}
|
||||
>
|
||||
<FaGithub className="w-5 h-5" />
|
||||
<GitHubIcon className="w-5 h-5" />
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
@@ -66,136 +463,63 @@ export default function About() {
|
||||
Next AI Draw.io
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 font-medium">
|
||||
AI-Powered Diagram Creation Tool - Chat, Draw,
|
||||
Visualize
|
||||
{t.tagline}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="relative mb-8 rounded-2xl bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 p-[1px] shadow-lg">
|
||||
<div className="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">
|
||||
Bring Your Own API Key
|
||||
{t.byok.title}
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 mb-2 max-w-md mx-auto">
|
||||
You can also use your own API key with any
|
||||
supported provider. Click the Settings icon
|
||||
in the chat panel to configure your provider
|
||||
and API key.
|
||||
{t.byok.body}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
Your key is stored locally in your browser
|
||||
and is never stored on the server.
|
||||
{t.byok.note}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-700">
|
||||
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.
|
||||
</p>
|
||||
<p className="text-gray-700">{t.intro}</p>
|
||||
|
||||
{/* Features */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
Features
|
||||
{t.featuresHeading}
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-2">
|
||||
<li>
|
||||
<strong>LLM-Powered Diagram Creation</strong>:
|
||||
Leverage Large Language Models to create and
|
||||
manipulate draw.io diagrams directly through natural
|
||||
language commands
|
||||
</li>
|
||||
<li>
|
||||
<strong>Image-Based Diagram Replication</strong>:
|
||||
Upload existing diagrams or images and have the AI
|
||||
replicate and enhance them automatically
|
||||
</li>
|
||||
<li>
|
||||
<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>:
|
||||
Communicate with AI to refine your diagrams in
|
||||
real-time
|
||||
</li>
|
||||
<li>
|
||||
<strong>AWS Architecture Diagram Support</strong>:
|
||||
Specialized support for generating AWS architecture
|
||||
diagrams
|
||||
</li>
|
||||
<li>
|
||||
<strong>Animated Connectors</strong>: Create dynamic
|
||||
and animated connectors between diagram elements for
|
||||
better visualization
|
||||
{t.features.map((feature) => (
|
||||
<li key={feature.title}>
|
||||
<strong>{feature.title}</strong>
|
||||
{t.colon}
|
||||
{feature.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{/* Examples */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
Examples
|
||||
{t.examplesHeading}
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-6">
|
||||
Here are some example prompts and their generated
|
||||
diagrams:
|
||||
</p>
|
||||
<p className="text-gray-700 mb-6">{t.examplesIntro}</p>
|
||||
|
||||
<div className="space-y-8">
|
||||
{/* ResNet50 Architecture */}
|
||||
{/* First example on its own */}
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
Animated ResNet50 Model Architecture
|
||||
{t.examples[hero.id].title}
|
||||
</h3>
|
||||
<p className="text-gray-600 mb-4">
|
||||
<strong>Prompt:</strong> Give me an{" "}
|
||||
<strong>animated</strong> architecture diagram
|
||||
of the ResNet50 model.
|
||||
<strong>Prompt:</strong> {hero.prompt}
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 inline-block">
|
||||
<Image
|
||||
src="/resnet50.svg"
|
||||
alt="Architecture diagram for ResNet50 model"
|
||||
src={hero.src}
|
||||
alt={t.examples[hero.id].alt}
|
||||
width={480}
|
||||
height={360}
|
||||
className="mx-auto"
|
||||
@@ -205,134 +529,67 @@ export default function About() {
|
||||
|
||||
{/* Diagram Grid */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<div className="text-center">
|
||||
{grid.map((example) => (
|
||||
<div key={example.id} className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
RAG Technique Diagram
|
||||
{t.examples[example.id].title}
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate a RAG
|
||||
architecture diagram for{" "}
|
||||
<strong>chat application</strong>. Use
|
||||
connected diagram for data ingestion
|
||||
<strong>Prompt:</strong>{" "}
|
||||
{example.prompt}
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/rag_prod.svg"
|
||||
alt="RAG Architecture Diagram"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
Authentication using React and AWS
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate
|
||||
authentication process using React with{" "}
|
||||
<strong>AWS</strong>. Use Serverless
|
||||
architecture.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/auth.svg"
|
||||
alt="Authentication Architecture Diagram"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
Agile Scrum Process
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Generate agile
|
||||
scrum workflow diagram for software
|
||||
development team.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/agile_scrum.svg"
|
||||
alt="Agile Scrum Diagram"
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-2">
|
||||
Open Innovation
|
||||
</h3>
|
||||
<p className="text-gray-600 text-sm mb-4">
|
||||
<strong>Prompt:</strong> Create
|
||||
visualization of Henry Chesbrough's
|
||||
Open Innovation model.
|
||||
</p>
|
||||
<div className="bg-neutral-950 rounded-lg p-4 flex items-center justify-center w-full h-[400px]">
|
||||
<Image
|
||||
src="/inno.svg"
|
||||
alt="Open Innovation Diagram"
|
||||
src={example.src}
|
||||
alt={t.examples[example.id].alt}
|
||||
width={480}
|
||||
height={360}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* How It Works */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
How It Works
|
||||
{t.howHeading}
|
||||
</h2>
|
||||
<p className="text-gray-700 mb-4">
|
||||
The application uses the following technologies:
|
||||
</p>
|
||||
<p className="text-gray-700 mb-4">{t.howIntro}</p>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-2">
|
||||
<li>
|
||||
<strong>Next.js</strong>: For the frontend framework
|
||||
and routing
|
||||
<strong>Next.js</strong>
|
||||
{t.colon}
|
||||
{t.tech.nextjs}
|
||||
</li>
|
||||
<li>
|
||||
<strong>Vercel AI SDK</strong> (<code>ai</code> +{" "}
|
||||
<code>@ai-sdk/*</code>): For streaming AI responses
|
||||
and multi-provider support
|
||||
<strong>Vercel AI SDK</strong>
|
||||
{t.parenOpen}
|
||||
<code>ai</code> + <code>@ai-sdk/*</code>
|
||||
{t.parenClose}
|
||||
{t.colon}
|
||||
{t.tech.aiSdk}
|
||||
</li>
|
||||
<li>
|
||||
<strong>draw.io</strong>: The editor, bundled with
|
||||
the app so it can be driven directly
|
||||
<strong>draw.io</strong>
|
||||
{t.colon}
|
||||
{t.tech.drawio}
|
||||
</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
Diagrams are represented as XML that can be rendered in
|
||||
draw.io. The AI processes your commands and generates or
|
||||
modifies this XML accordingly.
|
||||
</p>
|
||||
<p className="text-gray-700 mt-4">{t.howOutro}</p>
|
||||
|
||||
{/* Multi-Provider Support */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
Multi-Provider Support
|
||||
{t.providersHeading}
|
||||
</h2>
|
||||
<ul className="list-disc pl-6 text-gray-700 space-y-1">
|
||||
<li>{t.doubao}</li>
|
||||
<li>{t.bedrock}</li>
|
||||
<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>AWS Bedrock (default)</li>
|
||||
<li>
|
||||
OpenAI / OpenAI-compatible APIs (via{" "}
|
||||
<code>OPENAI_BASE_URL</code>)
|
||||
{t.openai.before}
|
||||
<code>OPENAI_BASE_URL</code>
|
||||
{t.openai.after}
|
||||
</li>
|
||||
<li>Anthropic</li>
|
||||
<li>Google AI</li>
|
||||
@@ -345,60 +602,47 @@ export default function About() {
|
||||
<li>ModelScope</li>
|
||||
</ul>
|
||||
<p className="text-gray-700 mt-4">
|
||||
Note that <code>claude-sonnet-4-5</code> has trained on
|
||||
draw.io diagrams with AWS logos, so if you want to
|
||||
create AWS architecture diagrams, this is the best
|
||||
choice.
|
||||
{t.modelNote.before}
|
||||
<code>claude-sonnet-4-5</code>
|
||||
{t.modelNote.after}
|
||||
</p>
|
||||
|
||||
{/* Support */}
|
||||
<h2 className="text-2xl font-semibold text-gray-900 mt-10 mb-4">
|
||||
Support & Contact
|
||||
{t.supportHeading}
|
||||
</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{" "}
|
||||
{t.sponsor.before}{" "}
|
||||
<a
|
||||
href="https://github.com/sponsors/DayuanJiang"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
sponsoring
|
||||
{t.sponsor.link}
|
||||
</a>{" "}
|
||||
to help host the live demo site!
|
||||
{t.sponsor.after}
|
||||
</p>
|
||||
<p className="text-gray-700 mt-2">
|
||||
For support or inquiries, please open an issue on the{" "}
|
||||
{t.contact.before}{" "}
|
||||
<a
|
||||
href="https://github.com/DayuanJiang/next-ai-draw-io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
GitHub repository
|
||||
{t.contact.link}
|
||||
</a>{" "}
|
||||
or contact: me[at]jiang.jp
|
||||
{t.contact.after}
|
||||
</p>
|
||||
|
||||
{/* CTA */}
|
||||
<div className="mt-12 text-center">
|
||||
<Link
|
||||
href="/"
|
||||
href={`/${lang}`}
|
||||
className="inline-block bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
Open Editor
|
||||
{t.openEditor}
|
||||
</Link>
|
||||
</div>
|
||||
</article>
|
||||
@@ -408,8 +652,7 @@ export default function About() {
|
||||
<footer className="bg-white border-t border-gray-200 mt-16">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<p className="text-center text-gray-600 text-sm">
|
||||
Next AI Draw.io - Open Source AI-Powered Diagram
|
||||
Generator
|
||||
{t.footer}
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { MaskedSecret as SecretValue } from "@/lib/admin/auth"
|
||||
import type { AdminProviderInput as AdminProvider } from "@/lib/admin/providers"
|
||||
import { getApiEndpoint } from "@/lib/base-path"
|
||||
import type { ProviderName } from "@/lib/types/model-config"
|
||||
|
||||
@@ -5,7 +7,10 @@ export const SESSION_PASSWORD_KEY = "next-ai-draw-io-admin-password"
|
||||
|
||||
// ── Shared types ─────────────────────────────────────────────────────
|
||||
|
||||
export type SecretValue = { isSet: true; hint: string }
|
||||
// The same shapes the admin API validates and returns. Secret fields of a
|
||||
// provider hold either a masked marker (unchanged) or a plaintext string
|
||||
// (new value).
|
||||
export type { AdminProvider, SecretValue }
|
||||
|
||||
export function isSecretValue(v: unknown): v is SecretValue {
|
||||
return typeof v === "object" && v !== null && "isSet" in v
|
||||
@@ -24,22 +29,6 @@ export function savedTextOf(state: SettingState | undefined): string {
|
||||
return state && !isSecretValue(state.value) ? (state.value ?? "") : ""
|
||||
}
|
||||
|
||||
// Admin provider in client state. Secret fields hold either a masked
|
||||
// marker (unchanged) or a plaintext string (new value).
|
||||
export interface AdminProvider {
|
||||
id: string
|
||||
provider: ProviderName
|
||||
name?: string
|
||||
apiKey?: string | SecretValue
|
||||
baseUrl?: string
|
||||
awsAccessKeyId?: string | SecretValue
|
||||
awsSecretAccessKey?: string | SecretValue
|
||||
awsRegion?: string
|
||||
vertexApiKey?: string | SecretValue
|
||||
models: string[]
|
||||
isDefault?: boolean
|
||||
}
|
||||
|
||||
// Provider defined in AI_MODELS_CONFIG / ai-models.json — shown read-only
|
||||
export interface EnvProvider {
|
||||
name: string
|
||||
|
||||
@@ -3,13 +3,6 @@ import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import type { SettingDef } from "@/lib/admin/settings-registry"
|
||||
@@ -206,26 +199,6 @@ export function SettingField({
|
||||
)
|
||||
break
|
||||
}
|
||||
case "enum":
|
||||
control = (
|
||||
<Select
|
||||
value={currentValue || undefined}
|
||||
disabled={disabled}
|
||||
onValueChange={onChange}
|
||||
>
|
||||
<SelectTrigger id={inputId} className="w-full max-w-xs">
|
||||
<SelectValue placeholder={dict.admin.notSet} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{def.options?.map((opt) => (
|
||||
<SelectItem key={opt} value={opt}>
|
||||
{opt}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
break
|
||||
case "secret":
|
||||
control = (
|
||||
<div className="w-full max-w-md">
|
||||
|
||||
+16
-16
@@ -3,6 +3,7 @@ import type { Metadata, Viewport } from "next"
|
||||
import { Instrument_Sans, JetBrains_Mono } from "next/font/google"
|
||||
import { notFound } from "next/navigation"
|
||||
import Script from "next/script"
|
||||
import { LocaleProvider } from "@/components/canvas/locale-context"
|
||||
import { AppToaster } from "@/components/workspace/app-toaster"
|
||||
import { DiagramProvider } from "@/contexts/diagram-context"
|
||||
import { DictionaryProvider } from "@/hooks/use-dictionary"
|
||||
@@ -40,6 +41,13 @@ export async function generateStaticParams() {
|
||||
return i18n.locales.map((locale) => ({ lang: locale }))
|
||||
}
|
||||
|
||||
const OG_LOCALE: Record<Locale, string> = {
|
||||
en: "en_US",
|
||||
zh: "zh_CN",
|
||||
ja: "ja_JP",
|
||||
"zh-Hant": "zh_HK",
|
||||
}
|
||||
|
||||
// Generate metadata per locale
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
@@ -47,22 +55,19 @@ export async function generateMetadata({
|
||||
params: Promise<{ lang: string }>
|
||||
}): Promise<Metadata> {
|
||||
const { lang: rawLang } = await params
|
||||
const lang = (
|
||||
rawLang in { en: 1, zh: 1, ja: 1, "zh-Hant": 1 } ? rawLang : "en"
|
||||
) as Locale
|
||||
const lang: Locale = hasLocale(rawLang) ? rawLang : i18n.defaultLocale
|
||||
|
||||
// Default to English metadata
|
||||
const titles: Record<Locale, string> = {
|
||||
en: "Next AI Draw.io - AI-Powered Diagram Generator",
|
||||
zh: "Next AI Draw.io - AI powered diagram generator",
|
||||
ja: "Next AI Draw.io - AI-powered diagram generator",
|
||||
zh: "Next AI Draw.io - AI 驱动的图表生成器",
|
||||
ja: "Next AI Draw.io - AI 搭載ダイアグラム生成ツール",
|
||||
"zh-Hant": "Next AI Draw.io - AI 驅動的圖表產生器",
|
||||
}
|
||||
|
||||
const descriptions: Record<Locale, string> = {
|
||||
en: "Create AWS architecture diagrams, flowcharts, and technical diagrams using AI. Free online tool integrating draw.io with AI assistance for professional diagram creation.",
|
||||
zh: "Use AI to create AWS architecture diagrams, flowcharts, and technical diagrams. Free online tool integrated with draw.io and AI assistance for professional diagram creation.",
|
||||
ja: "Create AWS architecture diagrams, flowcharts, and technical diagrams using AI. Create professional diagrams with a free online tool that integrates draw.io with an AI assistant.",
|
||||
zh: "使用 AI 创建 AWS 架构图、流程图和技术图表。免费在线工具,整合 draw.io 与 AI 辅助,轻松创建专业图表。",
|
||||
ja: "AI で AWS アーキテクチャ図、フローチャート、技術図を作成。draw.io と AI アシスタントを統合した無料オンラインツールで、プロ品質の図を簡単に作成できます。",
|
||||
"zh-Hant":
|
||||
"使用 AI 建立 AWS 架構圖、流程圖和技術圖表。免費線上工具整合 draw.io 與 AI 輔助,輕鬆建立專業圖表。",
|
||||
}
|
||||
@@ -91,14 +96,7 @@ export async function generateMetadata({
|
||||
type: "website",
|
||||
url: "https://next-ai-drawio.jiang.jp",
|
||||
siteName: "Next AI Draw.io",
|
||||
locale:
|
||||
lang === "zh"
|
||||
? "zh_CN"
|
||||
: lang === "zh-Hant"
|
||||
? "zh_HK"
|
||||
: lang === "ja"
|
||||
? "ja_JP"
|
||||
: "en_US",
|
||||
locale: OG_LOCALE[lang],
|
||||
images: [
|
||||
{
|
||||
url: "/architecture.png",
|
||||
@@ -184,7 +182,9 @@ export default async function RootLayout({
|
||||
className={`${instrumentSans.variable} ${jetbrainsMono.variable} antialiased`}
|
||||
>
|
||||
<DictionaryProvider dictionary={dictionary}>
|
||||
<LocaleProvider locale={validLang}>
|
||||
<DiagramProvider>{children}</DiagramProvider>
|
||||
</LocaleProvider>
|
||||
</DictionaryProvider>
|
||||
<AppToaster />
|
||||
</body>
|
||||
|
||||
@@ -53,10 +53,6 @@ function validateValue(def: SettingDef, value: string): string | null {
|
||||
return value === "true" || value === "false"
|
||||
? null
|
||||
: 'Must be "true" or "false"'
|
||||
case "enum":
|
||||
return def.options?.includes(value)
|
||||
? null
|
||||
: `Must be one of: ${def.options?.join(", ")}`
|
||||
default:
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { POST as validateModel } from "@/app/api/validate-model/route"
|
||||
import { checkAdminAuth } from "@/lib/admin/auth"
|
||||
import {
|
||||
AdminProviderSchema,
|
||||
@@ -6,6 +5,7 @@ import {
|
||||
mergeSecrets,
|
||||
} from "@/lib/admin/providers"
|
||||
import { globalBaseUrl } from "@/lib/ai-providers"
|
||||
import { testModelConnection } from "@/lib/test-model-connection"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
export const dynamic = "force-dynamic"
|
||||
@@ -48,37 +48,24 @@ export async function POST(req: Request) {
|
||||
sameEndpoint && stored ? [stored] : [],
|
||||
)
|
||||
|
||||
// Without a URL of its own, chat sends the entry's key to the server's
|
||||
// <P>_BASE_URL: test that endpoint, not another one. It is the server's
|
||||
// own, which chat uses without the checks for a URL a user typed.
|
||||
// The admin's own request supplies the EdgeOne endpoint, cookies and
|
||||
// access code, as a chat request would.
|
||||
const serverUrl = globalBaseUrl(resolved.provider)
|
||||
return validateModel(
|
||||
new Request(new URL("/api/validate-model", req.url), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
// Checked again there, in place of an access code
|
||||
"x-admin-password": req.headers.get("x-admin-password") || "",
|
||||
// The EdgeOne function checks the access code and Pages
|
||||
// cookies, and its URL is built from the page's origin
|
||||
"x-access-code": req.headers.get("x-access-code") || "",
|
||||
cookie: req.headers.get("cookie") || "",
|
||||
...(req.headers.get("origin") && {
|
||||
origin: req.headers.get("origin") as string,
|
||||
}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
return testModelConnection(
|
||||
req,
|
||||
{
|
||||
provider: resolved.provider,
|
||||
apiKey: resolved.apiKey,
|
||||
// Without a URL of its own, chat sends the entry's key to
|
||||
// the server's <P>_BASE_URL: test that endpoint, not
|
||||
// another one. It is the server's own, which chat uses
|
||||
// without the checks for a URL a user typed.
|
||||
baseUrl: resolved.baseUrl || serverUrl,
|
||||
...(!resolved.baseUrl && serverUrl && { serverBaseUrl: true }),
|
||||
modelId: body.modelId,
|
||||
awsAccessKeyId: resolved.awsAccessKeyId,
|
||||
awsSecretAccessKey: resolved.awsSecretAccessKey,
|
||||
awsRegion: resolved.awsRegion,
|
||||
vertexApiKey: resolved.vertexApiKey,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
!resolved.baseUrl && !!serverUrl,
|
||||
)
|
||||
}
|
||||
|
||||
+49
-138
@@ -1,8 +1,6 @@
|
||||
import {
|
||||
APICallError,
|
||||
convertToModelMessages,
|
||||
createUIMessageStream,
|
||||
createUIMessageStreamResponse,
|
||||
InvalidToolInputError,
|
||||
stepCountIs,
|
||||
streamText,
|
||||
@@ -21,12 +19,10 @@ import {
|
||||
usesServerCredentials,
|
||||
usesServerEndpoint,
|
||||
} from "@/lib/ai-providers"
|
||||
import { findCachedResponse } from "@/lib/cached-responses"
|
||||
import {
|
||||
dropInvalidToolCalls,
|
||||
fixToolInputJson,
|
||||
formatSelectionContext,
|
||||
replaceHistoricalToolInputs,
|
||||
validateFileParts,
|
||||
} from "@/lib/chat-helpers"
|
||||
import { withDeprecatedParamsFallback } from "@/lib/deprecated-params"
|
||||
@@ -55,53 +51,46 @@ 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 { hasCells } from "@/packages/mcp-server/src/pages.ts"
|
||||
import { foldCells } from "@/packages/mcp-server/src/compact-cells.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,
|
||||
// which is also where Node's response-body timeout on the upstream stream lands.
|
||||
|
||||
// Helper function to create cached stream response
|
||||
function createCachedStreamResponse(xml: string): Response {
|
||||
const toolCallId = `cached-${Date.now()}`
|
||||
|
||||
const stream = createUIMessageStream({
|
||||
execute: async ({ writer }) => {
|
||||
writer.write({ type: "start" })
|
||||
writer.write({
|
||||
type: "tool-input-start",
|
||||
toolCallId,
|
||||
toolName: "display_diagram",
|
||||
})
|
||||
writer.write({
|
||||
type: "tool-input-delta",
|
||||
toolCallId,
|
||||
inputTextDelta: xml,
|
||||
})
|
||||
writer.write({
|
||||
type: "tool-input-available",
|
||||
toolCallId,
|
||||
toolName: "display_diagram",
|
||||
input: { xml },
|
||||
})
|
||||
writer.write({ type: "finish" })
|
||||
},
|
||||
})
|
||||
|
||||
return createUIMessageStreamResponse({ stream })
|
||||
}
|
||||
|
||||
// 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"
|
||||
|
||||
// Message structure for DEBUG_LLM_PAYLOAD logs: roles, part types, tool names
|
||||
// and input keys, without the diagram XML or image data
|
||||
const describeMessages = (msgs: any[]) =>
|
||||
msgs.map((m) => ({
|
||||
role: m.role,
|
||||
parts: (m.parts ?? m.content ?? []).map(
|
||||
(p: any) =>
|
||||
p.type +
|
||||
(p.toolName ? `:${p.toolName}` : "") +
|
||||
(p.input && typeof p.input === "object"
|
||||
? `(${Object.keys(p.input).join(",")})`
|
||||
: ""),
|
||||
),
|
||||
}))
|
||||
|
||||
async function handleChatRequest(req: Request): Promise<Response> {
|
||||
const crossSite = rejectCrossSite(req)
|
||||
if (crossSite) return crossSite
|
||||
@@ -147,23 +136,6 @@ async function handleChatRequest(req: Request): Promise<Response> {
|
||||
}
|
||||
// === FILE VALIDATION END ===
|
||||
|
||||
// === CACHE CHECK START ===
|
||||
const isFirstMessage = messages.length === 1
|
||||
const isEmptyDiagram = !xml || !hasCells(xml)
|
||||
|
||||
if (isFirstMessage && isEmptyDiagram) {
|
||||
const lastMessage = messages[0]
|
||||
const textPart = lastMessage.parts?.find((p: any) => p.type === "text")
|
||||
const filePart = lastMessage.parts?.find((p: any) => p.type === "file")
|
||||
|
||||
const cached = findCachedResponse(textPart?.text || "", !!filePart)
|
||||
|
||||
if (cached) {
|
||||
return createCachedStreamResponse(cached.xml)
|
||||
}
|
||||
}
|
||||
// === CACHE CHECK END ===
|
||||
|
||||
// Read client AI provider overrides from headers
|
||||
const provider = req.headers.get("x-ai-provider")
|
||||
let baseUrl = req.headers.get("x-ai-base-url")
|
||||
@@ -339,7 +311,7 @@ async function handleChatRequest(req: Request): Promise<Response> {
|
||||
`[Prompt Caching] ${shouldCache ? "ENABLED" : "DISABLED"} for model: ${modelId}`,
|
||||
)
|
||||
|
||||
// Get the appropriate system prompt based on model (extended for Opus/Haiku 4.5)
|
||||
// System prompt, with the model name filled in and the style section chosen
|
||||
const systemMessage = getSystemPrompt(modelId, minimalStyle)
|
||||
const finalSystemMessage = customSystemMessage
|
||||
? `${systemMessage}\n\n## Custom Instructions\n${customSystemMessage}`
|
||||
@@ -371,47 +343,15 @@ ${userInputText}
|
||||
|
||||
// DEBUG_LLM_PAYLOAD=true logs the incoming message structure
|
||||
if (DEBUG_LLM_PAYLOAD) {
|
||||
console.log("[route.ts] Incoming messages count:", messages.length)
|
||||
messages.forEach((msg: any, idx: number) => {
|
||||
console.log(
|
||||
`[route.ts] Message ${idx} role:`,
|
||||
msg.role,
|
||||
"parts count:",
|
||||
msg.parts?.length,
|
||||
"[route.ts] incoming",
|
||||
JSON.stringify(describeMessages(messages)),
|
||||
)
|
||||
if (msg.parts) {
|
||||
msg.parts.forEach((part: any, partIdx: number) => {
|
||||
if (
|
||||
part.type === "tool-invocation" ||
|
||||
part.type === "tool-result"
|
||||
) {
|
||||
console.log(`[route.ts] Part ${partIdx}:`, {
|
||||
type: part.type,
|
||||
toolName: part.toolName,
|
||||
hasInput: !!part.input,
|
||||
inputType: typeof part.input,
|
||||
inputKeys:
|
||||
part.input && typeof part.input === "object"
|
||||
? Object.keys(part.input)
|
||||
: null,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Replace historical tool call XML with placeholders to reduce tokens
|
||||
// Disabled by default - some models (e.g. minimax) copy placeholders instead of generating XML
|
||||
const enableHistoryReplace =
|
||||
process.env.ENABLE_HISTORY_XML_REPLACE === "true"
|
||||
const placeholderMessages = enableHistoryReplace
|
||||
? replaceHistoricalToolInputs(modelMessages)
|
||||
: modelMessages
|
||||
|
||||
// Filter out messages with empty content arrays (Bedrock API rejects these)
|
||||
// This is a safety measure - ideally convertToModelMessages should handle all cases
|
||||
let enhancedMessages = placeholderMessages.filter(
|
||||
let enhancedMessages = modelMessages.filter(
|
||||
(msg: any) =>
|
||||
msg.content && Array.isArray(msg.content) && msg.content.length > 0,
|
||||
)
|
||||
@@ -423,36 +363,10 @@ ${userInputText}
|
||||
|
||||
// DEBUG_LLM_PAYLOAD=true logs what is sent to the model
|
||||
if (DEBUG_LLM_PAYLOAD) {
|
||||
console.log("[route.ts] Model messages count:", enhancedMessages.length)
|
||||
enhancedMessages.forEach((msg: any, idx: number) => {
|
||||
console.log(
|
||||
`[route.ts] ModelMsg ${idx} role:`,
|
||||
msg.role,
|
||||
"content count:",
|
||||
msg.content?.length,
|
||||
"[route.ts] to model",
|
||||
JSON.stringify(describeMessages(enhancedMessages)),
|
||||
)
|
||||
if (msg.content) {
|
||||
msg.content.forEach((part: any, partIdx: number) => {
|
||||
if (
|
||||
part.type === "tool-call" ||
|
||||
part.type === "tool-result"
|
||||
) {
|
||||
console.log(`[route.ts] Content ${partIdx}:`, {
|
||||
type: part.type,
|
||||
toolName: part.toolName,
|
||||
hasInput: !!part.input,
|
||||
inputType: typeof part.input,
|
||||
inputValue:
|
||||
part.input === undefined
|
||||
? "undefined"
|
||||
: part.input === null
|
||||
? "null"
|
||||
: "object",
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Update the last message with user input only (XML moved to separate cached system message)
|
||||
@@ -515,18 +429,20 @@ ${userInputText}
|
||||
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.${selectionContext ? `\n\n${selectionContext}` : ""}`
|
||||
@@ -654,19 +570,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.
|
||||
@@ -685,12 +606,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"}]}`,
|
||||
@@ -730,7 +651,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()
|
||||
@@ -774,19 +695,9 @@ Call this tool to get shape names and usage syntax for a specific library.`,
|
||||
// Keyless endpoints keep theirs: the desktop app's Ollama is the
|
||||
// user's own, and EdgeOne's text is our function's explanation.
|
||||
onError: (error) => streamErrorText(error, onServerCredentials),
|
||||
messageMetadata: ({ part }) => {
|
||||
if (part.type === "finish") {
|
||||
const usage = (part as any).totalUsage
|
||||
// AI SDK 6 provides totalTokens directly
|
||||
return {
|
||||
totalTokens: usage?.totalTokens ?? 0,
|
||||
finishReason: (part as any).finishReason,
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
modelStreamResponses.add(response)
|
||||
requestOfResponse.set(response, req)
|
||||
return response
|
||||
}
|
||||
|
||||
@@ -823,7 +734,7 @@ async function safeHandler(req: Request): Promise<Response> {
|
||||
} catch (error) {
|
||||
response = handleError(error)
|
||||
}
|
||||
// Early returns, cache hits and errors never reach streamText's callbacks,
|
||||
// Early returns and errors never reach streamText's callbacks,
|
||||
// so their Langfuse trace has to be ended here
|
||||
if (!modelStreamResponses.has(response)) endTrace()
|
||||
return response
|
||||
|
||||
@@ -1,321 +0,0 @@
|
||||
# Draw.io XML Schema Guide
|
||||
|
||||
This guide explains the structure of draw.io (diagrams.net) XML files to help you understand and create diagrams programmatically.
|
||||
|
||||
## Basic Structure
|
||||
|
||||
A draw.io XML file has the following hierarchy:
|
||||
|
||||
```xml
|
||||
<mxfile>
|
||||
<diagram>
|
||||
<mxGraphModel>
|
||||
<root>
|
||||
<mxCell /> <!-- Cells that make up the diagram -->
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
```
|
||||
|
||||
## Root Element: `<mxfile>`
|
||||
|
||||
The root element of a draw.io file.
|
||||
|
||||
**Attributes:**
|
||||
|
||||
- `host`: The application that created the file (e.g., "app.diagrams.net")
|
||||
- `modified`: Last modification timestamp
|
||||
- `agent`: Browser / user agent information
|
||||
- `version`: Version of the application
|
||||
- `type`: File type (usually "device" or "google")
|
||||
|
||||
**Example:**
|
||||
|
||||
```xml
|
||||
<mxfile host="app.diagrams.net" modified="2023-07-14T10:20:30.123Z" agent="Mozilla/5.0" version="21.5.2" type="device">
|
||||
```
|
||||
|
||||
## Diagram Element: `<diagram>`
|
||||
|
||||
Each page in your draw.io document is represented by a `<diagram>` element.
|
||||
|
||||
**Attributes:**
|
||||
|
||||
- `id`: Unique identifier for the diagram
|
||||
- `name`: The name of the diagram / page
|
||||
|
||||
**Example:**
|
||||
|
||||
```xml
|
||||
<diagram id="pWHN0msd4Ud1ZK5cD-Hr" name="Page-1">
|
||||
```
|
||||
|
||||
## Graph Model: `<mxGraphModel>`
|
||||
|
||||
Contains the actual diagram data.
|
||||
|
||||
**Attributes:**
|
||||
|
||||
- `dx`: Grid size in x-direction (usually 1)
|
||||
- `dy`: Grid size in y-direction (usually 1)
|
||||
- `grid`: Whether grid is enabled (0 or 1)
|
||||
- `gridSize`: Grid cell size (usually 10)
|
||||
- `guides`: Whether guides are enabled (0 or 1)
|
||||
- `tooltips`: Whether tooltips are enabled (0 or 1)
|
||||
- `connect`: Whether connections are enabled (0 or 1)
|
||||
- `arrows`: Whether arrows are enabled (0 or 1)
|
||||
- `fold`: Whether folding is enabled (0 or 1)
|
||||
- `page`: Whether page view is enabled (0 or 1)
|
||||
- `pageScale`: Scale of the page (usually 1)
|
||||
- `pageWidth`: Width of the page (e.g., 850)
|
||||
- `pageHeight`: Height of the page (e.g., 1100)
|
||||
- `math`: Whether math typesetting is enabled (0 or 1)
|
||||
- `shadow`: Whether shadows are enabled (0 or 1)
|
||||
|
||||
**Example:**
|
||||
|
||||
```xml
|
||||
<mxGraphModel dx="1" dy="1" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
|
||||
```
|
||||
|
||||
## Root Cell Container: `<root>`
|
||||
|
||||
Contains all the cells in the diagram. **Note:** When generating diagrams, you only need to provide the mxCell elements - the root container and root cells (id="0", id="1") are added automatically.
|
||||
|
||||
**Internal structure (auto-generated):**
|
||||
|
||||
```xml
|
||||
<root>
|
||||
<mxCell id="0"/> <!-- Auto-added -->
|
||||
<mxCell id="1" parent="0"/> <!-- Auto-added -->
|
||||
<!-- Your mxCell elements go here (start from id="2") -->
|
||||
</root>
|
||||
```
|
||||
|
||||
## Cell Elements: `<mxCell>`
|
||||
|
||||
The basic building block of diagrams. Cells represent shapes, connectors, text, etc.
|
||||
|
||||
**Attributes for all cells:**
|
||||
|
||||
- `id`: Unique identifier for the cell
|
||||
- `parent`: ID of the parent cell (typically "1" for most cells)
|
||||
- `value`: Text content of the cell
|
||||
- `style`: Styling information (see Style section below)
|
||||
|
||||
**Attributes for shapes (vertices):**
|
||||
|
||||
- `vertex`: Set to "1" for shapes
|
||||
- `connectable`: Whether the shape can be connected (0 or 1)
|
||||
|
||||
**Attributes for connectors (edges):**
|
||||
|
||||
- `edge`: Set to "1" for connectors
|
||||
- `source`: ID of the source cell
|
||||
- `target`: ID of the target cell
|
||||
|
||||
**Example (Rectangle shape):**
|
||||
|
||||
```xml
|
||||
<mxCell id="2" value="Hello World" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="350" y="190" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
```
|
||||
|
||||
**Example (Connector):**
|
||||
|
||||
```xml
|
||||
<mxCell id="3" value="" style="endArrow=classic;html=1;rounded=0;" edge="1" parent="1" source="2" target="4">
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="400" y="430" as="sourcePoint"/>
|
||||
<mxPoint x="450" y="380" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
```
|
||||
|
||||
## Geometry: `<mxGeometry>`
|
||||
|
||||
Defines the position and dimensions of cells.
|
||||
|
||||
**Attributes for shapes:**
|
||||
|
||||
- `x`: The x-coordinate of the **top-left** point of the shape.
|
||||
- `y`: The y-coordinate of the **top-left** point of the shape.
|
||||
- `width`: The width of the shape.
|
||||
- `height`: The height of the shape.
|
||||
- `as`: Specifies the role of this geometry within its parent cell. Typically set to `"geometry"` for the main shape definition.
|
||||
|
||||
**Attributes for connectors:**
|
||||
|
||||
- `relative`: Set to "1" for relative geometry
|
||||
- `as`: Set to "geometry"
|
||||
|
||||
**Example for shapes:**
|
||||
|
||||
```xml
|
||||
<mxGeometry x="350" y="190" width="120" height="60" as="geometry"/>
|
||||
```
|
||||
|
||||
**Example for connectors:**
|
||||
|
||||
```xml
|
||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||
<mxPoint x="400" y="430" as="sourcePoint"/>
|
||||
<mxPoint x="450" y="380" as="targetPoint"/>
|
||||
</mxGeometry>
|
||||
```
|
||||
|
||||
## Cell Style Reference
|
||||
|
||||
Styles are specified as semicolon-separated `key=value` pairs in the `style` attribute of `<mxCell>` elements.
|
||||
|
||||
### Shape-specific Styles
|
||||
|
||||
- Rectangle: `shape=rectangle`
|
||||
- Ellipse: `shape=ellipse`
|
||||
- Triangle: `shape=triangle`
|
||||
- Rhombus: `shape=rhombus`
|
||||
- Hexagon: `shape=hexagon`
|
||||
- Cloud: `shape=cloud`
|
||||
- Actor: `shape=actor`
|
||||
- Cylinder: `shape=cylinder`
|
||||
- Document: `shape=document`
|
||||
- Note: `shape=note`
|
||||
- Card: `shape=card`
|
||||
- Parallelogram: `shape=parallelogram`
|
||||
|
||||
### Connector Styles
|
||||
|
||||
- `endArrow=classic`: Arrow type at the end (classic, open, oval, diamond, block)
|
||||
- `startArrow=none`: Arrow type at the start (none, classic, open, oval, diamond)
|
||||
- `curved=1`: Curved connector (0 or 1)
|
||||
- `edgeStyle=orthogonalEdgeStyle`: Connector routing style
|
||||
- `elbow=vertical`: Elbow direction (vertical, horizontal)
|
||||
- `jumpStyle=arc`: Jump style for line crossing (arc, gap)
|
||||
- `jumpSize=10`: Size of the jump
|
||||
|
||||
## Special Cells
|
||||
|
||||
Draw.io files contain two special cells that are always present:
|
||||
|
||||
1. **Root Cell** (id = "0"): The parent of all cells
|
||||
2. **Default Parent Cell** (id = "1", parent = "0"): The default layer and parent for most cells
|
||||
|
||||
## Tips for Creating Draw.io XML
|
||||
|
||||
1. **Generate ONLY mxCell elements** - wrapper tags and root cells (id="0", id="1") are added automatically
|
||||
2. Start IDs from "2" (id="0" and id="1" are reserved for root cells)
|
||||
3. Assign unique and sequential IDs to all cells
|
||||
4. Define parent relationships correctly (use parent="1" for top-level shapes)
|
||||
5. Use `mxGeometry` elements to position shapes
|
||||
6. For connectors, specify `source` and `target` attributes
|
||||
7. **CRITICAL: All mxCell elements must be siblings. NEVER nest mxCell inside another mxCell.**
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Grouping Elements
|
||||
|
||||
To group elements, create a parent cell and set other cells' `parent` attribute to its ID:
|
||||
|
||||
```xml
|
||||
<!-- Group container -->
|
||||
<mxCell id="10" value="Group" style="group" vertex="1" connectable="0" parent="1">
|
||||
<mxGeometry x="200" y="200" width="200" height="100" as="geometry" />
|
||||
</mxCell>
|
||||
<!-- Elements inside the group -->
|
||||
<mxCell id="11" value="Element 1" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="10">
|
||||
<mxGeometry width="90" height="40" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="12" value="Element 2" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="10">
|
||||
<mxGeometry x="110" width="90" height="40" as="geometry" />
|
||||
</mxCell>
|
||||
```
|
||||
|
||||
### Swimlanes
|
||||
|
||||
Swimlanes use the `swimlane` shape style. **IMPORTANT: All mxCell elements (swimlanes, steps, and edges) must be siblings under `<root>`. Edges are NOT nested inside swimlanes or steps.**
|
||||
|
||||
```xml
|
||||
<root>
|
||||
<mxCell id="0"/>
|
||||
<mxCell id="1" parent="0"/>
|
||||
<!-- Swimlane 1 -->
|
||||
<mxCell id="lane1" value="Frontend" style="swimlane;startSize=30;" vertex="1" parent="1">
|
||||
<mxGeometry x="40" y="40" width="200" height="300" as="geometry"/>
|
||||
</mxCell>
|
||||
<!-- Swimlane 2 -->
|
||||
<mxCell id="lane2" value="Backend" style="swimlane;startSize=30;" vertex="1" parent="1">
|
||||
<mxGeometry x="280" y="40" width="200" height="300" as="geometry"/>
|
||||
</mxCell>
|
||||
<!-- Step inside lane1 (parent="lane1") -->
|
||||
<mxCell id="step1" value="Send Request" style="rounded=1;" vertex="1" parent="lane1">
|
||||
<mxGeometry x="20" y="60" width="160" height="40" as="geometry"/>
|
||||
</mxCell>
|
||||
<!-- Step inside lane2 (parent="lane2") -->
|
||||
<mxCell id="step2" value="Process" style="rounded=1;" vertex="1" parent="lane2">
|
||||
<mxGeometry x="20" y="60" width="160" height="40" as="geometry"/>
|
||||
</mxCell>
|
||||
<!-- Edge connecting step1 to step2 (sibling element, NOT nested inside steps) -->
|
||||
<mxCell id="edge1" style="edgeStyle=orthogonalEdgeStyle;endArrow=classic;" edge="1" parent="1" source="step1" target="step2">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
</root>
|
||||
```
|
||||
|
||||
### Tables
|
||||
|
||||
Tables use multiple cells with parent-child relationships:
|
||||
|
||||
```xml
|
||||
<mxCell id="30" value="Table" style="shape=table;startSize=30;container=1;collapsible=1;childLayout=tableLayout;fixedRows=1;rowLines=0;fontStyle=1;align=center;resizeLast=1;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="200" y="200" width="180" height="120" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="31" value="" style="shape=tableRow;horizontal=0;startSize=0;swimlaneHead=0;swimlaneBody=0;fillColor=none;collapsible=0;dropTarget=0;points=[0,0.5,1,0.5];portConstraint=eastwest;top=0;left=0;right=0;bottom=1;" vertex="1" parent="30">
|
||||
<mxGeometry y="30" width="180" height="30" as="geometry" />
|
||||
</mxCell>
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Custom Attributes
|
||||
|
||||
Draw.io allows adding custom attributes to cells:
|
||||
|
||||
```xml
|
||||
<mxCell id="40" value="Custom Element" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="200" y="200" width="120" height="60" as="geometry"/>
|
||||
<Object label="Custom Label" customAttr="value" />
|
||||
</mxCell>
|
||||
```
|
||||
|
||||
These custom attributes can store additional metadata or be used by plugins and custom behaviors.
|
||||
|
||||
### User-defined Styles
|
||||
|
||||
You can define custom styles for cells by combining various style attributes:
|
||||
|
||||
```xml
|
||||
<mxCell id="50" value="Custom Styled Cell"
|
||||
style="shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;fillColor=#f8cecc;strokeColor=#b85450;strokeWidth=2;fontSize=14;fontStyle=1"
|
||||
vertex="1" parent="1">
|
||||
<mxGeometry x="300" y="200" width="120" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
```
|
||||
|
||||
### Layers
|
||||
|
||||
You can create multiple layers in a diagram to organize complex diagrams:
|
||||
|
||||
```xml
|
||||
<!-- Default layer (always present) -->
|
||||
<mxCell id="1" parent="0"/>
|
||||
|
||||
<!-- Additional custom layer -->
|
||||
<mxCell id="60" value="Layer 2" style="locked=0;group=" parent="0"/>
|
||||
|
||||
<!-- Elements in Layer 2 -->
|
||||
<mxCell id="61" value="Element in Layer 2" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="60">
|
||||
<mxGeometry x="200" y="300" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
```
|
||||
@@ -3,8 +3,5 @@ import { NextResponse } from "next/server"
|
||||
export async function GET() {
|
||||
return NextResponse.json({
|
||||
accessCodeRequired: !!process.env.ACCESS_CODE_LIST,
|
||||
dailyRequestLimit: Number(process.env.DAILY_REQUEST_LIMIT) || 0,
|
||||
dailyTokenLimit: Number(process.env.DAILY_TOKEN_LIMIT) || 0,
|
||||
tpmLimit: Number(process.env.TPM_LIMIT) || 0,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { randomUUID } from "crypto"
|
||||
import { z } from "zod"
|
||||
import { getLangfuseClient } from "@/lib/langfuse"
|
||||
import { getLangfuseClient, scoreLatestTrace } from "@/lib/langfuse"
|
||||
import { getUserIdFromRequest } from "@/lib/user-id"
|
||||
|
||||
const feedbackSchema = z.object({
|
||||
@@ -37,74 +36,23 @@ export async function POST(req: Request) {
|
||||
const userId = getUserIdFromRequest(req)
|
||||
|
||||
try {
|
||||
// Find the most recent chat trace for this session to attach the score to
|
||||
const tracesResponse = await langfuse.api.trace.list({
|
||||
// Score the session's latest chat trace; without one, a standalone
|
||||
// feedback trace carries the score
|
||||
await scoreLatestTrace(langfuse, {
|
||||
sessionId,
|
||||
limit: 1,
|
||||
})
|
||||
|
||||
const traces = tracesResponse.data || []
|
||||
const latestTrace = traces[0]
|
||||
|
||||
if (!latestTrace) {
|
||||
// No trace found for this session - create a standalone feedback trace
|
||||
const traceId = randomUUID()
|
||||
const timestamp = new Date().toISOString()
|
||||
|
||||
await langfuse.api.ingestion.batch({
|
||||
batch: [
|
||||
{
|
||||
type: "trace-create",
|
||||
id: randomUUID(),
|
||||
timestamp,
|
||||
body: {
|
||||
id: traceId,
|
||||
name: "user-feedback",
|
||||
sessionId,
|
||||
value: feedback === "good" ? 1 : 0,
|
||||
comment: `User gave ${feedback} feedback`,
|
||||
fallbackTrace: {
|
||||
name: "user-feedback",
|
||||
userId,
|
||||
input: { messageId, feedback },
|
||||
metadata: {
|
||||
source: "feedback-button",
|
||||
note: "standalone - no chat trace found",
|
||||
},
|
||||
timestamp,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "score-create",
|
||||
id: randomUUID(),
|
||||
timestamp,
|
||||
body: {
|
||||
id: randomUUID(),
|
||||
traceId,
|
||||
name: "user-feedback",
|
||||
value: feedback === "good" ? 1 : 0,
|
||||
comment: `User gave ${feedback} feedback`,
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
} else {
|
||||
// Attach score to the existing chat trace
|
||||
const timestamp = new Date().toISOString()
|
||||
|
||||
await langfuse.api.ingestion.batch({
|
||||
batch: [
|
||||
{
|
||||
type: "score-create",
|
||||
id: randomUUID(),
|
||||
timestamp,
|
||||
body: {
|
||||
id: randomUUID(),
|
||||
traceId: latestTrace.id,
|
||||
name: "user-feedback",
|
||||
value: feedback === "good" ? 1 : 0,
|
||||
comment: `User gave ${feedback} feedback`,
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
return Response.json({ success: true, logged: true })
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { randomUUID } from "crypto"
|
||||
import { z } from "zod"
|
||||
import { getLangfuseClient } from "@/lib/langfuse"
|
||||
import { getLangfuseClient, scoreLatestTrace } from "@/lib/langfuse"
|
||||
|
||||
const saveSchema = z.object({
|
||||
filename: z.string().min(1).max(255),
|
||||
@@ -33,39 +32,16 @@ export async function POST(req: Request) {
|
||||
}
|
||||
|
||||
try {
|
||||
const timestamp = new Date().toISOString()
|
||||
|
||||
// Find the most recent chat trace for this session to attach the save flag
|
||||
const tracesResponse = await langfuse.api.trace.list({
|
||||
// Flag the session's latest chat trace as saved; a session without a
|
||||
// trace (no chat yet) is skipped
|
||||
const logged = await scoreLatestTrace(langfuse, {
|
||||
sessionId,
|
||||
limit: 1,
|
||||
})
|
||||
|
||||
const traces = tracesResponse.data || []
|
||||
const latestTrace = traces[0]
|
||||
|
||||
if (latestTrace) {
|
||||
// Add a score to the existing trace to flag that user saved
|
||||
await langfuse.api.ingestion.batch({
|
||||
batch: [
|
||||
{
|
||||
type: "score-create",
|
||||
id: randomUUID(),
|
||||
timestamp,
|
||||
body: {
|
||||
id: randomUUID(),
|
||||
traceId: latestTrace.id,
|
||||
name: "diagram-saved",
|
||||
value: 1,
|
||||
comment: `User saved diagram as ${filename}.${format}`,
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
// If no trace found, skip logging (user hasn't chatted yet)
|
||||
|
||||
return Response.json({ success: true, logged: !!latestTrace })
|
||||
return Response.json({ success: true, logged })
|
||||
} catch (error) {
|
||||
console.error("Langfuse save error:", error)
|
||||
return Response.json(
|
||||
|
||||
@@ -7,8 +7,5 @@ export const dynamic = "force-dynamic"
|
||||
|
||||
export async function GET() {
|
||||
const models = await loadFlattenedServerModels()
|
||||
return NextResponse.json({
|
||||
models,
|
||||
hasConfig: models.length > 0,
|
||||
})
|
||||
return NextResponse.json({ models })
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* API endpoint for VLM-based diagram validation.
|
||||
* Accepts a PNG image and streams validation results using useObject-compatible format.
|
||||
* Accepts a PNG image and answers with the validation result as JSON.
|
||||
*/
|
||||
|
||||
import { Output, streamText } from "ai"
|
||||
import { generateText, Output } from "ai"
|
||||
import { checkAccessCode, rejectCrossSite } from "@/lib/access-code"
|
||||
import { getValidationModel } from "@/lib/ai-providers"
|
||||
import {
|
||||
@@ -35,13 +35,6 @@ const DEFAULT_VALID_RESULT: ValidationResult = {
|
||||
suggestions: [],
|
||||
}
|
||||
|
||||
/** A fixed result in the text format useObject reads */
|
||||
function createStreamingResponse(result: ValidationResult): Response {
|
||||
return new Response(JSON.stringify(result), {
|
||||
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
||||
})
|
||||
}
|
||||
|
||||
export async function POST(req: Request): Promise<Response> {
|
||||
const crossSite = rejectCrossSite(req)
|
||||
if (crossSite) return crossSite
|
||||
@@ -53,7 +46,7 @@ export async function POST(req: Request): Promise<Response> {
|
||||
// Check if VLM validation is enabled (default: true)
|
||||
const enableValidation = process.env.ENABLE_VLM_VALIDATION !== "false"
|
||||
if (!enableValidation) {
|
||||
return createStreamingResponse(DEFAULT_VALID_RESULT)
|
||||
return Response.json(DEFAULT_VALID_RESULT)
|
||||
}
|
||||
|
||||
const body: ValidateDiagramRequest = await req.json()
|
||||
@@ -123,7 +116,7 @@ export async function POST(req: Request): Promise<Response> {
|
||||
error,
|
||||
)
|
||||
// Return valid if no vision model is configured
|
||||
return createStreamingResponse(DEFAULT_VALID_RESULT)
|
||||
return Response.json(DEFAULT_VALID_RESULT)
|
||||
}
|
||||
|
||||
// Parse timeout with validation (minimum 1000ms, default 10000ms)
|
||||
@@ -133,8 +126,7 @@ export async function POST(req: Request): Promise<Response> {
|
||||
parseInt(process.env.VALIDATION_TIMEOUT || "10000", 10),
|
||||
) || 10000
|
||||
|
||||
// Stream the VLM response for useObject consumption
|
||||
const result = streamText({
|
||||
const { output, totalUsage } = await generateText({
|
||||
model,
|
||||
output: Output.object({ schema: ValidationResultSchema }),
|
||||
system: VALIDATION_SYSTEM_PROMPT,
|
||||
@@ -155,23 +147,19 @@ export async function POST(req: Request): Promise<Response> {
|
||||
],
|
||||
maxOutputTokens: 1024,
|
||||
abortSignal: AbortSignal.timeout(timeout),
|
||||
onFinish: ({ output, totalUsage }) => {
|
||||
if (countsQuota && totalUsage) {
|
||||
recordTokenUsage(
|
||||
})
|
||||
if (countsQuota) {
|
||||
await recordTokenUsage(
|
||||
userId,
|
||||
(totalUsage.inputTokens || 0) +
|
||||
(totalUsage.outputTokens || 0),
|
||||
(totalUsage.inputTokens || 0) + (totalUsage.outputTokens || 0),
|
||||
)
|
||||
}
|
||||
if (sessionId && output) {
|
||||
if (sessionId) {
|
||||
console.log(
|
||||
`[validate-diagram] Session ${sessionId}: valid=${output.valid}, issues=${output.issues?.length ?? 0}`,
|
||||
)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return result.toTextStreamResponse()
|
||||
return Response.json(output)
|
||||
} catch (error) {
|
||||
// Log with session context if available
|
||||
const errorMessage =
|
||||
@@ -179,6 +167,6 @@ export async function POST(req: Request): Promise<Response> {
|
||||
console.error("[validate-diagram] Error:", errorMessage)
|
||||
|
||||
// On error, return valid to not block the user
|
||||
return createStreamingResponse(DEFAULT_VALID_RESULT)
|
||||
return Response.json(DEFAULT_VALID_RESULT)
|
||||
}
|
||||
}
|
||||
|
||||
+12
-232
@@ -1,249 +1,29 @@
|
||||
import { streamText, tool } from "ai"
|
||||
import { NextResponse } from "next/server"
|
||||
import { z } from "zod"
|
||||
import { checkAccessCode, rejectCrossSite } from "@/lib/access-code"
|
||||
import { checkAdminAuth } from "@/lib/admin/auth"
|
||||
import {
|
||||
edgeOneEndpoint,
|
||||
getAIModel,
|
||||
globalBaseUrl,
|
||||
usesServerCredentials,
|
||||
usesServerEndpoint,
|
||||
} from "@/lib/ai-providers"
|
||||
import {
|
||||
checkAndIncrementRequest,
|
||||
isQuotaEnabled,
|
||||
} from "@/lib/dynamo-quota-manager"
|
||||
import { classifyLLMError } from "@/lib/llm-errors"
|
||||
import { allowPrivateUrls, isPrivateUrl } from "@/lib/ssrf-protection"
|
||||
import { normalizeBaseUrl, type ProviderName } from "@/lib/types/model-config"
|
||||
import { getUserIdFromRequest } from "@/lib/user-id"
|
||||
type TestModelRequest,
|
||||
testModelConnection,
|
||||
} from "@/lib/test-model-connection"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
interface ValidateRequest {
|
||||
provider: ProviderName
|
||||
apiKey: string
|
||||
baseUrl?: string
|
||||
modelId: string
|
||||
// AWS Bedrock specific
|
||||
awsAccessKeyId?: string
|
||||
awsSecretAccessKey?: string
|
||||
awsRegion?: string
|
||||
awsSessionToken?: string
|
||||
// Vertex AI specific
|
||||
vertexApiKey?: string // Express Mode API key
|
||||
// Set by the admin panel's Test: baseUrl is the server's <P>_BASE_URL
|
||||
serverBaseUrl?: boolean
|
||||
}
|
||||
|
||||
const TEST_TIMEOUT_MS = 15_000
|
||||
|
||||
// Drawing works through tool calls, so the test asks for one
|
||||
const PING_TOOL = tool({
|
||||
description: "Report that the connection works.",
|
||||
inputSchema: z.object({}),
|
||||
})
|
||||
|
||||
const NO_TOOL_CALL_WARNING =
|
||||
"Connected, but the model answered without calling a tool. It may not support tool calls, which drawing needs."
|
||||
|
||||
// The Settings dialog's Test button: a model on the user's own credentials
|
||||
export async function POST(req: Request) {
|
||||
const crossSite = rejectCrossSite(req)
|
||||
if (crossSite) return crossSite
|
||||
// Lets the server send requests to arbitrary URLs, so require the access
|
||||
// code, or the admin password (the admin panel's Test button)
|
||||
// Lets the server send requests to arbitrary URLs, so require the access code
|
||||
const accessError = checkAccessCode(req)
|
||||
if (accessError && checkAdminAuth(req)) return accessError
|
||||
if (accessError) return accessError
|
||||
|
||||
let body: TestModelRequest
|
||||
try {
|
||||
const body: ValidateRequest = await req.json()
|
||||
const {
|
||||
provider,
|
||||
apiKey,
|
||||
modelId,
|
||||
awsAccessKeyId,
|
||||
awsSecretAccessKey,
|
||||
awsRegion,
|
||||
awsSessionToken,
|
||||
// Note: Express Mode only needs vertexApiKey
|
||||
vertexApiKey,
|
||||
} = body
|
||||
|
||||
if (!provider || !modelId) {
|
||||
body = await req.json()
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Provider and model ID are required" },
|
||||
{ valid: false, error: "Invalid JSON body" },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
// EdgeOne is this site's own function, as in the chat; the admin
|
||||
// panel's Test sends no URL, and a relative one cannot be fetched
|
||||
const baseUrl =
|
||||
provider === "edgeone" ? edgeOneEndpoint(req) : body.baseUrl
|
||||
// The admin panel's Test of an entry without a URL sends the
|
||||
// server's own <P>_BASE_URL, which chat uses as it is: not a URL a
|
||||
// user chose, so no private-address or redirect rules
|
||||
const serverUrl =
|
||||
body.serverBaseUrl === true &&
|
||||
!!baseUrl &&
|
||||
baseUrl === globalBaseUrl(provider) &&
|
||||
!checkAdminAuth(req)
|
||||
|
||||
// SECURITY: Block SSRF attacks via custom baseUrl
|
||||
if (
|
||||
baseUrl &&
|
||||
!serverUrl &&
|
||||
!allowPrivateUrls() &&
|
||||
(await isPrivateUrl(baseUrl))
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "Invalid base URL" },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// Validate credentials based on provider
|
||||
if (provider === "bedrock") {
|
||||
if (
|
||||
!(apiKey || (awsAccessKeyId && awsSecretAccessKey)) ||
|
||||
!awsRegion
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
valid: false,
|
||||
error: "AWS credentials (a Bedrock API key, or an Access Key ID and Secret Access Key, and a Region) are required",
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
} else if (provider === "vertexai") {
|
||||
if (!vertexApiKey) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
valid: false,
|
||||
error: "Vertex AI API key is required for Express Mode",
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
} else if (provider !== "ollama" && provider !== "edgeone" && !apiKey) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "API key is required" },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
// The Test button checks the user's own provider. On the server's
|
||||
// keys (Ollama Cloud without a key or URL) anyone could run any model.
|
||||
if (
|
||||
usesServerCredentials(provider, {
|
||||
apiKey,
|
||||
baseUrl,
|
||||
awsAccessKeyId,
|
||||
awsSecretAccessKey,
|
||||
vertexApiKey,
|
||||
})
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: "API key is required" },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// On the deployment's own endpoints a Test runs a model as a chat
|
||||
// does, so with the quota on it counts as a chat request (an
|
||||
// admin's Test of the server's URL does not)
|
||||
const userId = getUserIdFromRequest(req)
|
||||
if (
|
||||
isQuotaEnabled() &&
|
||||
!serverUrl &&
|
||||
userId !== "anonymous" &&
|
||||
(await usesServerEndpoint(
|
||||
provider,
|
||||
normalizeBaseUrl(body.baseUrl ?? ""),
|
||||
apiKey,
|
||||
))
|
||||
) {
|
||||
const quotaCheck = await checkAndIncrementRequest(userId, {
|
||||
requests: Number(process.env.DAILY_REQUEST_LIMIT) || 10,
|
||||
tokens: Number(process.env.DAILY_TOKEN_LIMIT) || 200000,
|
||||
tpm: Number(process.env.TPM_LIMIT) || 20000,
|
||||
})
|
||||
if (!quotaCheck.allowed) {
|
||||
return NextResponse.json(
|
||||
{ valid: false, error: quotaCheck.error },
|
||||
{ status: 429 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// The same model the chat would use. A client base URL makes it
|
||||
// refuse redirects to internal hosts.
|
||||
const { model } = getAIModel({
|
||||
provider,
|
||||
modelId,
|
||||
apiKey,
|
||||
baseUrl,
|
||||
trustedBaseUrl: serverUrl,
|
||||
awsAccessKeyId,
|
||||
awsSecretAccessKey,
|
||||
awsRegion,
|
||||
// Temporary AWS credentials need it, as in the chat
|
||||
awsSessionToken,
|
||||
vertexApiKey,
|
||||
// EdgeOne checks the Pages cookies and the access code
|
||||
...(provider === "edgeone" && {
|
||||
headers: {
|
||||
cookie: req.headers.get("cookie") || "",
|
||||
"x-access-code": req.headers.get("x-access-code") || "",
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
// Streaming, like the chat (some models only stream). Stop at the
|
||||
// first tool call; a reasoning model that runs out of tokens first
|
||||
// proves the connection but not tool support.
|
||||
const startTime = Date.now()
|
||||
const result = streamText({
|
||||
model,
|
||||
prompt: "Call the ping tool.",
|
||||
tools: { ping: PING_TOOL },
|
||||
maxOutputTokens: 1024,
|
||||
maxRetries: 0,
|
||||
abortSignal: AbortSignal.timeout(TEST_TIMEOUT_MS),
|
||||
})
|
||||
let calledTool = false
|
||||
let finishReason: string | undefined
|
||||
for await (const part of result.fullStream) {
|
||||
if (part.type === "error") throw part.error
|
||||
// The timeout ends the stream with an abort part, not an error
|
||||
if (part.type === "abort") {
|
||||
const timeout = new Error(
|
||||
`The model did not answer within ${TEST_TIMEOUT_MS / 1000} s.`,
|
||||
)
|
||||
timeout.name = "TimeoutError"
|
||||
throw timeout
|
||||
}
|
||||
if (part.type === "tool-call") {
|
||||
calledTool = true
|
||||
break
|
||||
}
|
||||
if (part.type === "finish") finishReason = part.finishReason
|
||||
}
|
||||
const responseTime = Date.now() - startTime
|
||||
|
||||
return NextResponse.json({
|
||||
valid: true,
|
||||
responseTime,
|
||||
...(!calledTool &&
|
||||
finishReason !== "length" && { warning: NO_TOOL_CALL_WARNING }),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("[validate-model] Error:", error)
|
||||
|
||||
const { code, message } = classifyLLMError(error)
|
||||
return NextResponse.json(
|
||||
{ valid: false, code, error: message },
|
||||
{ status: 200 }, // Return 200 so client can read error message
|
||||
)
|
||||
}
|
||||
// A URL in the request is one the user typed, never the server's own
|
||||
return testModelConnection(req, body, false)
|
||||
}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 2.0 KiB |
+9
-22
@@ -98,9 +98,7 @@
|
||||
--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);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -241,13 +239,6 @@
|
||||
.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);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
@@ -284,17 +275,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes check-pop {
|
||||
0% {
|
||||
transform: scale(0.8);
|
||||
opacity: 0;
|
||||
/* A highlight sweeps across "Thinking..." text (Shimmer) */
|
||||
@keyframes shimmer {
|
||||
from {
|
||||
background-position: 100% center;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
to {
|
||||
background-position: 0% center;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,15 +294,15 @@
|
||||
.animate-panel-in {
|
||||
animation: panelIn 0.32s var(--ease-out) both;
|
||||
}
|
||||
.animate-check-pop {
|
||||
animation: check-pop 0.25s var(--ease-spring) forwards;
|
||||
.animate-shimmer {
|
||||
animation: shimmer var(--shimmer-duration, 2s) linear infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.animate-fade-in,
|
||||
.animate-message-in,
|
||||
.animate-panel-in,
|
||||
.animate-check-pop {
|
||||
.animate-shimmer {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"**",
|
||||
"!public",
|
||||
"!packages/mcp-server/src/preview",
|
||||
"!packages/mcp-server/shell/index.html",
|
||||
"!lib/model-catalog.json"
|
||||
]
|
||||
},
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
import { Cloud } from "lucide-react"
|
||||
import type { ComponentProps, ElementRef, ReactNode } from "react"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
CommandShortcut,
|
||||
} from "@/components/ui/command"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export type ModelSelectorProps = ComponentProps<typeof Dialog>
|
||||
|
||||
export const ModelSelector = (props: ModelSelectorProps) => (
|
||||
<Dialog {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorTriggerProps = ComponentProps<typeof DialogTrigger>
|
||||
|
||||
export const ModelSelectorTrigger = (props: ModelSelectorTriggerProps) => (
|
||||
<DialogTrigger {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorContentProps = ComponentProps<typeof DialogContent> & {
|
||||
title?: ReactNode
|
||||
}
|
||||
|
||||
export const ModelSelectorContent = ({
|
||||
className,
|
||||
children,
|
||||
title = "Model Selector",
|
||||
...props
|
||||
}: ModelSelectorContentProps) => (
|
||||
<DialogContent className={cn("p-0", className)} {...props}>
|
||||
<DialogTitle className="sr-only">{title}</DialogTitle>
|
||||
<Command className="**:data-[slot=command-input-wrapper]:h-auto">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
)
|
||||
|
||||
export type ModelSelectorDialogProps = ComponentProps<typeof CommandDialog>
|
||||
|
||||
export const ModelSelectorDialog = (props: ModelSelectorDialogProps) => (
|
||||
<CommandDialog {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorInputProps = ComponentProps<typeof CommandInput>
|
||||
|
||||
export const ModelSelectorInput = ({
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorInputProps) => (
|
||||
<CommandInput className={cn("h-auto py-3.5", className)} {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorListProps = ComponentProps<typeof CommandList>
|
||||
|
||||
export const ModelSelectorList = ({
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorListProps) => {
|
||||
const listRef = useRef<ElementRef<typeof CommandList>>(null)
|
||||
const [showShadow, setShowShadow] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const listElement = listRef.current
|
||||
if (!listElement) return
|
||||
|
||||
const checkScroll = () => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = listElement
|
||||
// Show shadow if there is more content below
|
||||
// Using a small threshold to handle fractional pixel rendering
|
||||
setShowShadow(
|
||||
scrollHeight > Math.ceil(scrollTop + clientHeight) + 1,
|
||||
)
|
||||
}
|
||||
|
||||
// Initial check
|
||||
checkScroll()
|
||||
|
||||
// Event listeners
|
||||
listElement.addEventListener("scroll", checkScroll)
|
||||
window.addEventListener("resize", checkScroll)
|
||||
|
||||
// Observe content changes (e.g. async loading of items)
|
||||
const observer = new MutationObserver(checkScroll)
|
||||
observer.observe(listElement, { childList: true, subtree: true })
|
||||
|
||||
return () => {
|
||||
listElement.removeEventListener("scroll", checkScroll)
|
||||
window.removeEventListener("resize", checkScroll)
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<CommandList
|
||||
ref={listRef}
|
||||
className={cn(
|
||||
// Hide scrollbar on all platforms
|
||||
"[&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
{/* Bottom shadow indicator for scrollable content */}
|
||||
<div
|
||||
className={cn(
|
||||
"pointer-events-none absolute bottom-0 left-0 right-0 h-12 bg-gradient-to-t from-muted/80 via-muted/40 to-transparent transition-opacity duration-200",
|
||||
showShadow ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export type ModelSelectorEmptyProps = ComponentProps<typeof CommandEmpty>
|
||||
|
||||
export const ModelSelectorEmpty = (props: ModelSelectorEmptyProps) => (
|
||||
<CommandEmpty {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorGroupProps = ComponentProps<typeof CommandGroup>
|
||||
|
||||
export const ModelSelectorGroup = (props: ModelSelectorGroupProps) => (
|
||||
<CommandGroup {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorItemProps = ComponentProps<typeof CommandItem>
|
||||
|
||||
export const ModelSelectorItem = (props: ModelSelectorItemProps) => (
|
||||
<CommandItem {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorShortcutProps = ComponentProps<typeof CommandShortcut>
|
||||
|
||||
export const ModelSelectorShortcut = (props: ModelSelectorShortcutProps) => (
|
||||
<CommandShortcut {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorSeparatorProps = ComponentProps<
|
||||
typeof CommandSeparator
|
||||
>
|
||||
|
||||
export const ModelSelectorSeparator = (props: ModelSelectorSeparatorProps) => (
|
||||
<CommandSeparator {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorLogoProps = Omit<
|
||||
ComponentProps<"img">,
|
||||
"src" | "alt"
|
||||
> & {
|
||||
provider: string
|
||||
}
|
||||
|
||||
export const ModelSelectorLogo = ({
|
||||
provider,
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorLogoProps) => {
|
||||
// Use Lucide icon for bedrock since models.dev doesn't have a good AWS icon
|
||||
if (provider === "amazon-bedrock") {
|
||||
return <Cloud className={cn("size-4", className)} />
|
||||
}
|
||||
|
||||
return (
|
||||
// biome-ignore lint/performance/noImgElement: External URL from models.dev
|
||||
<img
|
||||
{...props}
|
||||
alt={`${provider} logo`}
|
||||
className={cn("size-4 dark:invert", className)}
|
||||
height={16}
|
||||
src={`https://models.dev/logos/${provider}.svg`}
|
||||
width={16}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export type ModelSelectorLogoGroupProps = ComponentProps<"div">
|
||||
|
||||
export const ModelSelectorLogoGroup = ({
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorLogoGroupProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"-space-x-1 flex shrink-0 items-center [&>img]:rounded-full [&>img]:bg-background [&>img]:p-px [&>img]:ring-1 dark:[&>img]:bg-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
export type ModelSelectorNameProps = ComponentProps<"span">
|
||||
|
||||
export const ModelSelectorName = ({
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorNameProps) => (
|
||||
<span className={cn("flex-1 truncate text-left", className)} {...props} />
|
||||
)
|
||||
|
||||
export type ModelSelectorSectionHeaderProps = {
|
||||
icon: ReactNode
|
||||
label: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const ModelSelectorSectionHeader = ({
|
||||
icon,
|
||||
label,
|
||||
className,
|
||||
}: ModelSelectorSectionHeaderProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/40 rounded-sm mx-1 mt-1",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="[&>svg]:size-3.5" aria-hidden="true">
|
||||
{icon}
|
||||
</span>
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
)
|
||||
@@ -1,66 +1,36 @@
|
||||
"use client"
|
||||
|
||||
import { useControllableState } from "@radix-ui/react-use-controllable-state"
|
||||
import { BrainIcon, ChevronDownIcon } from "lucide-react"
|
||||
import type { ComponentProps, ReactNode } from "react"
|
||||
import { createContext, memo, useContext, useEffect, useState } from "react"
|
||||
import type { ReactNode } from "react"
|
||||
import { useEffect, useState } from "react"
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Shimmer } from "./shimmer"
|
||||
|
||||
type ReasoningContextValue = {
|
||||
isStreaming: boolean
|
||||
isOpen: boolean
|
||||
setIsOpen: (open: boolean) => void
|
||||
duration: number | undefined
|
||||
}
|
||||
|
||||
const ReasoningContext = createContext<ReasoningContextValue | null>(null)
|
||||
|
||||
export const useReasoning = () => {
|
||||
const context = useContext(ReasoningContext)
|
||||
if (!context) {
|
||||
throw new Error("Reasoning components must be used within Reasoning")
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
export type ReasoningProps = ComponentProps<typeof Collapsible> & {
|
||||
export type ReasoningProps = {
|
||||
className?: string
|
||||
isStreaming?: boolean
|
||||
open?: boolean
|
||||
/** Open while streaming, then folds once about a second after it ends */
|
||||
defaultOpen?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
duration?: number
|
||||
getThinkingMessage: (isStreaming: boolean, duration?: number) => ReactNode
|
||||
children: string
|
||||
}
|
||||
|
||||
const AUTO_CLOSE_DELAY = 1000
|
||||
const MS_IN_S = 1000
|
||||
|
||||
export const Reasoning = memo(
|
||||
({
|
||||
export function Reasoning({
|
||||
className,
|
||||
isStreaming = false,
|
||||
open,
|
||||
defaultOpen = true,
|
||||
onOpenChange,
|
||||
duration: durationProp,
|
||||
getThinkingMessage,
|
||||
children,
|
||||
...props
|
||||
}: ReasoningProps) => {
|
||||
const [isOpen, setIsOpen] = useControllableState({
|
||||
prop: open,
|
||||
defaultProp: defaultOpen,
|
||||
onChange: onOpenChange,
|
||||
})
|
||||
const [duration, setDuration] = useControllableState({
|
||||
prop: durationProp,
|
||||
defaultProp: undefined,
|
||||
})
|
||||
|
||||
}: ReasoningProps) {
|
||||
const [isOpen, setIsOpen] = useState(defaultOpen)
|
||||
const [duration, setDuration] = useState<number>()
|
||||
const [hasAutoClosed, setHasAutoClosed] = useState(false)
|
||||
const [startTime, setStartTime] = useState<number | null>(null)
|
||||
|
||||
@@ -74,12 +44,12 @@ export const Reasoning = memo(
|
||||
setDuration(Math.ceil((Date.now() - startTime) / MS_IN_S))
|
||||
setStartTime(null)
|
||||
}
|
||||
}, [isStreaming, startTime, setDuration])
|
||||
}, [isStreaming, startTime])
|
||||
|
||||
// Auto-open when streaming starts, auto-close when streaming ends (once only)
|
||||
// Auto-close once when streaming ends, after a short delay so the user
|
||||
// sees the content
|
||||
useEffect(() => {
|
||||
if (defaultOpen && !isStreaming && isOpen && !hasAutoClosed) {
|
||||
// Add a small delay before closing to allow user to see the content
|
||||
const timer = setTimeout(() => {
|
||||
setIsOpen(false)
|
||||
setHasAutoClosed(true)
|
||||
@@ -87,64 +57,15 @@ export const Reasoning = memo(
|
||||
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [isStreaming, isOpen, defaultOpen, setIsOpen, hasAutoClosed])
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
setIsOpen(newOpen)
|
||||
}
|
||||
}, [isStreaming, isOpen, defaultOpen, hasAutoClosed])
|
||||
|
||||
return (
|
||||
<ReasoningContext.Provider
|
||||
value={{ isStreaming, isOpen, setIsOpen, duration }}
|
||||
>
|
||||
<Collapsible
|
||||
className={cn("not-prose mb-4", className)}
|
||||
onOpenChange={handleOpenChange}
|
||||
onOpenChange={setIsOpen}
|
||||
open={isOpen}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</Collapsible>
|
||||
</ReasoningContext.Provider>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export type ReasoningTriggerProps = ComponentProps<
|
||||
typeof CollapsibleTrigger
|
||||
> & {
|
||||
getThinkingMessage?: (isStreaming: boolean, duration?: number) => ReactNode
|
||||
}
|
||||
|
||||
const defaultGetThinkingMessage = (isStreaming: boolean, duration?: number) => {
|
||||
if (isStreaming || duration === 0) {
|
||||
return <Shimmer duration={1}>Thinking...</Shimmer>
|
||||
}
|
||||
if (duration === undefined) {
|
||||
return <p>Thought for a few seconds</p>
|
||||
}
|
||||
return <p>Thought for {duration} seconds</p>
|
||||
}
|
||||
|
||||
export const ReasoningTrigger = memo(
|
||||
({
|
||||
className,
|
||||
children,
|
||||
getThinkingMessage = defaultGetThinkingMessage,
|
||||
...props
|
||||
}: ReasoningTriggerProps) => {
|
||||
const { isStreaming, isOpen, duration } = useReasoning()
|
||||
|
||||
return (
|
||||
<CollapsibleTrigger
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
<>
|
||||
<CollapsibleTrigger className="flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground">
|
||||
<BrainIcon className="size-4" />
|
||||
{getThinkingMessage(isStreaming, duration)}
|
||||
<ChevronDownIcon
|
||||
@@ -153,34 +74,10 @@ export const ReasoningTrigger = memo(
|
||||
isOpen ? "rotate-180" : "rotate-0",
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CollapsibleTrigger>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export type ReasoningContentProps = ComponentProps<
|
||||
typeof CollapsibleContent
|
||||
> & {
|
||||
children: string
|
||||
}
|
||||
|
||||
export const ReasoningContent = memo(
|
||||
({ className, children, ...props }: ReasoningContentProps) => (
|
||||
<CollapsibleContent
|
||||
className={cn(
|
||||
"mt-4 text-sm",
|
||||
"data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CollapsibleContent className="mt-4 text-sm data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in">
|
||||
<div className="whitespace-pre-wrap">{children}</div>
|
||||
</CollapsibleContent>
|
||||
),
|
||||
)
|
||||
|
||||
Reasoning.displayName = "Reasoning"
|
||||
ReasoningTrigger.displayName = "ReasoningTrigger"
|
||||
ReasoningContent.displayName = "ReasoningContent"
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { motion } from "motion/react"
|
||||
import {
|
||||
type CSSProperties,
|
||||
type ElementType,
|
||||
type JSX,
|
||||
memo,
|
||||
useMemo,
|
||||
} from "react"
|
||||
import { type CSSProperties, type ElementType, memo, useMemo } from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export type TextShimmerProps = {
|
||||
@@ -25,39 +18,29 @@ const ShimmerComponent = ({
|
||||
duration = 2,
|
||||
spread = 2,
|
||||
}: TextShimmerProps) => {
|
||||
const MotionComponent = motion.create(
|
||||
Component as keyof JSX.IntrinsicElements,
|
||||
)
|
||||
|
||||
const dynamicSpread = useMemo(
|
||||
() => (children?.length ?? 0) * spread,
|
||||
[children, spread],
|
||||
)
|
||||
|
||||
return (
|
||||
<MotionComponent
|
||||
animate={{ backgroundPosition: "0% center" }}
|
||||
<Component
|
||||
className={cn(
|
||||
"relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent",
|
||||
"animate-shimmer relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent",
|
||||
"[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",
|
||||
className,
|
||||
)}
|
||||
initial={{ backgroundPosition: "100% center" }}
|
||||
style={
|
||||
{
|
||||
"--spread": `${dynamicSpread}px`,
|
||||
"--shimmer-duration": `${duration}s`,
|
||||
backgroundImage:
|
||||
"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))",
|
||||
} as CSSProperties
|
||||
}
|
||||
transition={{
|
||||
repeat: Number.POSITIVE_INFINITY,
|
||||
duration,
|
||||
ease: "linear",
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</MotionComponent>
|
||||
</Component>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import type { VariantProps } from "class-variance-authority"
|
||||
import type React from "react"
|
||||
import { Button, type buttonVariants } from "@/components/ui/button"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
|
||||
interface ButtonWithTooltipProps
|
||||
extends React.ComponentProps<"button">,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
tooltipContent: string
|
||||
children: React.ReactNode
|
||||
asChild?: boolean
|
||||
}
|
||||
|
||||
export function ButtonWithTooltip({
|
||||
tooltipContent,
|
||||
children,
|
||||
...buttonProps
|
||||
}: ButtonWithTooltipProps) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button {...buttonProps}>{children}</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs text-wrap">
|
||||
{tooltipContent}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
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 { useLocale } from "@/components/canvas/locale-context"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { DRAWIO_CSS, getDrawioSrc } from "@/lib/drawio/drawio-config"
|
||||
import {
|
||||
DRAWIO_CSS,
|
||||
type DrawioSource,
|
||||
getDrawioSrc,
|
||||
webDrawioSource,
|
||||
} 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"
|
||||
@@ -13,28 +16,42 @@ import { cn } from "@/lib/utils"
|
||||
import { useCanvasStore } from "@/stores/canvas-store"
|
||||
import { useSettingsStore } from "@/stores/settings-store"
|
||||
|
||||
/** Size of the canvas area, for overlays that stay inside it */
|
||||
export interface CanvasSize {
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
* an overlay laid over it (the web app's "ask AI" button; only when the
|
||||
* page can drive draw.io directly, not with an external cross-origin
|
||||
* draw.io).
|
||||
*/
|
||||
export function CanvasStage({
|
||||
className,
|
||||
style,
|
||||
hideOverlays = false,
|
||||
overlay,
|
||||
drawioSource,
|
||||
waitForSavedLocale = false,
|
||||
}: {
|
||||
className?: string
|
||||
style?: React.CSSProperties
|
||||
/** Hide the "ask AI" button (e.g. while the start screen covers the canvas) */
|
||||
/** Hide the overlay (e.g. while the start screen covers the canvas) */
|
||||
hideOverlays?: boolean
|
||||
/** Rendered over the canvas once draw.io is ready */
|
||||
overlay?: (size: CanvasSize) => React.ReactNode
|
||||
/** Where the editor comes from; none: the web app's own copy (the MCP
|
||||
* shell passes what its server configured) */
|
||||
drawioSource?: DrawioSource
|
||||
/** Web app: the page is about to switch to the language picked last
|
||||
* time (useSavedLocale in the workspace); do not load draw.io in the
|
||||
* URL's language meanwhile */
|
||||
waitForSavedLocale?: 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 lang = useLocale()
|
||||
const {
|
||||
drawioRef,
|
||||
handleDiagramAutoSave,
|
||||
@@ -43,14 +60,8 @@ export function CanvasStage({
|
||||
resetDrawioReady,
|
||||
isDrawioReady,
|
||||
} = useDiagram()
|
||||
const engine = useChatEngine()
|
||||
const isDark = useSettingsStore((s) => s.isDark)
|
||||
const hasEditor = useCanvasStore((s) => s.hasEditor)
|
||||
// The model sees the first page only, so asking about shapes elsewhere
|
||||
// would change the wrong page
|
||||
const onFirstPage = useCanvasStore(
|
||||
(s) => s.pages.length === 0 || s.pages[0]?.id === s.currentPageId,
|
||||
)
|
||||
// Canvas width when the chat panel starts sliding in or out
|
||||
const slideStartWidthRef = useRef(0)
|
||||
|
||||
@@ -58,20 +69,24 @@ export function CanvasStage({
|
||||
// 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 })
|
||||
const [size, setSize] = useState<CanvasSize>({ 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
|
||||
// Load draw.io once, in the language the page will have
|
||||
if (waitForSavedLocale) {
|
||||
const saved = localStorage.getItem(STORAGE_KEYS.locale)
|
||||
if (saved && saved !== lang && i18n.locales.includes(saved as 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 }))
|
||||
setSrc(getDrawioSrc(drawioSource ?? webDrawioSource(lang), dark))
|
||||
}, [lang])
|
||||
|
||||
// A new iframe starts over: draw.io reports load and access again
|
||||
@@ -87,8 +102,7 @@ export function CanvasStage({
|
||||
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 }))
|
||||
setSrc(getDrawioSrc(drawioSource ?? webDrawioSource(lang), isDark))
|
||||
}, [isDark, editorAccess, lang, src])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -141,8 +155,7 @@ export function CanvasStage({
|
||||
key={src}
|
||||
ref={drawioRef}
|
||||
src={src}
|
||||
configCss={DRAWIO_CSS}
|
||||
editorCss={DRAWIO_CSS}
|
||||
css={DRAWIO_CSS}
|
||||
dark={isDark}
|
||||
onLoad={onDrawioLoad}
|
||||
onAutoSave={handleDiagramAutoSave}
|
||||
@@ -164,13 +177,7 @@ export function CanvasStage({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showOverlays && (
|
||||
<SelectionAsk
|
||||
width={size.width}
|
||||
height={size.height}
|
||||
hidden={engine.isBusy || !onFirstPage}
|
||||
/>
|
||||
)}
|
||||
{showOverlays && overlay?.(size)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { ChevronLeft, ChevronRight, RotateCcw } from "lucide-react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { VersionThumb } from "@/components/canvas/version-card"
|
||||
import { useVersionsContext } from "@/components/canvas/versions-context"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -11,11 +13,8 @@ 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 { describeChangeSummary } 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,
|
||||
@@ -40,12 +39,11 @@ function Sheet({
|
||||
export function CompareDialog() {
|
||||
const dict = useDictionary()
|
||||
const t = dict.versions
|
||||
const engine = useChatEngine()
|
||||
const { versions, isBusy, restore } = useVersionsContext()
|
||||
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)
|
||||
@@ -56,11 +54,11 @@ export function CompareDialog() {
|
||||
() => !version || isSameDocument(version.xml, chartXML),
|
||||
[version, chartXML],
|
||||
)
|
||||
// What the canvas has changed since this version on the first page
|
||||
// (null: nothing there)
|
||||
// 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)
|
||||
const { summary } = diffDiagrams(version.xml, chartXML, version.pageId)
|
||||
return Object.values(summary).some((n) => n > 0) ? summary : null
|
||||
}, [version, chartXML, same])
|
||||
|
||||
@@ -82,7 +80,7 @@ export function CompareDialog() {
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [versionId, engine.isBusy])
|
||||
}, [versionId, isBusy])
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
@@ -98,7 +96,7 @@ export function CompareDialog() {
|
||||
: same
|
||||
? t.isOnCanvas
|
||||
: changes
|
||||
? `${formatMessage(t.compareSince, { n: version.number })} ${describeChanges(changes, t)}`
|
||||
? `${formatMessage(t.compareSince, { n: version.number })} ${describeChangeSummary(changes, t)}`
|
||||
: formatMessage(t.differsElsewhere, {
|
||||
n: version.number,
|
||||
})}
|
||||
@@ -139,10 +137,10 @@ export function CompareDialog() {
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!version || same || engine.isBusy}
|
||||
disabled={!version || same || isBusy}
|
||||
onClick={() => {
|
||||
if (!version) return
|
||||
engine.restoreVersion(version.id)
|
||||
restore(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"
|
||||
@@ -30,10 +30,11 @@ export interface DrawioFrameHandle {
|
||||
|
||||
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
|
||||
/**
|
||||
* Theme CSS: sent with the configure message (works cross-origin too)
|
||||
* and, same origin, injected as a <style> so it updates without a reload
|
||||
*/
|
||||
css: string
|
||||
/** draw.io's dark mode, switched in place when the editor is reachable */
|
||||
dark: boolean
|
||||
onLoad?: () => void
|
||||
@@ -52,25 +53,14 @@ const STYLE_ID = "next-ai-drawio-theme"
|
||||
*/
|
||||
export const DrawioFrame = forwardRef<DrawioFrameHandle, DrawioFrameProps>(
|
||||
function DrawioFrame(
|
||||
{
|
||||
src,
|
||||
configCss,
|
||||
editorCss,
|
||||
dark,
|
||||
onLoad,
|
||||
onAutoSave,
|
||||
onExport,
|
||||
onEditorAccess,
|
||||
},
|
||||
{ src, css, 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 cssRef = useRef(css)
|
||||
cssRef.current = css
|
||||
const darkRef = useRef(dark)
|
||||
darkRef.current = dark
|
||||
// Handlers change on every render; the message listener reads refs
|
||||
@@ -111,7 +101,7 @@ export const DrawioFrame = forwardRef<DrawioFrameHandle, DrawioFrameProps>(
|
||||
style.id = STYLE_ID
|
||||
doc.head.appendChild(style)
|
||||
}
|
||||
style.textContent = editorCssRef.current
|
||||
style.textContent = cssRef.current
|
||||
} catch {
|
||||
// Cross-origin: the configure message already applied it
|
||||
}
|
||||
@@ -119,7 +109,7 @@ export const DrawioFrame = forwardRef<DrawioFrameHandle, DrawioFrameProps>(
|
||||
|
||||
useEffect(() => {
|
||||
applyThemeCss()
|
||||
}, [editorCss])
|
||||
}, [css])
|
||||
|
||||
// Same-origin only: draw.io's own dark mode, without a reload
|
||||
const applyDarkMode = () => {
|
||||
@@ -209,7 +199,7 @@ export const DrawioFrame = forwardRef<DrawioFrameHandle, DrawioFrameProps>(
|
||||
send("configure", {
|
||||
config: {
|
||||
...DRAWIO_CONFIG,
|
||||
css: configCssRef.current,
|
||||
css: cssRef.current,
|
||||
},
|
||||
})
|
||||
break
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useContext } from "react"
|
||||
import type { Locale } from "@/lib/i18n/config"
|
||||
|
||||
const LocaleContext = createContext<Locale | null>(null)
|
||||
|
||||
/** The page's language; the web layout feeds it from its route param */
|
||||
export function LocaleProvider({
|
||||
locale,
|
||||
children,
|
||||
}: {
|
||||
locale: Locale
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<LocaleContext.Provider value={locale}>
|
||||
{children}
|
||||
</LocaleContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useLocale(): Locale {
|
||||
const locale = useContext(LocaleContext)
|
||||
if (!locale) {
|
||||
throw new Error("useLocale must be used within a LocaleProvider")
|
||||
}
|
||||
return locale
|
||||
}
|
||||
@@ -10,25 +10,25 @@ 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.
|
||||
* Hidden while an answer is changing the canvas.
|
||||
*/
|
||||
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 isBusy = useCanvasStore((s) => s.isBusy)
|
||||
const focusComposer = useUiStore((s) => s.focusComposer)
|
||||
|
||||
if (hidden || popupOpen || !rect || selection.length === 0 || isFreehand) {
|
||||
if (isBusy || popupOpen || !rect || selection.length === 0 || isFreehand) {
|
||||
return null
|
||||
}
|
||||
// Selection scrolled out of view
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { Redo2, RotateCcw, Undo2 } from "lucide-react"
|
||||
import { Shimmer } from "@/components/ai-elements/shimmer"
|
||||
import {
|
||||
useVersionsContext,
|
||||
type VersionItem,
|
||||
} from "@/components/canvas/versions-context"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { describeChangeSummary, describeTotals } from "@/lib/version-text"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
|
||||
/** 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>
|
||||
)
|
||||
}
|
||||
|
||||
interface VersionCardProps extends React.ComponentProps<"div"> {
|
||||
version: VersionItem
|
||||
/** The newest version shows its picture; older ones fold into one row */
|
||||
isLatest: boolean
|
||||
/** What happened ("Drew the diagram"); an undone change says so instead */
|
||||
label: string
|
||||
/** Goes after the summary text (the chat adds its "Show XML" link) */
|
||||
afterSummary?: React.ReactNode
|
||||
/** Panel below the card (the chat shows the AI's XML there) */
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Card for one diagram version: picture, number, label, what changed, and
|
||||
* the action (undo or redo on the latest, restore on older ones). The
|
||||
* picture opens Compare. Other attributes go on the card's element.
|
||||
*/
|
||||
export function VersionCard({
|
||||
version,
|
||||
isLatest,
|
||||
label,
|
||||
afterSummary,
|
||||
children,
|
||||
className,
|
||||
...rest
|
||||
}: VersionCardProps) {
|
||||
const t = useDictionary().versions
|
||||
const source = useVersionsContext()
|
||||
const openCompare = useUiStore((s) => s.openCompare)
|
||||
|
||||
const isUndone = source.undoneId === version.id
|
||||
const isOnCanvas = source.onCanvasId === version.id
|
||||
const title = isUndone ? t.undone : label
|
||||
const summary = version.fromScratch
|
||||
? describeTotals(version.summary, t)
|
||||
: describeChangeSummary(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={source.isBusy || isOnCanvas}
|
||||
onClick={() => source.restore(version.id)}
|
||||
className={actionClass}
|
||||
data-testid="version-restore"
|
||||
>
|
||||
<RotateCcw className="size-3.5" />
|
||||
{formatMessage(t.restoreVersion, { n: version.number })}
|
||||
</button>
|
||||
)
|
||||
const summaryLine = (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{summary}
|
||||
{afterSummary}
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!isLatest) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden rounded-xl border border-border bg-card",
|
||||
className,
|
||||
)}
|
||||
data-testid="version-card"
|
||||
{...rest}
|
||||
>
|
||||
<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>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Undo and redo belong 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 = source.canUndo || source.canRedo
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden rounded-xl border border-border bg-card",
|
||||
isOnCanvas && "border-foreground/15",
|
||||
className,
|
||||
)}
|
||||
data-testid="version-card"
|
||||
{...rest}
|
||||
>
|
||||
<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={source.isBusy}
|
||||
onClick={() =>
|
||||
source.canRedo ? source.redo() : source.undo()
|
||||
}
|
||||
className={actionClass}
|
||||
data-testid="version-undo"
|
||||
>
|
||||
{source.canRedo ? (
|
||||
<Redo2 className="size-3.5" />
|
||||
) : (
|
||||
<Undo2 className="size-3.5" />
|
||||
)}
|
||||
{source.canRedo ? t.redo : t.undo}
|
||||
</button>
|
||||
) : (
|
||||
restoreButton
|
||||
)}
|
||||
<div className="col-span-2 col-start-2 mt-0.5">
|
||||
{summaryLine}
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +1,20 @@
|
||||
import { useEffect, useRef } from "react"
|
||||
import { useVersionsContext } from "@/components/canvas/versions-context"
|
||||
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() {
|
||||
export function VersionStrip({
|
||||
minVersions = 2,
|
||||
}: {
|
||||
/** Hidden below this many versions: one version alone adds nothing to
|
||||
* its card, unless the caller knows there is no card for it */
|
||||
minVersions?: number
|
||||
}) {
|
||||
const dict = useDictionary()
|
||||
const versions = useVersionsStore((s) => s.versions)
|
||||
const onCanvasVersionId = useVersionsStore((s) => s.onCanvasVersionId)
|
||||
const { versions, onCanvasId } = useVersionsContext()
|
||||
const openCompare = useUiStore((s) => s.openCompare)
|
||||
const engine = useChatEngine()
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Keep the newest version in view
|
||||
@@ -20,24 +23,7 @@ export function VersionStrip() {
|
||||
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
|
||||
if (versions.length < minVersions) return null
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 border-b border-border px-3.5 pt-1 pb-3">
|
||||
@@ -49,13 +35,13 @@ export function VersionStrip() {
|
||||
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
|
||||
const isCurrent = version.id === onCanvasId
|
||||
return (
|
||||
<button
|
||||
key={version.id}
|
||||
type="button"
|
||||
onClick={() => openCompare(version.id)}
|
||||
title={`v${version.number}${version.id === onCanvasVersionId ? ` · ${dict.versions.currentCanvas}` : ""}`}
|
||||
title={`v${version.number}${isCurrent ? ` · ${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
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useContext } from "react"
|
||||
import type { ChangeSummary } from "@/lib/diagram-diff"
|
||||
|
||||
/** One saved state of the diagram, as the version card and the compare
|
||||
* dialog show it */
|
||||
export interface VersionItem {
|
||||
id: string
|
||||
/** Shown as v{number} */
|
||||
number: number
|
||||
/** Full multi-page document */
|
||||
xml: string
|
||||
/** The page the change was made on; none: the first page */
|
||||
pageId?: string
|
||||
/** Document before the change, when it is known */
|
||||
beforeXml?: string
|
||||
/** SVG data URL thumbnail; undefined: still being made; "": none could
|
||||
* be made */
|
||||
svg?: string
|
||||
summary: ChangeSummary
|
||||
/** Drawn on an empty canvas (the card shows totals, not changes) */
|
||||
fromScratch?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the versions come from and what can be done with them. The web app
|
||||
* fills it from the chat's version store; the MCP shell from the server's
|
||||
* history.
|
||||
*/
|
||||
export interface VersionsSource {
|
||||
versions: VersionItem[]
|
||||
/** The version the canvas shows now, or null (hand edits, undone) */
|
||||
onCanvasId: string | null
|
||||
/** The latest version, when its change was undone */
|
||||
undoneId: string | null
|
||||
/** Something is changing the canvas: version actions wait */
|
||||
isBusy: boolean
|
||||
/** The latest version's change can be undone */
|
||||
canUndo: boolean
|
||||
/** The latest version's change was undone and can be put back */
|
||||
canRedo: boolean
|
||||
restore: (id: string) => void
|
||||
undo: () => void
|
||||
redo: () => void
|
||||
}
|
||||
|
||||
const VersionsContext = createContext<VersionsSource | null>(null)
|
||||
|
||||
export function VersionsProvider({
|
||||
value,
|
||||
children,
|
||||
}: {
|
||||
value: VersionsSource
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<VersionsContext.Provider value={value}>
|
||||
{children}
|
||||
</VersionsContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useVersionsContext(): VersionsSource {
|
||||
const source = useContext(VersionsContext)
|
||||
if (!source) {
|
||||
throw new Error(
|
||||
"useVersionsContext must be used within a VersionsProvider",
|
||||
)
|
||||
}
|
||||
return source
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { Bookmark, Plus } from "lucide-react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import {
|
||||
createTemplate,
|
||||
type TemplateCreateInput,
|
||||
} from "@/lib/template-storage"
|
||||
|
||||
interface TemplateCreateDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSuccess: () => void
|
||||
initialPrompt?: string
|
||||
}
|
||||
|
||||
export function TemplateCreateDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
initialPrompt = "",
|
||||
}: TemplateCreateDialogProps) {
|
||||
const dict = useDictionary()
|
||||
const [title, setTitle] = useState("")
|
||||
const [description, setDescription] = useState("")
|
||||
const [prompt, setPrompt] = useState("")
|
||||
const [pinned, setPinned] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// Reset form when dialog opens with the latest initialPrompt
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setTitle("")
|
||||
setDescription("")
|
||||
setPrompt(initialPrompt)
|
||||
setPinned(false)
|
||||
setError(null)
|
||||
}
|
||||
}, [open, initialPrompt])
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
// React submit events bubble through the portal; keep them away from
|
||||
// the chat form this dialog may be rendered in
|
||||
e.stopPropagation()
|
||||
|
||||
const trimmedPrompt = prompt.trim()
|
||||
if (!trimmedPrompt) {
|
||||
setError(dict.templates.promptRequired)
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const input: TemplateCreateInput = {
|
||||
prompt: trimmedPrompt,
|
||||
title: title.trim() || undefined,
|
||||
description: description.trim() || undefined,
|
||||
pinned,
|
||||
}
|
||||
|
||||
const template = await createTemplate(input)
|
||||
if (template) {
|
||||
onSuccess()
|
||||
onOpenChange(false)
|
||||
} else {
|
||||
setError(dict.templates.createFailed)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to create template:", err)
|
||||
setError(dict.templates.createFailed)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px] overflow-hidden">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Plus className="w-5 h-5" />
|
||||
{dict.templates.createTitle}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{dict.templates.createDescription}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{/* Prompt field - required */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="prompt" className="text-foreground">
|
||||
{dict.templates.promptLabel}
|
||||
<span className="text-destructive ml-1">*</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="prompt"
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
placeholder={dict.templates.promptPlaceholder}
|
||||
className="min-h-[100px] resize-none break-words"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Title field - optional */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="title" className="text-foreground">
|
||||
{dict.templates.titleLabel}
|
||||
</Label>
|
||||
<Input
|
||||
id="title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder={dict.templates.titlePlaceholder}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.templates.titleHint}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Description field - optional */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="description"
|
||||
className="text-foreground"
|
||||
>
|
||||
{dict.templates.descriptionLabel}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder={
|
||||
dict.templates.descriptionPlaceholder
|
||||
}
|
||||
className="min-h-[60px] resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Pinned switch */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label
|
||||
htmlFor="pinned"
|
||||
className="flex items-center gap-2 text-foreground"
|
||||
>
|
||||
<Bookmark className="w-4 h-4" />
|
||||
{dict.templates.pinnedLabel}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dict.templates.pinnedHint}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="pinned"
|
||||
checked={pinned}
|
||||
onCheckedChange={setPinned}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Error message */}
|
||||
{error && (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{dict.common.cancel}
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting
|
||||
? dict.common.loading
|
||||
: dict.templates.createButton}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { Bookmark, Edit2 } from "lucide-react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { Bookmark, Edit2, Plus } from "lucide-react"
|
||||
import { useEffect, useId, useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -16,22 +16,32 @@ import { Label } from "@/components/ui/label"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { type Template, updateTemplate } from "@/lib/template-storage"
|
||||
import {
|
||||
createTemplate,
|
||||
type Template,
|
||||
updateTemplate,
|
||||
} from "@/lib/template-storage"
|
||||
|
||||
interface TemplateEditDialogProps {
|
||||
interface TemplateFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
template: Template | null
|
||||
onSuccess: () => void
|
||||
/** The template to edit; without one the dialog creates a new template */
|
||||
template?: Template | null
|
||||
initialPrompt?: string
|
||||
}
|
||||
|
||||
export function TemplateEditDialog({
|
||||
// One form for creating and editing a template
|
||||
export function TemplateFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
template,
|
||||
onSuccess,
|
||||
}: TemplateEditDialogProps) {
|
||||
template,
|
||||
initialPrompt = "",
|
||||
}: TemplateFormDialogProps) {
|
||||
const dict = useDictionary()
|
||||
const id = useId()
|
||||
const isEdit = !!template
|
||||
const [title, setTitle] = useState("")
|
||||
const [description, setDescription] = useState("")
|
||||
const [prompt, setPrompt] = useState("")
|
||||
@@ -39,32 +49,22 @@ export function TemplateEditDialog({
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// Populate form each time the dialog opens, dropping any cancelled edits
|
||||
// Fill the form each time the dialog opens, dropping cancelled edits
|
||||
useEffect(() => {
|
||||
if (open && template) {
|
||||
setTitle(template.title || "")
|
||||
setDescription(template.description || "")
|
||||
setPrompt(template.prompt || "")
|
||||
setPinned(template.pinned || false)
|
||||
if (!open) return
|
||||
setTitle(template?.title || "")
|
||||
setDescription(template?.description || "")
|
||||
setPrompt(template ? template.prompt || "" : initialPrompt)
|
||||
setPinned(template?.pinned || false)
|
||||
setError(null)
|
||||
}
|
||||
}, [open, template])
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (!newOpen) {
|
||||
setError(null)
|
||||
}
|
||||
onOpenChange(newOpen)
|
||||
}
|
||||
}, [open, template, initialPrompt])
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
// React submit events bubble through the portal; keep them away from
|
||||
// any form this dialog may be rendered in
|
||||
// the chat form this dialog may be rendered in
|
||||
e.stopPropagation()
|
||||
|
||||
if (!template) return
|
||||
|
||||
const trimmedPrompt = prompt.trim()
|
||||
if (!trimmedPrompt) {
|
||||
setError(dict.templates.promptRequired)
|
||||
@@ -74,40 +74,59 @@ export function TemplateEditDialog({
|
||||
setIsSubmitting(true)
|
||||
setError(null)
|
||||
|
||||
const failed = isEdit
|
||||
? dict.templates.updateFailed
|
||||
: dict.templates.createFailed
|
||||
try {
|
||||
const updates: Partial<Omit<Template, "id" | "createdAt">> = {
|
||||
const fields = {
|
||||
prompt: trimmedPrompt,
|
||||
title: title.trim() || template.title,
|
||||
description: description.trim() || undefined,
|
||||
pinned,
|
||||
}
|
||||
|
||||
const updated = await updateTemplate(template.id, updates)
|
||||
if (updated) {
|
||||
// An emptied title keeps the old one when editing; a new template
|
||||
// gets a default title from its prompt
|
||||
const result = template
|
||||
? await updateTemplate(template.id, {
|
||||
...fields,
|
||||
title: title.trim() || template.title,
|
||||
})
|
||||
: await createTemplate({
|
||||
...fields,
|
||||
title: title.trim() || undefined,
|
||||
})
|
||||
if (result) {
|
||||
onSuccess()
|
||||
onOpenChange(false)
|
||||
} else {
|
||||
setError(dict.templates.updateFailed)
|
||||
setError(failed)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to update template:", err)
|
||||
setError(dict.templates.updateFailed)
|
||||
console.error("Failed to save template:", err)
|
||||
setError(failed)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px] overflow-hidden">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{isEdit ? (
|
||||
<Edit2 className="w-5 h-5" />
|
||||
{dict.templates.editTitle}
|
||||
) : (
|
||||
<Plus className="w-5 h-5" />
|
||||
)}
|
||||
{isEdit
|
||||
? dict.templates.editTitle
|
||||
: dict.templates.createTitle}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{dict.templates.editDescription}
|
||||
{isEdit
|
||||
? dict.templates.editDescription
|
||||
: dict.templates.createDescription}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -115,14 +134,14 @@ export function TemplateEditDialog({
|
||||
{/* Prompt field - required */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="edit-prompt"
|
||||
htmlFor={`${id}-prompt`}
|
||||
className="text-foreground"
|
||||
>
|
||||
{dict.templates.promptLabel}
|
||||
<span className="text-destructive ml-1">*</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="edit-prompt"
|
||||
id={`${id}-prompt`}
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
placeholder={dict.templates.promptPlaceholder}
|
||||
@@ -134,13 +153,13 @@ export function TemplateEditDialog({
|
||||
{/* Title field - optional */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="edit-title"
|
||||
htmlFor={`${id}-title`}
|
||||
className="text-foreground"
|
||||
>
|
||||
{dict.templates.titleLabel}
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-title"
|
||||
id={`${id}-title`}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder={dict.templates.titlePlaceholder}
|
||||
@@ -153,13 +172,13 @@ export function TemplateEditDialog({
|
||||
{/* Description field - optional */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="edit-description"
|
||||
htmlFor={`${id}-description`}
|
||||
className="text-foreground"
|
||||
>
|
||||
{dict.templates.descriptionLabel}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="edit-description"
|
||||
id={`${id}-description`}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder={
|
||||
@@ -173,7 +192,7 @@ export function TemplateEditDialog({
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label
|
||||
htmlFor="edit-pinned"
|
||||
htmlFor={`${id}-pinned`}
|
||||
className="flex items-center gap-2 text-foreground"
|
||||
>
|
||||
<Bookmark className="w-4 h-4" />
|
||||
@@ -184,7 +203,7 @@ export function TemplateEditDialog({
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="edit-pinned"
|
||||
id={`${id}-pinned`}
|
||||
checked={pinned}
|
||||
onCheckedChange={setPinned}
|
||||
/>
|
||||
@@ -208,7 +227,9 @@ export function TemplateEditDialog({
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting
|
||||
? dict.common.loading
|
||||
: dict.common.save}
|
||||
: isEdit
|
||||
? dict.common.save
|
||||
: dict.templates.createButton}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Trash2,
|
||||
Upload,
|
||||
} from "lucide-react"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useCallback, useEffect, useRef, useState } from "react"
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -23,63 +24,33 @@ import {
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatRelativeTime } from "@/lib/relative-time"
|
||||
import {
|
||||
deleteTemplate,
|
||||
duplicateTemplate,
|
||||
exportTemplates,
|
||||
getAllTemplates,
|
||||
importTemplates,
|
||||
incrementClickCount,
|
||||
incrementRunCount,
|
||||
searchTemplates,
|
||||
type Template,
|
||||
updateTemplate,
|
||||
validateImportData,
|
||||
} from "@/lib/template-storage"
|
||||
import { TemplateCreateDialog } from "./TemplateCreateDialog"
|
||||
import { TemplateEditDialog } from "./TemplateEditDialog"
|
||||
import { TemplateFormDialog } from "./TemplateFormDialog"
|
||||
|
||||
interface TemplatePanelProps {
|
||||
setInput: (input: string) => void
|
||||
/** Whether it was sent */
|
||||
onSendTemplate?: (template: Template) => Promise<boolean>
|
||||
onSendTemplate: (template: Template) => Promise<boolean>
|
||||
currentInput?: string
|
||||
}
|
||||
|
||||
function formatLastUsed(timestamp: number, neverUsedText: string): string {
|
||||
if (!timestamp) return neverUsedText
|
||||
const now = Date.now()
|
||||
const diffMs = now - timestamp
|
||||
const diffMins = Math.floor(diffMs / (1000 * 60))
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
|
||||
|
||||
try {
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" })
|
||||
if (diffMins < 1) return rtf.format(0, "minute")
|
||||
if (diffMins < 60) return rtf.format(-diffMins, "minute")
|
||||
if (diffHours < 24) return rtf.format(-diffHours, "hour")
|
||||
if (diffDays < 7) return rtf.format(-diffDays, "day")
|
||||
} catch {
|
||||
// Fallback if Intl.RelativeTimeFormat is not available
|
||||
if (diffMins < 1) return "<1m ago"
|
||||
if (diffMins < 60) return `${diffMins}m ago`
|
||||
if (diffHours < 24) return `${diffHours}h ago`
|
||||
if (diffDays < 7) return `${diffDays}d ago`
|
||||
}
|
||||
|
||||
return new Date(timestamp).toLocaleDateString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
}
|
||||
|
||||
export function TemplatePanel({
|
||||
setInput,
|
||||
onSendTemplate,
|
||||
currentInput = "",
|
||||
}: TemplatePanelProps) {
|
||||
const dict = useDictionary()
|
||||
const params = useParams<{ lang: string }>()
|
||||
const [templates, setTemplates] = useState<Template[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [createDialogOpen, setCreateDialogOpen] = useState(false)
|
||||
@@ -111,10 +82,6 @@ export function TemplatePanel({
|
||||
|
||||
useEffect(() => {
|
||||
loadTemplates()
|
||||
// Reload when a template is saved elsewhere, e.g. from the chat input
|
||||
window.addEventListener("templatesChanged", loadTemplates)
|
||||
return () =>
|
||||
window.removeEventListener("templatesChanged", loadTemplates)
|
||||
}, [loadTemplates])
|
||||
|
||||
const handleCreateSuccess = () => {
|
||||
@@ -133,7 +100,7 @@ export function TemplatePanel({
|
||||
const handleDuplicate = async (template: Template) => {
|
||||
const duplicated = await duplicateTemplate(
|
||||
template.id,
|
||||
dict.templates.copySuffix || "(copy)",
|
||||
dict.templates.copySuffix,
|
||||
)
|
||||
if (duplicated) {
|
||||
loadTemplates()
|
||||
@@ -179,24 +146,14 @@ export function TemplatePanel({
|
||||
|
||||
// Actually send the template
|
||||
const sendTemplate = async (template: Template) => {
|
||||
if (onSendTemplate) {
|
||||
// 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) {
|
||||
// A run only when it was sent (not while a message is still being
|
||||
// sent, or attachments read)
|
||||
if (await onSendTemplate(template)) {
|
||||
// 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)
|
||||
}
|
||||
setConfirmSendDialogOpen(false)
|
||||
setTemplateToSend(null)
|
||||
}
|
||||
@@ -218,7 +175,7 @@ export function TemplatePanel({
|
||||
if (templates.length === 0) {
|
||||
setImportMessage({
|
||||
type: "error",
|
||||
text: dict.templates.exportEmpty || "No templates to export",
|
||||
text: dict.templates.exportEmpty,
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -260,8 +217,7 @@ export function TemplatePanel({
|
||||
if (!file) {
|
||||
setImportMessage({
|
||||
type: "error",
|
||||
text:
|
||||
dict.templates.importNoFile || "Please select a JSON file",
|
||||
text: dict.templates.importNoFile,
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -370,7 +326,7 @@ export function TemplatePanel({
|
||||
<div className="mt-3">{importMessageBox}</div>
|
||||
)}
|
||||
|
||||
<TemplateCreateDialog
|
||||
<TemplateFormDialog
|
||||
open={createDialogOpen}
|
||||
onOpenChange={setCreateDialogOpen}
|
||||
onSuccess={handleCreateSuccess}
|
||||
@@ -500,7 +456,7 @@ export function TemplatePanel({
|
||||
<div className="relative shrink-0">
|
||||
<div className="text-[11px] text-muted-foreground whitespace-nowrap group-hover:invisible">
|
||||
{template.runCount > 0
|
||||
? `${dict.templates.usedCount.replace("{count}", String(template.runCount))} · ${formatLastUsed(template.lastUsedAt, dict.templates.neverUsed)}`
|
||||
? `${dict.templates.usedCount.replace("{count}", String(template.runCount))} · ${template.lastUsedAt ? formatRelativeTime(template.lastUsedAt, params.lang, dict.sessionHistory.justNow) : dict.templates.neverUsed}`
|
||||
: dict.templates.neverUsed}
|
||||
</div>
|
||||
<div className="absolute inset-0 flex items-center justify-end gap-0.5 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">
|
||||
@@ -517,10 +473,8 @@ export function TemplatePanel({
|
||||
}`}
|
||||
title={
|
||||
template.pinned
|
||||
? dict.templates
|
||||
.unpin || "Unpin"
|
||||
: dict.templates.pin ||
|
||||
"Pin"
|
||||
? dict.templates.unpin
|
||||
: dict.templates.pin
|
||||
}
|
||||
>
|
||||
<Bookmark
|
||||
@@ -545,10 +499,7 @@ export function TemplatePanel({
|
||||
handleDuplicate(template)
|
||||
}}
|
||||
className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-all"
|
||||
title={
|
||||
dict.templates.duplicate ||
|
||||
"Duplicate"
|
||||
}
|
||||
title={dict.templates.duplicate}
|
||||
>
|
||||
<Copy className="w-4 h-4" />
|
||||
</button>
|
||||
@@ -570,13 +521,13 @@ export function TemplatePanel({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TemplateCreateDialog
|
||||
<TemplateFormDialog
|
||||
open={createDialogOpen}
|
||||
onOpenChange={setCreateDialogOpen}
|
||||
onSuccess={handleCreateSuccess}
|
||||
/>
|
||||
|
||||
<TemplateEditDialog
|
||||
<TemplateFormDialog
|
||||
open={editDialogOpen}
|
||||
onOpenChange={setEditDialogOpen}
|
||||
template={templateToEdit}
|
||||
@@ -591,12 +542,10 @@ export function TemplatePanel({
|
||||
<AlertDialogContent className="max-w-sm">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{dict.templates.deleteTitle ||
|
||||
"Delete this template?"}
|
||||
{dict.templates.deleteTitle}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{dict.templates.deleteDescription ||
|
||||
"This will permanently delete this template. This action cannot be undone."}
|
||||
{dict.templates.deleteDescription}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@@ -621,12 +570,10 @@ export function TemplatePanel({
|
||||
<AlertDialogContent className="max-w-sm">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{dict.templates.confirmSendTitle ||
|
||||
"Replace current input?"}
|
||||
{dict.templates.confirmSendTitle}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{dict.templates.confirmSendDescription ||
|
||||
"You have unsent content in the input. Sending this template will replace it."}
|
||||
{dict.templates.confirmSendDescription}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@@ -634,8 +581,7 @@ export function TemplatePanel({
|
||||
{dict.common.cancel}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleConfirmSend}>
|
||||
{dict.templates.confirmSendButton ||
|
||||
"Send Template"}
|
||||
{dict.templates.confirmSendButton}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -16,7 +16,6 @@ import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import type { ValidationResult } from "@/lib/diagram-validator"
|
||||
|
||||
export type ValidationStatus =
|
||||
| "idle"
|
||||
| "capturing"
|
||||
| "validating"
|
||||
| "success"
|
||||
@@ -159,13 +158,10 @@ export function ValidationCard({
|
||||
color: "text-gray-600 bg-gray-50",
|
||||
icon: <Check className="h-4 w-4" aria-hidden="true" />,
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const statusDisplay = getStatusDisplay()
|
||||
if (!statusDisplay || state.status === "idle") return null
|
||||
|
||||
return (
|
||||
<div className="my-3 rounded-xl border border-border/60 bg-muted/30 overflow-hidden">
|
||||
|
||||
+52
-120
@@ -23,10 +23,7 @@ import { flushSync } from "react-dom"
|
||||
import { toast } from "sonner"
|
||||
import type { ValidationState } from "@/components/chat/ValidationCard"
|
||||
import { useDiagram } from "@/contexts/diagram-context"
|
||||
import {
|
||||
keepFileVars,
|
||||
useDiagramToolHandlers,
|
||||
} from "@/hooks/use-diagram-tool-handlers"
|
||||
import { useDiagramToolHandlers } from "@/hooks/use-diagram-tool-handlers"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import {
|
||||
getSelectedAIConfig,
|
||||
@@ -34,7 +31,6 @@ import {
|
||||
useModelConfig,
|
||||
} from "@/hooks/use-model-config"
|
||||
import {
|
||||
getSessionVersions,
|
||||
type SessionData,
|
||||
useSessionManager,
|
||||
} from "@/hooks/use-session-manager"
|
||||
@@ -42,6 +38,7 @@ import { useValidateDiagram } from "@/hooks/use-validate-diagram"
|
||||
import { getApiEndpoint } from "@/lib/base-path"
|
||||
import { findCachedResponse } from "@/lib/cached-responses"
|
||||
import { buildChatHeaders } from "@/lib/chat-request"
|
||||
import { pageModelXml, placeOnPage } from "@/lib/diagram-pages"
|
||||
import { EMPTY_DRAWIO_DOCUMENT } from "@/lib/drawio/drawio-config"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
import { isPdfFile, isTextFile } from "@/lib/pdf-utils"
|
||||
@@ -90,15 +87,20 @@ function hasToolErrors(messages: UIMessage[]): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshots keep the full multi-page document, but the model only sees and
|
||||
* edits the first page, so give it the first page's mxGraphModel.
|
||||
* Older snapshots already hold a single mxGraphModel and are returned as is.
|
||||
* Snapshots keep the full multi-page document, but the model sees and
|
||||
* edits one page, the one the user is viewing (the first when unknown), so
|
||||
* give it that page's mxGraphModel. Older snapshots already hold a single
|
||||
* mxGraphModel and are returned as is.
|
||||
*/
|
||||
function getFirstPageXml(xml: string): string {
|
||||
function getPageXml(xml: string, pageId: string | null): string {
|
||||
if (!xml.includes("<mxfile")) return xml
|
||||
const doc = new DOMParser().parseFromString(xml, "text/xml")
|
||||
const model = doc.querySelector("diagram")?.querySelector("mxGraphModel")
|
||||
return model ? formatXML(new XMLSerializer().serializeToString(model)) : xml
|
||||
const model = pageModelXml(xml, pageId)
|
||||
return model ? formatXML(model) : xml
|
||||
}
|
||||
|
||||
/** The page the user is viewing; null with an external draw.io */
|
||||
function viewedPageId(): string | null {
|
||||
return useCanvasStore.getState().currentPageId
|
||||
}
|
||||
|
||||
// Shapes sent with a user message (also kept in its metadata)
|
||||
@@ -115,31 +117,14 @@ function newLangfuseSessionId() {
|
||||
return `session-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
}
|
||||
|
||||
const XML_PROLOG =
|
||||
/^(?:\s|<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!DOCTYPE[^>[]*(?:\[[\s\S]*?\])?\s*>)*/i
|
||||
|
||||
/**
|
||||
* Read the diagram document out of a .drawio, .xml or .drawio.svg file, with
|
||||
* its pages inflated: previews and the model read it before draw.io saves
|
||||
* it again. A broken or cut off file gives null.
|
||||
*/
|
||||
async function readDiagramFile(file: File): Promise<string | null> {
|
||||
const raw = await file.text()
|
||||
// What XML allows before the root element: the declaration, comments,
|
||||
// a DOCTYPE (the parser below expects the root first)
|
||||
let text = raw.replace(XML_PROLOG, "")
|
||||
// Editable SVG: the diagram is stored in the root's `content` attribute.
|
||||
// Parsed whole: its DOCTYPE may define entities the content uses.
|
||||
if (/^<(?:[\w.-]+:)?svg[\s>]/i.test(text)) {
|
||||
const doc = new DOMParser().parseFromString(raw, "image/svg+xml")
|
||||
text = (doc.documentElement?.getAttribute("content") ?? "").replace(
|
||||
XML_PROLOG,
|
||||
"",
|
||||
)
|
||||
}
|
||||
const loaded = parseDrawioFileContent(text)
|
||||
if (!loaded.ok) return null
|
||||
return withUniquePageIds(loaded.xml)
|
||||
const loaded = parseDrawioFileContent(await file.text())
|
||||
return loaded.ok ? withUniquePageIds(loaded.xml) : null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -261,11 +246,10 @@ export function ChatEngineProvider({
|
||||
}) {
|
||||
const {
|
||||
loadDiagram: onDisplayChart,
|
||||
handleExport: onExport,
|
||||
exportResolversRef,
|
||||
fetchDiagramXml,
|
||||
chartXML,
|
||||
chartXMLRef: liveChartXMLRef,
|
||||
latestSvg,
|
||||
chartXMLRef,
|
||||
latestSvgRef,
|
||||
clearDiagram,
|
||||
getThumbnailSvg,
|
||||
captureValidationPng,
|
||||
@@ -278,26 +262,10 @@ export function ChatEngineProvider({
|
||||
const searchParams = useSearchParams()
|
||||
const urlSessionId = searchParams.get("session")
|
||||
|
||||
const settings = useSettingsStore()
|
||||
const vlmValidationEnabled = useSettingsStore((s) => s.vlmValidationEnabled)
|
||||
const openSettings = useUiStore((s) => s.openSettings)
|
||||
const focusComposer = useUiStore((s) => s.focusComposer)
|
||||
|
||||
const onFetchChart = () => {
|
||||
// Waits for the reply to its own export, by its tag
|
||||
const tag = onExport()
|
||||
return Promise.race([
|
||||
new Promise<string>((resolve) => {
|
||||
if (tag) exportResolversRef.current[tag] = resolve
|
||||
}),
|
||||
new Promise<string>((_, reject) => {
|
||||
setTimeout(() => {
|
||||
delete exportResolversRef.current[tag]
|
||||
reject(new Error("Chart export timed out after 10 seconds"))
|
||||
}, 10000)
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
const { files, pdfData, handleFileChange, setFiles } = useFileProcessor({
|
||||
tooLong: dict.errors.fileTooLong,
|
||||
readFailed: dict.errors.fileReadFailed,
|
||||
@@ -312,9 +280,6 @@ export function ChatEngineProvider({
|
||||
const sessionManager = useSessionManager({ initialSessionId: urlSessionId })
|
||||
|
||||
const [input, setInputState] = useState("")
|
||||
const [dailyRequestLimit, setDailyRequestLimit] = useState(0)
|
||||
const [dailyTokenLimit, setDailyTokenLimit] = useState(0)
|
||||
const [tpmLimit, setTpmLimit] = useState(0)
|
||||
|
||||
// Restore the unsent input from sessionStorage
|
||||
useEffect(() => {
|
||||
@@ -334,21 +299,7 @@ export function ChatEngineProvider({
|
||||
else sessionStorage.removeItem(SESSION_STORAGE_INPUT_KEY)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetch(getApiEndpoint("/api/config"))
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
setDailyRequestLimit(data.dailyRequestLimit || 0)
|
||||
setDailyTokenLimit(data.dailyTokenLimit || 0)
|
||||
setTpmLimit(data.tpmLimit || 0)
|
||||
})
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
const quotaManager = useQuotaManager({
|
||||
dailyRequestLimit,
|
||||
dailyTokenLimit,
|
||||
tpmLimit,
|
||||
onConfigModel: () => openSettings("models"),
|
||||
})
|
||||
|
||||
@@ -374,6 +325,9 @@ export function ChatEngineProvider({
|
||||
|
||||
// XML snapshot taken before each user message (keyed by message index)
|
||||
const xmlSnapshotsRef = useRef<Map<number, string>>(new Map())
|
||||
// The page the running turn's model reads and writes: the one the user
|
||||
// viewed when the message was sent (null: the first page)
|
||||
const turnPageIdRef = useRef<string | null>(null)
|
||||
// Index of the user message whose turn is running (versions belong to it)
|
||||
const currentTurnRef = useRef(0)
|
||||
// The chat (its generation) the running turn was sent in: a reply that
|
||||
@@ -383,20 +337,12 @@ export function ChatEngineProvider({
|
||||
const hasRestoredRef = useRef(false)
|
||||
const [isRestored, setIsRestored] = useState(false)
|
||||
|
||||
// Latest chartXML for callbacks (avoids stale closures)
|
||||
const chartXMLRef = useRef(chartXML)
|
||||
// Session loaded without a diagram (prevents thumbnail contamination)
|
||||
const justLoadedSessionIdRef = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
chartXMLRef.current = chartXML
|
||||
if (chartXML) justLoadedSessionIdRef.current = null
|
||||
}, [chartXML])
|
||||
|
||||
const latestSvgRef = useRef(latestSvg)
|
||||
useEffect(() => {
|
||||
latestSvgRef.current = latestSvg
|
||||
}, [latestSvg])
|
||||
|
||||
const autoRetryCountRef = useRef(0)
|
||||
const continuationRetryCountRef = useRef(0)
|
||||
// Partial XML when output was truncated; non-empty means continuation mode
|
||||
@@ -449,12 +395,13 @@ export function ChatEngineProvider({
|
||||
processedToolCallsRef,
|
||||
validationRetryCountRef,
|
||||
// A preview undone just before the tool call is in this one already
|
||||
chartXMLRef: liveChartXMLRef,
|
||||
chartXMLRef,
|
||||
turnPageIdRef,
|
||||
onDisplayChart,
|
||||
onFetchChart,
|
||||
onFetchChart: fetchDiagramXml,
|
||||
captureValidationPng,
|
||||
validateDiagram: validateWithFallback,
|
||||
enableVlmValidation: settings.vlmValidationEnabled,
|
||||
enableVlmValidation: vlmValidationEnabled,
|
||||
sessionId: langfuseSessionId,
|
||||
watchStop: () => {
|
||||
const stopsBefore = stopCountRef.current
|
||||
@@ -716,6 +663,11 @@ export function ChatEngineProvider({
|
||||
// isBusy of the latest render, for code that runs after an await
|
||||
const busyRef = useRef(isBusy)
|
||||
busyRef.current = isBusy
|
||||
// Canvas components (version cards, the compare dialog, "ask AI") read
|
||||
// the busy flag from the canvas store
|
||||
useEffect(() => {
|
||||
useCanvasStore.getState().set({ isBusy })
|
||||
}, [isBusy])
|
||||
// The page goes (another language mounts a new one): the answer stops,
|
||||
// so it cannot reach the next page's canvas
|
||||
const stopRef = useRef(stop)
|
||||
@@ -748,6 +700,7 @@ export function ChatEngineProvider({
|
||||
processedToolCallsRef,
|
||||
editDiagramOriginalXmlRef,
|
||||
loadedMessageIdsRef,
|
||||
turnPageIdRef,
|
||||
})
|
||||
|
||||
const { restoreVersion, undoVersion } = useVersions({
|
||||
@@ -762,14 +715,10 @@ export function ChatEngineProvider({
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
const selection = useCanvasStore((s) => s.selection)
|
||||
// The model sees and edits the first page only
|
||||
const onFirstPage = useCanvasStore(
|
||||
(s) => s.pages.length === 0 || s.pages[0]?.id === s.currentPageId,
|
||||
)
|
||||
const [dismissedSelectionKey, setDismissedSelectionKey] = useState("")
|
||||
const selectionKey = selection.map((c) => c.id).join(",")
|
||||
const chatSelection =
|
||||
!onFirstPage || selectionKey === dismissedSelectionKey ? [] : selection
|
||||
selectionKey === dismissedSelectionKey ? [] : selection
|
||||
// Once nothing is selected, picking the same shapes again attaches them
|
||||
useEffect(() => {
|
||||
if (selection.length === 0) setDismissedSelectionKey("")
|
||||
@@ -825,13 +774,7 @@ export function ChatEngineProvider({
|
||||
const messagesBeforeShownRef = useRef<UIMessage[] | null>(null)
|
||||
|
||||
const syncUIWithSession = useCallback(
|
||||
(
|
||||
data:
|
||||
| (SessionData & {
|
||||
diagramHistory?: { svg: string; xml: string }[]
|
||||
})
|
||||
| null,
|
||||
) => {
|
||||
(data: SessionData | null) => {
|
||||
// An answer still coming in belongs to the chat that was on
|
||||
// screen (browser back or forward): it stops, before this chat's
|
||||
// messages are put in its place, so none of it lands here
|
||||
@@ -870,24 +813,15 @@ export function ChatEngineProvider({
|
||||
)
|
||||
setMessages(data.messages as unknown as UIMessage[])
|
||||
xmlSnapshotsRef.current = new Map(data.xmlSnapshots)
|
||||
if (data.diagramXml) {
|
||||
onDisplayChart(data.diagramXml, true)
|
||||
chartXMLRef.current = data.diagramXml
|
||||
} else {
|
||||
clearDiagram()
|
||||
chartXMLRef.current = ""
|
||||
}
|
||||
if (data.diagramXml) onDisplayChart(data.diagramXml, true)
|
||||
else clearDiagram()
|
||||
if (!isRealDiagram(data.diagramXml)) latestSvgRef.current = ""
|
||||
useVersionsStore
|
||||
.getState()
|
||||
.setVersions(getSessionVersions(data))
|
||||
useVersionsStore.getState().setVersions(data.versions ?? [])
|
||||
} else {
|
||||
loadedMessageIdsRef.current = new Set()
|
||||
setMessages([])
|
||||
xmlSnapshotsRef.current.clear()
|
||||
clearDiagram()
|
||||
chartXMLRef.current = ""
|
||||
latestSvgRef.current = ""
|
||||
useVersionsStore.getState().clear()
|
||||
}
|
||||
},
|
||||
@@ -920,7 +854,6 @@ export function ChatEngineProvider({
|
||||
if (isRealDiagram(currentDiagramXml) && options.withThumbnail) {
|
||||
const freshThumb = await getThumbnailSvg()
|
||||
if (freshThumb) {
|
||||
latestSvgRef.current = freshThumb
|
||||
thumbnailDataUrl = freshThumb
|
||||
} else if (latestSvgRef.current) {
|
||||
thumbnailDataUrl = latestSvgRef.current
|
||||
@@ -1178,8 +1111,9 @@ export function ChatEngineProvider({
|
||||
.filter((k) => k < beforeIndex)
|
||||
.sort((a, b) => b - a)
|
||||
return snapshotKeys.length > 0
|
||||
? getFirstPageXml(
|
||||
? getPageXml(
|
||||
xmlSnapshotsRef.current.get(snapshotKeys[0]) || "",
|
||||
viewedPageId(),
|
||||
)
|
||||
: ""
|
||||
}
|
||||
@@ -1198,6 +1132,7 @@ export function ChatEngineProvider({
|
||||
continuationOriginalRef.current = null
|
||||
stoppedRef.current = false
|
||||
currentTurnRef.current = turnIndex
|
||||
turnPageIdRef.current = viewedPageId()
|
||||
turnChatRef.current = getChatGeneration()
|
||||
// Busy from now on, before the next render says so
|
||||
busyRef.current = true
|
||||
@@ -1247,14 +1182,15 @@ export function ChatEngineProvider({
|
||||
selectedCells: MessageSelection = [],
|
||||
generation = getChatGeneration(),
|
||||
): Promise<boolean> => {
|
||||
const chartXml = formatXML(await onFetchChart())
|
||||
const chartXml = formatXML(await fetchDiagramXml())
|
||||
if (getChatGeneration() !== generation || leavingRef.current) {
|
||||
return false
|
||||
}
|
||||
const turnIndex = messagesRef.current.length
|
||||
const previousXml = getPreviousXml(turnIndex)
|
||||
// Snapshot the full multi-page document (kept fresh by autosave) so
|
||||
// regenerate/edit can restore every page; the model gets page 1 only
|
||||
// regenerate/edit can restore every page; the model gets the page
|
||||
// the user is viewing
|
||||
xmlSnapshotsRef.current.set(turnIndex, chartXMLRef.current || chartXml)
|
||||
sendChatMessage(parts, chartXml, previousXml, turnIndex, selectedCells)
|
||||
return true
|
||||
@@ -1328,11 +1264,12 @@ export function ChatEngineProvider({
|
||||
pageName: "Page-1",
|
||||
})
|
||||
if (prepared.ok) {
|
||||
const pageId = viewedPageId()
|
||||
onDisplayChart(
|
||||
keepFileVars(prepared.xml, chartXMLRef.current || ""),
|
||||
placeOnPage(prepared.xml, chartXMLRef.current, pageId),
|
||||
true,
|
||||
"commit",
|
||||
{ toolCallId },
|
||||
{ toolCallId, pageId },
|
||||
)
|
||||
}
|
||||
clearComposer()
|
||||
@@ -1417,8 +1354,8 @@ export function ChatEngineProvider({
|
||||
}
|
||||
|
||||
// Templates fill the input and send it right away (attachments included)
|
||||
// Whether it was sent (it can run after a wait: the template panel
|
||||
// stores its click count first, so busy is read from the ref)
|
||||
// Whether it was sent (it can run after a wait, so busy is read from
|
||||
// the ref)
|
||||
const sendTemplate = async (prompt: string): Promise<boolean> => {
|
||||
// Like the send button, it waits for an answer or a message being
|
||||
// prepared (that message may still come back to the input), and for
|
||||
@@ -1458,11 +1395,6 @@ export function ChatEngineProvider({
|
||||
}
|
||||
}
|
||||
|
||||
const restoreDiagramFromSnapshot = (savedXml: string) => {
|
||||
onDisplayChart(savedXml, true)
|
||||
chartXMLRef.current = savedXml
|
||||
}
|
||||
|
||||
// Snapshots of the messages after this one go with them
|
||||
const dropLaterSnapshots = (messageIndex: number) => {
|
||||
for (const key of xmlSnapshotsRef.current.keys()) {
|
||||
@@ -1480,7 +1412,7 @@ export function ChatEngineProvider({
|
||||
return false
|
||||
}
|
||||
const previousXml = getPreviousXml(index)
|
||||
restoreDiagramFromSnapshot(savedXml)
|
||||
onDisplayChart(savedXml, true)
|
||||
dropLaterSnapshots(index)
|
||||
useVersionsStore.getState().removeFromTurn(index)
|
||||
|
||||
@@ -1492,7 +1424,7 @@ export function ChatEngineProvider({
|
||||
})
|
||||
sendChatMessage(
|
||||
parts,
|
||||
getFirstPageXml(savedXml),
|
||||
getPageXml(savedXml, viewedPageId()),
|
||||
previousXml,
|
||||
index,
|
||||
selectionOf(messages[index]),
|
||||
@@ -1548,7 +1480,7 @@ export function ChatEngineProvider({
|
||||
// Like submit: the diagram export comes first
|
||||
preparingSendRef.current = true
|
||||
try {
|
||||
const chartXml = formatXML(await onFetchChart())
|
||||
const chartXml = formatXML(await fetchDiagramXml())
|
||||
// Another chat came on screen meanwhile (browser back/forward),
|
||||
// or this one is being left
|
||||
if (getChatGeneration() !== generation || leavingRef.current) {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import {
|
||||
ChevronDown,
|
||||
Download,
|
||||
FilePlus,
|
||||
MessageSquareDashed,
|
||||
PanelRightClose,
|
||||
Settings2,
|
||||
SquarePen,
|
||||
Settings,
|
||||
} from "lucide-react"
|
||||
import { useRef } from "react"
|
||||
import { VersionStrip } from "@/components/canvas/version-strip"
|
||||
import { DevXmlSimulator } from "@/components/dev-xml-simulator"
|
||||
import { BrandMark } from "@/components/workspace/brand-mark"
|
||||
import { IconButton } from "@/components/workspace/icon-button"
|
||||
@@ -21,11 +22,11 @@ import {
|
||||
useSettingsStore,
|
||||
} from "@/stores/settings-store"
|
||||
import { useUiStore } from "@/stores/ui-store"
|
||||
import { useVersionsStore } from "@/stores/versions-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"
|
||||
|
||||
@@ -97,6 +98,25 @@ export function ChatPanel({
|
||||
const openSettings = useUiStore((s) => s.openSettings)
|
||||
const setPanelOpen = useUiStore((s) => s.setPanelOpen)
|
||||
|
||||
// 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). The
|
||||
// strip shows them even when there is only one.
|
||||
const versions = useVersionsStore((s) => s.versions)
|
||||
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"
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
@@ -139,14 +159,14 @@ export function ChatPanel({
|
||||
disabled={engine.isBusy}
|
||||
data-testid="new-chat-button"
|
||||
>
|
||||
<SquarePen />
|
||||
<FilePlus />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label={dict.nav.settings}
|
||||
onClick={() => openSettings()}
|
||||
data-testid="settings-button"
|
||||
>
|
||||
<Settings2 />
|
||||
<Settings />
|
||||
</IconButton>
|
||||
{!mobile && (
|
||||
<IconButton
|
||||
@@ -160,7 +180,7 @@ export function ChatPanel({
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<VersionStrip />
|
||||
<VersionStrip minVersions={hasCardless ? 1 : 2} />
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto scrollbar-thin">
|
||||
{engine.messages.length > 0 ? <MessageList /> : <EmptyThread />}
|
||||
@@ -173,7 +193,7 @@ export function ChatPanel({
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="shrink-0 p-2.5 pt-1">
|
||||
<div className="shrink-0 px-4 pt-1 pb-3">
|
||||
<Composer
|
||||
placeholder={
|
||||
engine.messages.length > 0 &&
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
VersionsProvider,
|
||||
type VersionsSource,
|
||||
} from "@/components/canvas/versions-context"
|
||||
import { useCanvasStore } from "@/stores/canvas-store"
|
||||
import { useVersionsStore } from "@/stores/versions-store"
|
||||
import { useChatEngine } from "./chat-engine"
|
||||
|
||||
/**
|
||||
* The chat's versions for the canvas components (version cards, the strip,
|
||||
* the compare dialog): the version store's list and flags, and the chat
|
||||
* engine's restore and undo
|
||||
*/
|
||||
export function ChatVersionsProvider({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { restoreVersion, undoVersion } = useChatEngine()
|
||||
const versions = useVersionsStore((s) => s.versions)
|
||||
const onCanvasId = useVersionsStore((s) => s.onCanvasVersionId)
|
||||
const undoneId = useVersionsStore((s) => s.undoneVersionId)
|
||||
const isBusy = useCanvasStore((s) => s.isBusy)
|
||||
|
||||
// Only the latest version can be undone, and only while it is (or was)
|
||||
// on the canvas: after an older version was restored, the latest one
|
||||
// is restored too
|
||||
const latest = versions.at(-1)
|
||||
const undoable = !!latest && latest.beforeXml !== undefined
|
||||
const value: VersionsSource = {
|
||||
versions,
|
||||
onCanvasId,
|
||||
undoneId,
|
||||
isBusy,
|
||||
canUndo: undoable && latest.id === onCanvasId,
|
||||
canRedo: undoable && latest.id === undoneId,
|
||||
restore: restoreVersion,
|
||||
// The engine's undo toggles: it redoes a change that is undone
|
||||
undo: () => latest && undoVersion(latest.id),
|
||||
redo: () => latest && undoVersion(latest.id),
|
||||
}
|
||||
|
||||
return <VersionsProvider value={value}>{children}</VersionsProvider>
|
||||
}
|
||||
@@ -18,9 +18,8 @@ import {
|
||||
useState,
|
||||
} from "react"
|
||||
import { toast } from "sonner"
|
||||
import { TemplateCreateDialog } from "@/components/chat/TemplateCreateDialog"
|
||||
import { TemplateFormDialog } from "@/components/chat/TemplateFormDialog"
|
||||
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 {
|
||||
@@ -46,24 +45,16 @@ 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(
|
||||
toast.error(
|
||||
<span className="text-muted-foreground">{errors[0]}</span>,
|
||||
{ duration: 5000 },
|
||||
)
|
||||
return
|
||||
}
|
||||
showErrorToast(
|
||||
toast.error(
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="font-medium">
|
||||
{formatMessage(dict.errors.filesRejected, {
|
||||
@@ -83,6 +74,7 @@ function showValidationErrors(errors: string[], dict: any) {
|
||||
)}
|
||||
</ul>
|
||||
</div>,
|
||||
{ duration: 5000 },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -277,10 +269,11 @@ export function Composer({
|
||||
next.delete(url)
|
||||
return next
|
||||
})
|
||||
showErrorToast(
|
||||
toast.error(
|
||||
<span className="text-muted-foreground">
|
||||
{err instanceof Error ? err.message : dict.url.failed}
|
||||
</span>,
|
||||
{ duration: 5000 },
|
||||
)
|
||||
} finally {
|
||||
setIsExtractingUrl(false)
|
||||
@@ -519,7 +512,7 @@ export function Composer({
|
||||
onSubmit={handleUrlExtract}
|
||||
isExtracting={isExtractingUrl}
|
||||
/>
|
||||
<TemplateCreateDialog
|
||||
<TemplateFormDialog
|
||||
open={saveTemplateOpen}
|
||||
onOpenChange={setSaveTemplateOpen}
|
||||
onSuccess={() => setSaveTemplateOpen(false)}
|
||||
@@ -532,10 +525,6 @@ export function Composer({
|
||||
</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)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FileText, FileUp, History, Pencil } from "lucide-react"
|
||||
import { FileUp, History, Pencil } from "lucide-react"
|
||||
import type React from "react"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { getAssetUrl } from "@/lib/base-path"
|
||||
@@ -12,58 +12,51 @@ interface Example {
|
||||
title: string
|
||||
description: string
|
||||
/** Picture of the result (or of the input, for "replicate" examples) */
|
||||
image?: string
|
||||
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 choice: a small picture, a title and one line */
|
||||
function ExampleCard({
|
||||
/** 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}
|
||||
className="group/example flex min-w-0 items-center gap-2.5 rounded-xl border border-border bg-card p-1.5 pr-2.5 text-left transition-colors hover:border-foreground/25"
|
||||
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-12 w-16 shrink-0 items-center justify-center overflow-hidden rounded-lg",
|
||||
plain ? "bg-muted" : "sheet-light bg-white",
|
||||
)}
|
||||
>
|
||||
<span className="flex h-16 w-full items-center justify-center overflow-hidden rounded-lg sheet-light bg-white">
|
||||
{picture}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="line-clamp-2 text-[13px] leading-snug font-medium text-foreground">
|
||||
<span className="px-1 text-[13px] leading-snug font-medium text-foreground">
|
||||
{title}
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-xs text-muted-foreground">
|
||||
{description}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -92,6 +85,7 @@ export function LobbyHero({
|
||||
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",
|
||||
@@ -185,10 +179,12 @@ export function LobbyHero({
|
||||
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-3",
|
||||
compact ? "grid-cols-1" : "grid-cols-5",
|
||||
)}
|
||||
>
|
||||
{examples.map((example) =>
|
||||
@@ -209,70 +205,51 @@ export function LobbyHero({
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<ExampleCard
|
||||
<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-10 max-w-[56px] object-contain transition-transform duration-300 group-hover/example:scale-[1.06]"
|
||||
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}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
{!compact && (
|
||||
<ExampleCard
|
||||
onClick={onOpenFile}
|
||||
title={dict.workspace.openFile}
|
||||
description={t.openFileHint}
|
||||
picture={
|
||||
<FileUp className="size-5 text-muted-foreground" />
|
||||
}
|
||||
plain
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-3 text-center text-xs text-faint">
|
||||
<p className="mt-2.5 text-center text-xs text-faint">
|
||||
{dict.examples.cachedNote}
|
||||
</p>
|
||||
|
||||
<div className="mt-6 flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-[13px] text-muted-foreground">
|
||||
{/* 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="inline-flex items-center gap-1.5 hover:text-foreground"
|
||||
>
|
||||
<button type="button" className={startButtonClass}>
|
||||
<History className="size-4" />
|
||||
{t.recent}
|
||||
</button>
|
||||
</SessionMenu>
|
||||
)}
|
||||
{compact && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenFile}
|
||||
className="inline-flex items-center gap-1.5 hover:text-foreground"
|
||||
className={startButtonClass}
|
||||
data-testid="open-file"
|
||||
>
|
||||
<FileUp className="size-4" />
|
||||
{dict.workspace.openFile}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDrawYourself}
|
||||
className="inline-flex items-center gap-1.5 hover:text-foreground"
|
||||
className={startButtonClass}
|
||||
data-testid="draw-yourself"
|
||||
>
|
||||
<Pencil className="size-4" />
|
||||
|
||||
@@ -16,13 +16,9 @@ import {
|
||||
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 { Reasoning } from "@/components/ai-elements/reasoning"
|
||||
import { Shimmer } from "@/components/ai-elements/shimmer"
|
||||
import { TemplateCreateDialog } from "@/components/chat/TemplateCreateDialog"
|
||||
import { TemplateFormDialog } from "@/components/chat/TemplateFormDialog"
|
||||
import type { ToolPartLike } from "@/components/chat/types"
|
||||
import { ValidationCard } from "@/components/chat/ValidationCard"
|
||||
import Image from "@/components/image-with-basepath"
|
||||
@@ -291,7 +287,7 @@ function UserMessage({
|
||||
{text && <MessageText text={text} />}
|
||||
</div>
|
||||
{saveTemplate && (
|
||||
<TemplateCreateDialog
|
||||
<TemplateFormDialog
|
||||
open
|
||||
onOpenChange={(open) => !open && setSaveTemplate(false)}
|
||||
onSuccess={() => setSaveTemplate(false)}
|
||||
@@ -398,13 +394,9 @@ function AssistantMessage({
|
||||
className="w-full"
|
||||
isStreaming={isStreamingReasoning}
|
||||
defaultOpen={!isRestored}
|
||||
>
|
||||
<ReasoningTrigger
|
||||
getThinkingMessage={thinkingMessage}
|
||||
/>
|
||||
<ReasoningContent>
|
||||
>
|
||||
{(part as { text: string }).text}
|
||||
</ReasoningContent>
|
||||
</Reasoning>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,23 +2,17 @@ import {
|
||||
AlertCircle,
|
||||
Check,
|
||||
ChevronDown,
|
||||
Code2,
|
||||
Copy,
|
||||
Library,
|
||||
PenTool,
|
||||
Redo2,
|
||||
RotateCcw,
|
||||
Undo2,
|
||||
} from "lucide-react"
|
||||
import { useState } from "react"
|
||||
import { Shimmer } from "@/components/ai-elements/shimmer"
|
||||
import { VersionCard as VersionCardView } from "@/components/canvas/version-card"
|
||||
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"
|
||||
@@ -84,45 +78,9 @@ function toolText(part: ToolPartLike): string {
|
||||
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).
|
||||
* Card for one diagram version produced by a tool call: the shared card
|
||||
* with a link to what the AI wrote (shown in a panel under the card)
|
||||
*/
|
||||
function VersionCard({
|
||||
part,
|
||||
@@ -135,64 +93,32 @@ function VersionCard({
|
||||
}) {
|
||||
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, on every card (main showed it on every tool call)
|
||||
const codeButton = (
|
||||
return (
|
||||
<VersionCardView
|
||||
version={version}
|
||||
isLatest={isLatest}
|
||||
label={isEdit ? t.edited : t.created}
|
||||
data-tool-state={part.state}
|
||||
// A text link, so the card's only button is the action (undo
|
||||
// or restore); it wraps as one unit with its separator
|
||||
afterSummary={
|
||||
<span className="whitespace-nowrap">
|
||||
<span aria-hidden> · </span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCode((v) => !v)}
|
||||
aria-label={showCode ? t.hideCode : t.showCode}
|
||||
title={showCode ? t.hideCode : t.showCode}
|
||||
className="inline-flex size-7 shrink-0 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
className="underline decoration-foreground/30 underline-offset-2 hover:text-foreground hover:decoration-foreground"
|
||||
>
|
||||
<Code2 className="size-4" />
|
||||
{showCode ? t.hideCode : t.showCode}
|
||||
</button>
|
||||
)
|
||||
const codePanel = showCode && (
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{showCode && (
|
||||
<div className="relative border-t border-border bg-surface-1 px-3 py-2.5">
|
||||
<button
|
||||
type="button"
|
||||
@@ -208,101 +134,8 @@ function VersionCard({
|
||||
</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" title={summary}>
|
||||
<div className="truncate text-[13px] text-foreground">
|
||||
{title}
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted-foreground">
|
||||
{summary}
|
||||
</div>
|
||||
</div>
|
||||
{codeButton}
|
||||
{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>
|
||||
<div className="flex items-center gap-2.5 px-3 py-2.5">
|
||||
{badge}
|
||||
<div className="min-w-0 flex-1" title={summary}>
|
||||
<div className="truncate text-[13px] font-medium text-foreground">
|
||||
{title}
|
||||
</div>
|
||||
<div className="line-clamp-2 text-xs text-muted-foreground">
|
||||
{summary}
|
||||
</div>
|
||||
</div>
|
||||
{codeButton}
|
||||
{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>
|
||||
{codePanel}
|
||||
</div>
|
||||
</VersionCardView>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -5,13 +5,25 @@ 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, replacePageModel } from "@/lib/diagram-pages"
|
||||
import { extractCompleteMxCells } from "@/lib/utils"
|
||||
import {
|
||||
convertToLegalXml,
|
||||
extractCompleteMxCells,
|
||||
replaceNodes,
|
||||
} from "@/lib/utils"
|
||||
defaultLayerOf,
|
||||
expandCompactCells,
|
||||
} from "@/packages/mcp-server/src/compact-cells.ts"
|
||||
import { applyDiagramOperations } from "@/packages/mcp-server/src/diagram-operations.ts"
|
||||
import { BLANK_MXFILE } from "@/packages/mcp-server/src/pages.ts"
|
||||
import { targetPageXml } from "@/packages/mcp-server/src/edit-diagram.ts"
|
||||
import {
|
||||
BLANK_MXFILE,
|
||||
wrapCellsInModel,
|
||||
} from "@/packages/mcp-server/src/pages.ts"
|
||||
import {
|
||||
addDefaultStyles,
|
||||
applyStyleClasses,
|
||||
edgeIdsOf,
|
||||
readStyleClasses,
|
||||
} from "@/packages/mcp-server/src/style-classes.ts"
|
||||
import { autoFixXml } from "@/packages/mcp-server/src/xml-validation.ts"
|
||||
|
||||
// Helper to extract complete operations from streaming input
|
||||
function getCompleteOperations(
|
||||
@@ -34,6 +46,8 @@ interface UseDiagramStreamingParams {
|
||||
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>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,6 +64,7 @@ export function useDiagramStreaming({
|
||||
processedToolCallsRef,
|
||||
editDiagramOriginalXmlRef,
|
||||
loadedMessageIdsRef,
|
||||
turnPageIdRef,
|
||||
}: UseDiagramStreamingParams) {
|
||||
const { chartXML, chartXMLRef, loadDiagram } = useDiagram()
|
||||
const previousXML = useRef<string>("")
|
||||
@@ -71,24 +86,36 @@ export function useDiagramStreaming({
|
||||
// so far. The tool handler validates and loads the final diagram.
|
||||
const handleDisplayChart = useCallback(
|
||||
(xml: string) => {
|
||||
const completeCells = extractCompleteMxCells(xml || "")
|
||||
// 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 = convertToLegalXml(completeCells)
|
||||
if (convertedXml === previousXML.current) return
|
||||
// The same wrapping, fixes and expansion as the final diagram
|
||||
// (prepareNewDiagram), so the preview matches what is committed
|
||||
const model = addDefaultStyles(
|
||||
applyStyleClasses(
|
||||
expandCompactCells(
|
||||
autoFixXml(wrapCellsInModel(completeCells)).fixed,
|
||||
),
|
||||
classes,
|
||||
),
|
||||
)
|
||||
if (model === 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",
|
||||
)
|
||||
const testDoc = new DOMParser().parseFromString(model, "text/xml")
|
||||
if (testDoc.querySelector("parsererror")) return
|
||||
|
||||
try {
|
||||
// Replace the first 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)
|
||||
previousXML.current = convertedXml
|
||||
// Replace the model's page so other pages stay intact; an
|
||||
// empty canvas gets the blank mxfile to put the page in
|
||||
const replacedXML = replacePageModel(
|
||||
chartXML,
|
||||
turnPageIdRef?.current,
|
||||
model,
|
||||
)
|
||||
previousXML.current = model
|
||||
loadDiagram(replacedXML, true, "preview")
|
||||
} catch (error) {
|
||||
console.error("Error processing XML:", error)
|
||||
@@ -202,9 +229,29 @@ export function useDiagramStreaming({
|
||||
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,
|
||||
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
|
||||
|
||||
@@ -4,7 +4,10 @@ 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 {
|
||||
clearHighlights,
|
||||
highlightChangedCells,
|
||||
} 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"
|
||||
@@ -46,29 +49,24 @@ export function useVersions({
|
||||
// (effect cleanups run before the streaming hook commits). The handler
|
||||
// only reads refs and stable functions.
|
||||
useEffect(() => {
|
||||
setCommitHandler(({ beforeXml, afterXml, toolCallId }) => {
|
||||
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)
|
||||
}
|
||||
if (!fromScratch) highlightChangedCells(touchedIds)
|
||||
// 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
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { prepareNewDiagram } from "@/packages/mcp-server/src/new-diagram.ts"
|
||||
|
||||
// Dev XML presets for streaming simulator
|
||||
@@ -135,15 +134,12 @@ const DEV_XML_PRESETS: Record<string, string> = {
|
||||
interface DevXmlSimulatorProps {
|
||||
setMessages: React.Dispatch<React.SetStateAction<any[]>>
|
||||
onDisplayChart: (xml: string) => void
|
||||
onShowQuotaToast?: () => void
|
||||
}
|
||||
|
||||
export function DevXmlSimulator({
|
||||
setMessages,
|
||||
onDisplayChart,
|
||||
onShowQuotaToast,
|
||||
}: DevXmlSimulatorProps) {
|
||||
const dict = useDictionary()
|
||||
const [devXml, setDevXml] = useState("")
|
||||
const [isSimulating, setIsSimulating] = useState(false)
|
||||
const [devIntervalMs, setDevIntervalMs] = useState(1)
|
||||
@@ -180,7 +176,7 @@ export function DevXmlSimulator({
|
||||
parts: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: dict.dev.simulatingMessage,
|
||||
text: "[Dev] Simulating XML streaming",
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -230,7 +226,7 @@ export function DevXmlSimulator({
|
||||
const lastMsg = updated[updated.length - 1] as any
|
||||
if (lastMsg?.role === "assistant" && lastMsg.parts?.[0]) {
|
||||
lastMsg.parts[0].state = "output-available"
|
||||
lastMsg.parts[0].output = dict.dev.successMessage
|
||||
lastMsg.parts[0].output = "Successfully displayed the diagram."
|
||||
lastMsg.parts[0].input = { xml }
|
||||
}
|
||||
return updated
|
||||
@@ -247,12 +243,12 @@ export function DevXmlSimulator({
|
||||
<div className="border-t border-dashed border-orange-500/50 px-4 py-2 bg-orange-50/50 dark:bg-orange-950/30">
|
||||
<details>
|
||||
<summary className="text-xs text-orange-600 dark:text-orange-400 cursor-pointer font-medium">
|
||||
{dict.dev.title}
|
||||
Dev: XML Streaming Simulator
|
||||
</summary>
|
||||
<div className="mt-2 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{dict.dev.preset}
|
||||
Preset:
|
||||
</label>
|
||||
<select
|
||||
onChange={(e) => {
|
||||
@@ -264,7 +260,7 @@ export function DevXmlSimulator({
|
||||
defaultValue=""
|
||||
>
|
||||
<option value="" disabled>
|
||||
{dict.dev.selectPreset}
|
||||
Select a preset...
|
||||
</option>
|
||||
{Object.keys(DEV_XML_PRESETS).map((name) => (
|
||||
<option key={name} value={name}>
|
||||
@@ -277,19 +273,19 @@ export function DevXmlSimulator({
|
||||
onClick={() => setDevXml("")}
|
||||
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground border rounded"
|
||||
>
|
||||
{dict.dev.clear}
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
value={devXml}
|
||||
onChange={(e) => setDevXml(e.target.value)}
|
||||
placeholder={dict.dev.placeholder}
|
||||
placeholder="Paste mxCell XML here or select a preset..."
|
||||
className="w-full h-24 text-xs font-mono p-2 border rounded bg-background"
|
||||
/>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<label className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{dict.dev.interval}
|
||||
Interval:
|
||||
</label>
|
||||
<input
|
||||
type="range"
|
||||
@@ -308,7 +304,7 @@ export function DevXmlSimulator({
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{dict.dev.chars}
|
||||
Chars:
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
@@ -332,8 +328,8 @@ export function DevXmlSimulator({
|
||||
className="px-3 py-1 text-xs bg-orange-500 text-white rounded hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isSimulating
|
||||
? dict.dev.streaming
|
||||
: `${dict.dev.simulate} (${devChunkSize} chars/${devIntervalMs}ms)`}
|
||||
? "Streaming..."
|
||||
: `Simulate (${devChunkSize} chars/${devIntervalMs}ms)`}
|
||||
</button>
|
||||
{isSimulating && (
|
||||
<button
|
||||
@@ -343,16 +339,7 @@ export function DevXmlSimulator({
|
||||
}}
|
||||
className="px-3 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
|
||||
>
|
||||
{dict.dev.stop}
|
||||
</button>
|
||||
)}
|
||||
{onShowQuotaToast && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onShowQuotaToast}
|
||||
className="px-3 py-1 text-xs bg-purple-500 text-white rounded hover:bg-purple-600"
|
||||
>
|
||||
{dict.dev.testQuotaToast}
|
||||
Stop
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
|
||||
interface ErrorToastProps {
|
||||
message: React.ReactNode
|
||||
onDismiss: () => void
|
||||
}
|
||||
|
||||
export function ErrorToast({ message, onDismiss }: ErrorToastProps) {
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" || e.key === " " || e.key === "Escape") {
|
||||
e.preventDefault()
|
||||
onDismiss()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
tabIndex={0}
|
||||
onClick={onDismiss}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="flex items-center gap-3 bg-card border border-border/50 px-4 py-3 rounded-xl shadow-sm cursor-pointer hover:bg-muted/50 focus:outline-none focus:ring-2 focus:ring-primary/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-center w-8 h-8 rounded-full bg-destructive/10 flex-shrink-0">
|
||||
<svg
|
||||
className="w-4 h-4 text-destructive"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<span className="text-sm text-foreground">{message}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// GitHub mark as an inline SVG, so no icon package is needed for one icon
|
||||
export function GitHubIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 16 16"
|
||||
fill="currentColor"
|
||||
aria-hidden="true"
|
||||
className={className}
|
||||
>
|
||||
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -43,7 +43,6 @@ import {
|
||||
CommandList,
|
||||
} from "@/components/ui/command"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
@@ -164,7 +163,6 @@ export function ModelConfigDialog({
|
||||
)
|
||||
const [customModelInput, setCustomModelInput] = useState("")
|
||||
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false)
|
||||
const [deleteConfirmText, setDeleteConfirmText] = useState("")
|
||||
// Models whose test is running (they are all tested at once)
|
||||
const [validatingModelIds, setValidatingModelIds] = useState<Set<string>>(
|
||||
() => new Set(),
|
||||
@@ -441,7 +439,6 @@ export function ModelConfigDialog({
|
||||
setFetchModelsError("")
|
||||
updates = {
|
||||
...updates,
|
||||
validated: false,
|
||||
models: selectedProvider.models.map((m) => ({
|
||||
...m,
|
||||
validated: undefined,
|
||||
@@ -659,10 +656,6 @@ export function ModelConfigDialog({
|
||||
return
|
||||
}
|
||||
|
||||
// A model whose id changed was not tested
|
||||
if (allValid && !idChanged) {
|
||||
updateProvider(selectedProviderId, { validated: true })
|
||||
}
|
||||
markRejected(selectedProviderId, askedWith, rejected)
|
||||
// The status line is about the provider shown now
|
||||
if (selectedProviderIdRef.current !== selectedProviderId) return
|
||||
@@ -1004,7 +997,6 @@ export function ModelConfigDialog({
|
||||
name={provider.name}
|
||||
baseUrl={provider.baseUrl}
|
||||
awsRegion={provider.awsRegion}
|
||||
bedrockApiKey
|
||||
settingsLayout
|
||||
bedrockFilled={{
|
||||
apiKey: !!provider.apiKey,
|
||||
@@ -1389,10 +1381,7 @@ export function ModelConfigDialog({
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<AlertDialog
|
||||
open={deleteConfirmOpen}
|
||||
onOpenChange={(open) => {
|
||||
setDeleteConfirmOpen(open)
|
||||
if (!open) setDeleteConfirmText("")
|
||||
}}
|
||||
onOpenChange={setDeleteConfirmOpen}
|
||||
>
|
||||
<AlertDialogContent className="border-destructive/30">
|
||||
<AlertDialogHeader>
|
||||
@@ -1410,39 +1399,11 @@ export function ModelConfigDialog({
|
||||
})}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{selectedProvider &&
|
||||
selectedProvider.models.length >= 3 && (
|
||||
<div className="mt-2 space-y-2">
|
||||
<Label
|
||||
htmlFor="delete-confirm"
|
||||
className="text-sm text-muted-foreground"
|
||||
>
|
||||
{formatMessage(t.typeToConfirm, {
|
||||
name: providerName(selectedProvider),
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="delete-confirm"
|
||||
value={deleteConfirmText}
|
||||
onChange={(e) =>
|
||||
setDeleteConfirmText(e.target.value)
|
||||
}
|
||||
placeholder={t.typeProviderName}
|
||||
className="h-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t.cancel}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteProvider}
|
||||
disabled={
|
||||
selectedProvider &&
|
||||
selectedProvider.models.length >= 3 &&
|
||||
deleteConfirmText !==
|
||||
providerName(selectedProvider)
|
||||
}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90 disabled:opacity-50"
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{t.delete}
|
||||
</AlertDialogAction>
|
||||
|
||||
+223
-189
@@ -10,28 +10,38 @@ import {
|
||||
Settings2,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import {
|
||||
ModelSelectorContent,
|
||||
ModelSelectorEmpty,
|
||||
ModelSelectorGroup,
|
||||
ModelSelectorInput,
|
||||
ModelSelectorItem,
|
||||
ModelSelectorList,
|
||||
ModelSelectorLogo,
|
||||
ModelSelectorName,
|
||||
ModelSelector as ModelSelectorRoot,
|
||||
ModelSelectorSectionHeader,
|
||||
ModelSelectorSeparator,
|
||||
ModelSelectorTrigger,
|
||||
} from "@/components/ai-elements/model-selector"
|
||||
import { ButtonWithTooltip } from "@/components/button-with-tooltip"
|
||||
type ComponentProps,
|
||||
type ReactNode,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
import { ProviderLogo } from "@/components/provider-logo"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
type FlattenedModel,
|
||||
PROVIDER_LOGO_MAP,
|
||||
} from "@/lib/types/model-config"
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "@/components/ui/command"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import type { FlattenedModel, ProviderName } from "@/lib/types/model-config"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface ModelSelectorProps {
|
||||
@@ -44,25 +54,22 @@ interface ModelSelectorProps {
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
type ProviderGroup = { provider: ProviderName; models: FlattenedModel[] }
|
||||
|
||||
// Group models by providerLabel (handles duplicate providers)
|
||||
function groupModelsByProvider(
|
||||
models: FlattenedModel[],
|
||||
): Map<string, { provider: string; models: FlattenedModel[] }> {
|
||||
const groups = new Map<
|
||||
string,
|
||||
{ provider: string; models: FlattenedModel[] }
|
||||
>()
|
||||
): Map<string, ProviderGroup> {
|
||||
const groups = new Map<string, ProviderGroup>()
|
||||
for (const model of models) {
|
||||
// For server models, strip "Server · " prefix for cleaner grouping
|
||||
const key =
|
||||
model.source === "server"
|
||||
? model.providerLabel.replace(/^Server · /, "")
|
||||
: model.providerLabel
|
||||
const existing = groups.get(key)
|
||||
const existing = groups.get(model.providerLabel)
|
||||
if (existing) {
|
||||
existing.models.push(model)
|
||||
} else {
|
||||
groups.set(key, { provider: model.provider, models: [model] })
|
||||
groups.set(model.providerLabel, {
|
||||
provider: model.provider,
|
||||
models: [model],
|
||||
})
|
||||
}
|
||||
}
|
||||
return groups
|
||||
@@ -88,6 +95,72 @@ export function shortModelName(id: string): string {
|
||||
return short
|
||||
}
|
||||
|
||||
// The command list with a shadow at the bottom while more items are below
|
||||
function ModelList({
|
||||
className,
|
||||
...props
|
||||
}: ComponentProps<typeof CommandList>) {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const [showShadow, setShowShadow] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const listElement = listRef.current
|
||||
if (!listElement) return
|
||||
|
||||
const checkScroll = () => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = listElement
|
||||
// A small threshold handles fractional pixel rendering
|
||||
setShowShadow(
|
||||
scrollHeight > Math.ceil(scrollTop + clientHeight) + 1,
|
||||
)
|
||||
}
|
||||
|
||||
checkScroll()
|
||||
listElement.addEventListener("scroll", checkScroll)
|
||||
window.addEventListener("resize", checkScroll)
|
||||
// Content changes, e.g. the search filtering items
|
||||
const observer = new MutationObserver(checkScroll)
|
||||
observer.observe(listElement, { childList: true, subtree: true })
|
||||
|
||||
return () => {
|
||||
listElement.removeEventListener("scroll", checkScroll)
|
||||
window.removeEventListener("resize", checkScroll)
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<CommandList
|
||||
ref={listRef}
|
||||
className={cn(
|
||||
// Hide scrollbar on all platforms
|
||||
"[&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"pointer-events-none absolute bottom-0 left-0 right-0 h-12 bg-gradient-to-t from-muted/80 via-muted/40 to-transparent transition-opacity duration-200",
|
||||
showShadow ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SectionHeader({ icon, label }: { icon: ReactNode; label: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/40 rounded-sm mx-1 mt-1">
|
||||
<span className="[&>svg]:size-3.5" aria-hidden="true">
|
||||
{icon}
|
||||
</span>
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ModelSelector({
|
||||
models,
|
||||
selectedModelId,
|
||||
@@ -146,6 +219,52 @@ export function ModelSelector({
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
// One group per provider; `trailing` is the small label at the end of a
|
||||
// row ("Default" for server models, the test state for user models)
|
||||
const renderGroups = (
|
||||
groups: Map<string, ProviderGroup>,
|
||||
keyPrefix: "server" | "user",
|
||||
trailing: (model: FlattenedModel) => ReactNode,
|
||||
) =>
|
||||
Array.from(groups.entries()).map(
|
||||
([providerLabel, { provider, models: providerModels }]) => (
|
||||
<CommandGroup
|
||||
key={`${keyPrefix}-${providerLabel}`}
|
||||
heading={providerLabel}
|
||||
className="[&>[cmdk-group-heading]]:pl-4"
|
||||
>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.id}
|
||||
// Unique value so same-named models highlight
|
||||
// separately; keywords keep search by name
|
||||
value={model.id}
|
||||
keywords={[model.modelId, providerLabel]}
|
||||
onSelect={() => handleSelect(model.id)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
selectedModelId === model.id
|
||||
? "opacity-100"
|
||||
: "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<ProviderLogo
|
||||
provider={provider}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="flex-1 truncate text-left">
|
||||
{model.modelId}
|
||||
</span>
|
||||
{trailing(model)}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
),
|
||||
)
|
||||
|
||||
const tooltipContent = selectedModel
|
||||
? `${selectedModel.modelId} ${dict.modelConfig.clickToChange}`
|
||||
: `${dict.modelConfig.usingServerDefault} ${dict.modelConfig.clickToChange}`
|
||||
@@ -186,16 +305,19 @@ export function ModelSelector({
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className="min-w-0 max-w-44">
|
||||
<ModelSelectorRoot
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (next) toSettingsRef.current = false
|
||||
setOpen(next)
|
||||
}}
|
||||
>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<ButtonWithTooltip
|
||||
tooltipContent={tooltipContent}
|
||||
{/* The dialog trigger must wrap the button itself: Radix
|
||||
Tooltip's root renders no element to pass its props to */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
@@ -219,50 +341,63 @@ export function ModelSelector({
|
||||
{showLabel ? (
|
||||
<span className="min-w-0 truncate text-xs">
|
||||
{selectedModel
|
||||
? shortModelName(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>
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs text-wrap">
|
||||
{tooltipContent}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<ModelSelectorContent
|
||||
title={dict.modelConfig.selectModel}
|
||||
<DialogContent
|
||||
className="p-0"
|
||||
onCloseAutoFocus={(e) => {
|
||||
if (!toSettingsRef.current) return
|
||||
toSettingsRef.current = false
|
||||
e.preventDefault()
|
||||
}}
|
||||
>
|
||||
<ModelSelectorInput
|
||||
<DialogTitle className="sr-only">
|
||||
{dict.modelConfig.selectModel}
|
||||
</DialogTitle>
|
||||
<Command className="**:data-[slot=command-input-wrapper]:h-auto">
|
||||
<CommandInput
|
||||
className="h-auto py-3.5"
|
||||
placeholder={dict.modelConfig.searchModels}
|
||||
/>
|
||||
<div className="flex flex-1 flex-col min-h-0 overflow-hidden">
|
||||
<div className="flex-1 min-h-0 overflow-hidden">
|
||||
<ModelSelectorList className="overflow-y-auto scrollbar-thin">
|
||||
<ModelSelectorEmpty>
|
||||
<ModelList className="overflow-y-auto scrollbar-thin">
|
||||
<CommandEmpty>
|
||||
{dict.modelConfig.noModelsFound}
|
||||
</ModelSelectorEmpty>
|
||||
</CommandEmpty>
|
||||
|
||||
{/* Server Default Option - only show when no server models are configured */}
|
||||
{serverModels.length === 0 && (
|
||||
<ModelSelectorGroup
|
||||
<CommandGroup
|
||||
heading={dict.modelConfig.default}
|
||||
>
|
||||
<ModelSelectorItem
|
||||
<CommandItem
|
||||
value="__server_default__"
|
||||
onSelect={handleSelect}
|
||||
className={cn(
|
||||
"cursor-pointer",
|
||||
!selectedModelId && "bg-accent",
|
||||
!selectedModelId &&
|
||||
"bg-accent",
|
||||
)}
|
||||
>
|
||||
<Check
|
||||
@@ -274,98 +409,43 @@ export function ModelSelector({
|
||||
)}
|
||||
/>
|
||||
<Server className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||
<ModelSelectorName>
|
||||
{dict.modelConfig.serverDefault}
|
||||
</ModelSelectorName>
|
||||
</ModelSelectorItem>
|
||||
</ModelSelectorGroup>
|
||||
<span className="flex-1 truncate text-left">
|
||||
{
|
||||
dict.modelConfig
|
||||
.serverDefault
|
||||
}
|
||||
</span>
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Server Models Section */}
|
||||
{serverModels.length > 0 && (
|
||||
<>
|
||||
<ModelSelectorSectionHeader
|
||||
<SectionHeader
|
||||
icon={<Monitor />}
|
||||
label={
|
||||
dict.modelConfig.serverModels
|
||||
dict.modelConfig
|
||||
.serverModels
|
||||
}
|
||||
/>
|
||||
{Array.from(
|
||||
groupedServerModels.entries(),
|
||||
).map(
|
||||
([
|
||||
providerLabel,
|
||||
{
|
||||
provider,
|
||||
models: providerModels,
|
||||
},
|
||||
]) => (
|
||||
<ModelSelectorGroup
|
||||
key={`server-${providerLabel}`}
|
||||
heading={providerLabel}
|
||||
className="[&>[cmdk-group-heading]]:pl-4"
|
||||
>
|
||||
{providerModels.map(
|
||||
(model) => (
|
||||
<ModelSelectorItem
|
||||
key={model.id}
|
||||
// Unique value so same-named models highlight
|
||||
// separately; keywords keep search by name
|
||||
value={model.id}
|
||||
keywords={[
|
||||
model.modelId,
|
||||
providerLabel,
|
||||
]}
|
||||
onSelect={() =>
|
||||
handleSelect(
|
||||
model.id,
|
||||
)
|
||||
}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
selectedModelId ===
|
||||
model.id
|
||||
? "opacity-100"
|
||||
: "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<ModelSelectorLogo
|
||||
provider={
|
||||
PROVIDER_LOGO_MAP[
|
||||
provider
|
||||
] ||
|
||||
provider
|
||||
}
|
||||
className="mr-2"
|
||||
/>
|
||||
<ModelSelectorName>
|
||||
{
|
||||
model.modelId
|
||||
}
|
||||
</ModelSelectorName>
|
||||
{model.isDefault && (
|
||||
{renderGroups(
|
||||
groupedServerModels,
|
||||
"server",
|
||||
(model) =>
|
||||
model.isDefault && (
|
||||
<span
|
||||
title={
|
||||
dict
|
||||
.modelConfig
|
||||
dict.modelConfig
|
||||
.serverDefaultModel
|
||||
}
|
||||
className="ml-auto text-xs text-muted-foreground"
|
||||
>
|
||||
{
|
||||
dict
|
||||
.modelConfig
|
||||
dict.modelConfig
|
||||
.default
|
||||
}
|
||||
</span>
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
),
|
||||
)}
|
||||
</ModelSelectorGroup>
|
||||
),
|
||||
)}
|
||||
</>
|
||||
@@ -375,67 +455,19 @@ export function ModelSelector({
|
||||
{userModels.length > 0 && (
|
||||
<>
|
||||
{serverModels.length > 0 && (
|
||||
<ModelSelectorSeparator />
|
||||
<CommandSeparator />
|
||||
)}
|
||||
<ModelSelectorSectionHeader
|
||||
<SectionHeader
|
||||
icon={<User />}
|
||||
label={dict.modelConfig.userModels}
|
||||
/>
|
||||
{Array.from(
|
||||
groupedUserModels.entries(),
|
||||
).map(
|
||||
([
|
||||
providerLabel,
|
||||
{
|
||||
provider,
|
||||
models: providerModels,
|
||||
},
|
||||
]) => (
|
||||
<ModelSelectorGroup
|
||||
key={`user-${providerLabel}`}
|
||||
heading={providerLabel}
|
||||
className="[&>[cmdk-group-heading]]:pl-4"
|
||||
>
|
||||
{providerModels.map(
|
||||
(model) => (
|
||||
<ModelSelectorItem
|
||||
key={model.id}
|
||||
value={model.id}
|
||||
keywords={[
|
||||
model.modelId,
|
||||
providerLabel,
|
||||
]}
|
||||
onSelect={() =>
|
||||
handleSelect(
|
||||
model.id,
|
||||
)
|
||||
label={
|
||||
dict.modelConfig.userModels
|
||||
}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
selectedModelId ===
|
||||
model.id
|
||||
? "opacity-100"
|
||||
: "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<ModelSelectorLogo
|
||||
provider={
|
||||
PROVIDER_LOGO_MAP[
|
||||
provider
|
||||
] ||
|
||||
provider
|
||||
}
|
||||
className="mr-2"
|
||||
/>
|
||||
<ModelSelectorName>
|
||||
{
|
||||
model.modelId
|
||||
}
|
||||
</ModelSelectorName>
|
||||
{model.validated !==
|
||||
{renderGroups(
|
||||
groupedUserModels,
|
||||
"user",
|
||||
(model) =>
|
||||
model.validated !==
|
||||
true && (
|
||||
<span
|
||||
className={cn(
|
||||
@@ -455,16 +487,11 @@ export function ModelSelector({
|
||||
.modelConfig
|
||||
.modelUntested}
|
||||
</span>
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
),
|
||||
)}
|
||||
</ModelSelectorGroup>
|
||||
),
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</ModelSelectorList>
|
||||
</ModelList>
|
||||
</div>
|
||||
{/* Pinned footer: add a provider, configure models
|
||||
(z-10 above list shadow). Buttons, outside the
|
||||
@@ -486,7 +513,10 @@ export function ModelSelector({
|
||||
>
|
||||
<Plus className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate">
|
||||
{dict.modelConfig.addProviderEntry}
|
||||
{
|
||||
dict.modelConfig
|
||||
.addProviderEntry
|
||||
}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
@@ -500,15 +530,19 @@ export function ModelSelector({
|
||||
>
|
||||
<Settings2 className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate">
|
||||
{dict.modelConfig.configureModels}
|
||||
{
|
||||
dict.modelConfig
|
||||
.configureModels
|
||||
}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelectorRoot>
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -58,9 +58,6 @@ 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
|
||||
@@ -68,9 +65,6 @@ interface ProviderCredentialsFieldsProps {
|
||||
// UI (e.g. the user dialog's inline Test button + validation error); the
|
||||
// shared component only supplies the label above it.
|
||||
renderSecret: (opts: { field: SecretField; id: string }) => ReactNode
|
||||
// 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
|
||||
@@ -91,11 +85,9 @@ export function ProviderCredentialsFields({
|
||||
name,
|
||||
baseUrl,
|
||||
awsRegion,
|
||||
bedrockApiKey,
|
||||
disabled,
|
||||
onChange,
|
||||
renderSecret,
|
||||
footer,
|
||||
settingsLayout,
|
||||
clearSecrets,
|
||||
bedrockFilled,
|
||||
@@ -269,10 +261,8 @@ export function ProviderCredentialsFields({
|
||||
</div>
|
||||
)
|
||||
|
||||
// EdgeOne needs no credentials — the caller supplies just a test button
|
||||
if (provider === "edgeone") {
|
||||
return <div className="space-y-5">{footer}</div>
|
||||
}
|
||||
// EdgeOne needs no credentials
|
||||
if (provider === "edgeone") return null
|
||||
|
||||
if (settingsLayout) {
|
||||
return (
|
||||
@@ -447,7 +437,6 @@ export function ProviderCredentialsFields({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{footer}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -458,26 +447,6 @@ export function ProviderCredentialsFields({
|
||||
|
||||
{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
|
||||
@@ -535,8 +504,6 @@ export function ProviderCredentialsFields({
|
||||
{baseUrlField}
|
||||
</>
|
||||
)}
|
||||
|
||||
{footer}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { Coffee, Settings, X } from "lucide-react"
|
||||
import type React from "react"
|
||||
import { FaGithub } from "react-icons/fa"
|
||||
import { GitHubIcon } from "@/components/icons/github"
|
||||
import { useDictionary } from "@/hooks/use-dictionary"
|
||||
import { formatMessage } from "@/lib/i18n/utils"
|
||||
|
||||
@@ -28,16 +28,10 @@ export function QuotaLimitToast({
|
||||
n >= 1000 ? `${(n / 1000).toFixed(1)}k` : n.toString()
|
||||
|
||||
const quotaMessage = isTokenLimit
|
||||
? isSelfHosted
|
||||
? (dict.quota.messageTokenSelfHosted ?? dict.quota.messageToken)
|
||||
: dict.quota.messageToken
|
||||
: isSelfHosted
|
||||
? (dict.quota.messageApiSelfHosted ?? dict.quota.messageApi)
|
||||
? dict.quota.messageToken
|
||||
: dict.quota.messageApi
|
||||
|
||||
const tipHtml = isSelfHosted
|
||||
? (dict.quota.tipSelfHosted ?? dict.quota.tip)
|
||||
: dict.quota.tip
|
||||
const tipHtml = isSelfHosted ? dict.quota.tipSelfHosted : dict.quota.tip
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
@@ -52,7 +46,7 @@ export function QuotaLimitToast({
|
||||
aria-live="polite"
|
||||
tabIndex={0}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="relative w-[400px] overflow-hidden rounded-xl border border-border/50 bg-card p-5 shadow-soft animate-message-in"
|
||||
className="relative w-[400px] overflow-hidden rounded-xl border border-border/50 bg-card p-5 shadow-float animate-message-in"
|
||||
>
|
||||
{/* Close button */}
|
||||
<button
|
||||
@@ -85,18 +79,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,
|
||||
@@ -127,7 +109,7 @@ export function QuotaLimitToast({
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border border-border text-foreground hover:bg-muted transition-colors"
|
||||
>
|
||||
<FaGithub className="w-3.5 h-3.5" />
|
||||
<GitHubIcon className="w-3.5 h-3.5" />
|
||||
{dict.quota.selfHost}
|
||||
</a>
|
||||
<a
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
Github,
|
||||
Info,
|
||||
Monitor,
|
||||
Moon,
|
||||
@@ -13,6 +12,7 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation"
|
||||
import { useEffect, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { useChatEngine } from "@/components/chat/chat-engine"
|
||||
import { GitHubIcon } from "@/components/icons/github"
|
||||
import { ModelConfigDialog } from "@/components/model-config-dialog"
|
||||
import { SettingsHeader } from "@/components/settings/settings-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -510,7 +510,7 @@ function AboutTab() {
|
||||
const lang = pathname.split("/").filter(Boolean)[0] || i18n.defaultLocale
|
||||
const showAbout = process.env.NEXT_PUBLIC_SHOW_ABOUT_AND_NOTICE === "true"
|
||||
const isSelfHosted = process.env.NEXT_PUBLIC_SELFHOSTED === "true"
|
||||
const aboutPath = `/${lang}/about${lang === "zh" ? "/cn" : lang === "ja" ? "/ja" : ""}`
|
||||
const aboutPath = `/${lang}/about`
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
@@ -553,7 +553,7 @@ function AboutTab() {
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Github className="size-3.5" />
|
||||
<GitHubIcon className="size-3.5" />
|
||||
GitHub
|
||||
</a>
|
||||
{showAbout && (
|
||||
|
||||
@@ -12,14 +12,6 @@ function AlertDialog({
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
@@ -144,9 +136,6 @@ function AlertDialogCancel({
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
|
||||
@@ -5,13 +5,6 @@ import { Command as CommandPrimitive } from "cmdk"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
function Command({
|
||||
className,
|
||||
@@ -29,32 +22,6 @@ function Command({
|
||||
)
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = "Command Palette",
|
||||
description = "Search for a command to run...",
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogHeader className="sr-only">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent className={cn("overflow-hidden p-0", className)}>
|
||||
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandInput({
|
||||
className,
|
||||
...props
|
||||
@@ -164,30 +131,12 @@ function CommandItem({
|
||||
)
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="command-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
|
||||
@@ -24,12 +24,6 @@ function DialogPortal({
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
@@ -65,7 +59,7 @@ function DialogContent({
|
||||
"max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%]",
|
||||
"grid gap-4 p-6",
|
||||
// Refined visual treatment
|
||||
"bg-surface-0 rounded-2xl border border-border-subtle shadow-dialog",
|
||||
"bg-surface-0 rounded-2xl border border-border-subtle shadow-pop",
|
||||
// Entry/exit animations
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
@@ -151,13 +145,10 @@ function DialogDescription({
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
|
||||
@@ -39,10 +39,4 @@ function PopoverContent({
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
export { Popover, PopoverTrigger, PopoverContent }
|
||||
|
||||
@@ -55,4 +55,4 @@ function ScrollBar({
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
export { ScrollArea }
|
||||
|
||||
@@ -12,12 +12,6 @@ function Select({
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
@@ -87,19 +81,6 @@ function SelectContent({
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
@@ -124,19 +105,6 @@ function SelectItem({
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
@@ -176,12 +144,7 @@ function SelectScrollDownButton({
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
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 */
|
||||
/** The app icon in a rounded tile; the icon has its own white tile, so dark mode uses it too */
|
||||
export function BrandMark({ className }: { className?: string }) {
|
||||
return (
|
||||
<span
|
||||
@@ -16,13 +16,7 @@ export function BrandMark({ className }: { className?: string }) {
|
||||
<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"
|
||||
className="size-full object-contain"
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
|
||||
@@ -13,9 +13,7 @@ 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 */
|
||||
@@ -24,9 +22,7 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||
{
|
||||
label,
|
||||
shortcut,
|
||||
active = false,
|
||||
tooltipSide = "bottom",
|
||||
size = "md",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
@@ -40,17 +36,12 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||
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",
|
||||
"inline-flex size-8 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}
|
||||
@@ -73,8 +64,3 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
/** Thin vertical divider between toolbar groups */
|
||||
export function ToolbarDivider() {
|
||||
return <span className="mx-1 h-5 w-px shrink-0 bg-border" aria-hidden />
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
"use client"
|
||||
|
||||
import { MessageSquare, PanelRightOpen, Settings2, Shapes } from "lucide-react"
|
||||
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 { CompareDialog } from "@/components/canvas/compare-dialog"
|
||||
import { SelectionAsk } from "@/components/canvas/selection-ask"
|
||||
import {
|
||||
ChatEngineProvider,
|
||||
useChatEngine,
|
||||
} from "@/components/chat/chat-engine"
|
||||
import { ChatPanel } from "@/components/chat/chat-panel"
|
||||
import { CompareDialog } from "@/components/chat/compare-dialog"
|
||||
import { ChatVersionsProvider } from "@/components/chat/chat-versions"
|
||||
import { LobbyHero } from "@/components/chat/lobby-hero"
|
||||
import { SaveDialog } from "@/components/save-dialog"
|
||||
import { SettingsDialog } from "@/components/settings-dialog"
|
||||
@@ -100,7 +102,7 @@ function StartBar({
|
||||
onClick={() => openSettings()}
|
||||
data-testid="settings-button"
|
||||
>
|
||||
<Settings2 />
|
||||
<Settings />
|
||||
</IconButton>
|
||||
</div>
|
||||
)
|
||||
@@ -116,7 +118,9 @@ export function Workspace() {
|
||||
|
||||
return (
|
||||
<ChatEngineProvider>
|
||||
<ChatVersionsProvider>
|
||||
<WorkspaceLayout />
|
||||
</ChatVersionsProvider>
|
||||
</ChatEngineProvider>
|
||||
)
|
||||
}
|
||||
@@ -267,6 +271,13 @@ function WorkspaceLayout() {
|
||||
}
|
||||
style={isMobile ? undefined : { right: canvasRight }}
|
||||
hideOverlays={!isMobile && showHero}
|
||||
overlay={(size) => (
|
||||
<SelectionAsk
|
||||
width={size.width}
|
||||
height={size.height}
|
||||
/>
|
||||
)}
|
||||
waitForSavedLocale
|
||||
/>
|
||||
{isMobile ? (
|
||||
mobileView === "chat" &&
|
||||
|
||||
+152
-81
@@ -23,12 +23,14 @@ import {
|
||||
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"
|
||||
|
||||
/**
|
||||
@@ -54,26 +56,38 @@ 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
|
||||
}
|
||||
|
||||
/** An export as draw.io's export action takes it: the format, and for PNG
|
||||
* its scale, width cap and the page to render (pageId) */
|
||||
export interface ExportRequest {
|
||||
format: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/** What draw.io answered: the image (a data URL, or SVG text) in data; for
|
||||
* format "xml" the document in xml instead */
|
||||
export interface ExportResult {
|
||||
data?: string
|
||||
xml?: string
|
||||
}
|
||||
|
||||
interface DiagramContextType {
|
||||
chartXML: string
|
||||
// chartXML right away, before the re-render (loadDiagram sets both)
|
||||
chartXMLRef: React.MutableRefObject<string>
|
||||
latestSvg: string
|
||||
// The diagram's latest SVG export, a fallback thumbnail for saves
|
||||
latestSvgRef: React.MutableRefObject<string>
|
||||
loadDiagram: (
|
||||
chart: string,
|
||||
skipValidation?: boolean,
|
||||
mode?: LoadMode,
|
||||
meta?: { toolCallId?: string },
|
||||
meta?: { toolCallId?: string; pageId?: string | null },
|
||||
) => string | null
|
||||
// Returns the export's tag (empty when draw.io is not there yet)
|
||||
handleExport: () => string
|
||||
// Pending exports by tag; a plain export's resolver gets the first
|
||||
// page's XML
|
||||
exportResolversRef: React.MutableRefObject<
|
||||
Record<string, (data: string, xml?: string) => void>
|
||||
>
|
||||
/** The XML of the page on screen, exported from draw.io */
|
||||
fetchDiagramXml: () => Promise<string>
|
||||
drawioRef: React.MutableRefObject<DrawioFrameHandle | null>
|
||||
handleDiagramExport: (data: DrawioExportEvent) => void
|
||||
handleDiagramAutoSave: (data: { xml?: string }) => void
|
||||
@@ -83,10 +97,23 @@ interface DiagramContextType {
|
||||
format: ExportFormat,
|
||||
sessionId?: string,
|
||||
successMessage?: string,
|
||||
) => void
|
||||
) => Promise<void>
|
||||
getThumbnailSvg: () => Promise<string | null>
|
||||
getVersionSvg: () => Promise<string | null>
|
||||
captureValidationPng: () => Promise<string | null>
|
||||
/** One export with its own result; null when draw.io does not answer
|
||||
* in time (the MCP shell answers the server's export requests with it) */
|
||||
requestExport: (
|
||||
request: ExportRequest,
|
||||
timeoutMs?: number,
|
||||
) => Promise<ExportResult | null>
|
||||
/** Show a document for an export only (the MCP's one-page projection of
|
||||
* another page): not recorded as the diagram, its autosaves ignored,
|
||||
* until the next loadDiagram puts the real document back */
|
||||
showTransient: (xml: string) => void
|
||||
/** A full load was sent and draw.io has not reported it yet: the
|
||||
* editor still shows the previous document */
|
||||
hasPendingLoad: () => boolean
|
||||
isDrawioReady: boolean
|
||||
onDrawioLoad: () => void
|
||||
resetDrawioReady: () => void
|
||||
@@ -104,11 +131,11 @@ 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" | "version"
|
||||
type ExportTag = "thumbnail" | "validation" | "version" | "fetch" | "save"
|
||||
|
||||
export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
const [chartXML, setChartXML] = useState<string>("")
|
||||
const [latestSvg, setLatestSvg] = useState<string>("")
|
||||
const latestSvgRef = useRef("")
|
||||
const [isDrawioReady, setIsDrawioReady] = useState(false)
|
||||
const hasCalledOnLoadRef = useRef(false)
|
||||
const mountedRef = useRef(true)
|
||||
@@ -121,7 +148,7 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
const drawioRef = useRef<DrawioFrameHandle | null>(null)
|
||||
// Pending exports, keyed by their export tag
|
||||
const exportResolversRef = useRef<
|
||||
Record<string, (data: string, xml?: string) => void>
|
||||
Record<string, (result: ExportResult) => void>
|
||||
>({})
|
||||
const exportSeqRef = useRef(0)
|
||||
// Track latest chartXML for restoration after remount
|
||||
@@ -134,17 +161,34 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
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)
|
||||
// A transient document (showTransient) is on the canvas, and the page
|
||||
// the user was on before it
|
||||
const transientRef = useRef(false)
|
||||
const pageBeforeTransientRef = 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) => {
|
||||
const fullLoad = (
|
||||
xml: string,
|
||||
pageId: string | null = useCanvasStore.getState().currentPageId,
|
||||
) => {
|
||||
if (!drawioRef.current) return
|
||||
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
|
||||
@@ -169,26 +213,15 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
setChartXML(xml)
|
||||
}
|
||||
|
||||
const handleExport = () => {
|
||||
if (!drawioRef.current) return ""
|
||||
// Export of the current state (for the chat and edit_diagram)
|
||||
const tag = `fetch-${++exportSeqRef.current}`
|
||||
drawioRef.current.exportDiagram({
|
||||
format: "xmlsvg",
|
||||
message: tag,
|
||||
})
|
||||
return tag
|
||||
}
|
||||
|
||||
// Export with a tag in `message` (draw.io echoes it back in the export
|
||||
// event) and wait for that result. Resolves to null on timeout, which is
|
||||
// expected occasionally.
|
||||
// (Reads refs only, so it keeps one identity)
|
||||
const requestTaggedExport = useCallback(
|
||||
(tag: ExportTag, format: "xmlsvg" | "svg" | "png", timeoutMs: number) =>
|
||||
new Promise<string | null>((resolve) => {
|
||||
new Promise<ExportResult | null>((resolve) => {
|
||||
const id = `${tag}-${++exportSeqRef.current}`
|
||||
const finish = (value: string | null) => {
|
||||
const finish = (value: ExportResult | null) => {
|
||||
clearTimeout(timer)
|
||||
delete exportResolversRef.current[id]
|
||||
resolve(value)
|
||||
@@ -201,20 +234,18 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
)
|
||||
|
||||
// Get current diagram as SVG for thumbnail (used by session storage).
|
||||
// One identity: the chat's auto-save depends on it, and each thumbnail
|
||||
// renders this provider again (latestSvg), which would otherwise start
|
||||
// the next save
|
||||
// One identity: the chat's auto-save effect depends on it
|
||||
const getThumbnailSvg = useCallback(async (): Promise<string | null> => {
|
||||
if (!drawioRef.current) return null
|
||||
// Don't export if diagram is empty
|
||||
if (!isRealDiagram(chartXMLRef.current)) return null
|
||||
|
||||
// xmlsvg exports return an SVG data URL
|
||||
const svgData = await requestTaggedExport("thumbnail", "xmlsvg", 3000)
|
||||
if (svgData?.startsWith("data:image/svg")) {
|
||||
// Update latestSvg so it's available for future saves
|
||||
setLatestSvg(svgData)
|
||||
return svgData
|
||||
const result = await requestTaggedExport("thumbnail", "xmlsvg", 3000)
|
||||
if (result?.data?.startsWith("data:image/svg")) {
|
||||
// Kept for later saves that take no fresh thumbnail
|
||||
latestSvgRef.current = result.data
|
||||
return result.data
|
||||
}
|
||||
return null
|
||||
}, [requestTaggedExport])
|
||||
@@ -222,8 +253,8 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
// 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
|
||||
const result = await requestTaggedExport("version", "svg", 4000)
|
||||
return result?.data?.startsWith("data:image/svg") ? result.data : null
|
||||
}
|
||||
|
||||
// Capture current diagram as PNG for VLM validation
|
||||
@@ -232,20 +263,75 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
// Don't export if diagram is empty
|
||||
if (!isRealDiagram(chartXMLRef.current)) return null
|
||||
|
||||
const pngData = await requestTaggedExport("validation", "png", 5000)
|
||||
const result = await requestTaggedExport("validation", "png", 5000)
|
||||
// PNG data should be a base64 data URL
|
||||
return pngData?.startsWith("data:image/png") ? pngData : null
|
||||
return result?.data?.startsWith("data:image/png") ? result.data : null
|
||||
}
|
||||
|
||||
// The page the user is viewing (the first one with an external draw.io,
|
||||
// which cannot tell us), for the chat and edit_diagram.
|
||||
// Not written to chartXML: exports don't change the diagram, and the
|
||||
// export's xml 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 fetchDiagramXml = async (): Promise<string> => {
|
||||
const result = await requestTaggedExport("fetch", "xmlsvg", 10000)
|
||||
if (!result?.data) {
|
||||
throw new Error("Chart export timed out after 10 seconds")
|
||||
}
|
||||
latestSvgRef.current = result.data
|
||||
return extractDiagramXML(
|
||||
result.data,
|
||||
useCanvasStore.getState().currentPageId,
|
||||
)
|
||||
}
|
||||
|
||||
// Like requestTaggedExport, with the request's other parameters (a PNG's
|
||||
// page and width) and both parts of the answer
|
||||
const requestExport = useCallback(
|
||||
(request: ExportRequest, timeoutMs = 10000) =>
|
||||
new Promise<ExportResult | null>((resolve) => {
|
||||
if (!drawioRef.current) {
|
||||
resolve(null)
|
||||
return
|
||||
}
|
||||
const id = `export-${++exportSeqRef.current}`
|
||||
const finish = (value: ExportResult | null) => {
|
||||
clearTimeout(timer)
|
||||
delete exportResolversRef.current[id]
|
||||
resolve(value)
|
||||
}
|
||||
const timer = setTimeout(() => finish(null), timeoutMs)
|
||||
exportResolversRef.current[id] = finish
|
||||
drawioRef.current.exportDiagram({ ...request, message: id })
|
||||
}),
|
||||
[],
|
||||
)
|
||||
|
||||
const showTransient = (xml: string) => {
|
||||
if (!transientRef.current) {
|
||||
pageBeforeTransientRef.current =
|
||||
useCanvasStore.getState().currentPageId
|
||||
}
|
||||
transientRef.current = true
|
||||
fullLoad(xml)
|
||||
}
|
||||
|
||||
const loadDiagram = (
|
||||
chart: string,
|
||||
skipValidation?: boolean,
|
||||
mode: LoadMode = "load",
|
||||
meta?: { toolCallId?: string },
|
||||
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
|
||||
// A real document ends a transient one; the user goes back to the
|
||||
// page they were on before it
|
||||
const pageBeforeTransient = transientRef.current
|
||||
? pageBeforeTransientRef.current
|
||||
: undefined
|
||||
transientRef.current = false
|
||||
let xmlToLoad = chart
|
||||
|
||||
// Validate XML structure before loading (unless skipped for internal
|
||||
@@ -300,7 +386,7 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
if (!applied) {
|
||||
// A full load replaces any preview, and its base is stale now
|
||||
resetPreview()
|
||||
fullLoad(xmlToLoad)
|
||||
fullLoad(xmlToLoad, pageBeforeTransient)
|
||||
}
|
||||
|
||||
if (mode === "commit") {
|
||||
@@ -308,6 +394,7 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
beforeXml,
|
||||
afterXml: xmlToLoad,
|
||||
toolCallId: meta?.toolCallId,
|
||||
pageId: meta?.pageId,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -319,35 +406,22 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
resetPreview()
|
||||
}
|
||||
|
||||
// Each export result goes to the caller that asked for it, by its tag
|
||||
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|version|save)-/.test(tag ?? "")) {
|
||||
exportResolversRef.current[tag as string]?.(data.data, data.xml)
|
||||
return
|
||||
}
|
||||
|
||||
// Don't write chartXML here: exports don't change the diagram, and
|
||||
// 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)
|
||||
setLatestSvg(data.data)
|
||||
|
||||
// The chat's own export (onFetchChart), not another one in flight
|
||||
const resolve =
|
||||
tag !== undefined ? exportResolversRef.current[tag] : undefined
|
||||
if (resolve) {
|
||||
delete exportResolversRef.current[tag as string]
|
||||
resolve(extractedXML)
|
||||
}
|
||||
if (!tag) return
|
||||
exportResolversRef.current[tag]?.({ data: data.data, xml: data.xml })
|
||||
}
|
||||
|
||||
// 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
|
||||
// An edit of a transient document is not the diagram's; nor is one
|
||||
// of the canvas a full load still on its way replaces (draw.io
|
||||
// reports each load, in order, so no autosave of the new document
|
||||
// comes before that)
|
||||
if (transientRef.current || pendingLoadsRef.current > 0) return
|
||||
// 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 && chartXMLRef.current) return
|
||||
@@ -362,10 +436,10 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
const emptyDiagram = BLANK_MXFILE
|
||||
// Skip validation for trusted internal template (loadDiagram also sets chartXML)
|
||||
loadDiagram(emptyDiagram, true)
|
||||
setLatestSvg("")
|
||||
latestSvgRef.current = ""
|
||||
}
|
||||
|
||||
const saveDiagramToFile = (
|
||||
const saveDiagramToFile = async (
|
||||
filename: string,
|
||||
format: ExportFormat,
|
||||
sessionId?: string,
|
||||
@@ -380,13 +454,15 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
const drawioFormat =
|
||||
format === "drawio" || format === "xmlsvg" ? "xmlsvg" : format
|
||||
|
||||
// Each save has its own tag, so two at once never swap results
|
||||
const tag = `save-${++exportSeqRef.current}`
|
||||
exportResolversRef.current[tag] = (
|
||||
exportData: string,
|
||||
fullDiagramXML?: string,
|
||||
) => {
|
||||
delete exportResolversRef.current[tag]
|
||||
// Each save has its own tag, so two at once never swap results. A
|
||||
// large PNG takes a while to render.
|
||||
const result = await requestTaggedExport("save", drawioFormat, 30000)
|
||||
if (!result?.data) {
|
||||
console.warn("Diagram export for saving timed out")
|
||||
return
|
||||
}
|
||||
const exportData = result.data
|
||||
const fullDiagramXML = result.xml
|
||||
let fileContent: string | Blob
|
||||
let mimeType: string
|
||||
let extension: string
|
||||
@@ -454,13 +530,6 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
// Export diagram - callback will be handled in handleDiagramExport
|
||||
drawioRef.current.exportDiagram({
|
||||
format: drawioFormat,
|
||||
message: tag,
|
||||
})
|
||||
}
|
||||
|
||||
// Log save event to Langfuse (just flags the trace, doesn't send content)
|
||||
const logSaveToLangfuse = async (
|
||||
filename: string,
|
||||
@@ -489,10 +558,9 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
value={{
|
||||
chartXML,
|
||||
chartXMLRef,
|
||||
latestSvg,
|
||||
latestSvgRef,
|
||||
loadDiagram,
|
||||
handleExport,
|
||||
exportResolversRef,
|
||||
fetchDiagramXml,
|
||||
drawioRef,
|
||||
handleDiagramExport,
|
||||
handleDiagramAutoSave,
|
||||
@@ -501,6 +569,9 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {
|
||||
getThumbnailSvg,
|
||||
getVersionSvg,
|
||||
captureValidationPng,
|
||||
requestExport,
|
||||
showTransient,
|
||||
hasPendingLoad: () => pendingLoadsRef.current > 0,
|
||||
isDrawioReady,
|
||||
onDrawioLoad,
|
||||
resetDrawioReady,
|
||||
|
||||
+80
-182
@@ -1,107 +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 每改一次图,聊天里就多一张带缩略图的版本卡片,可以和画布对比、恢复,也可以撤销这次修改;在画布上按 Ctrl+Z 也能一步撤回 AI 的修改。AI 刚改过的图形会在画布上标出来
|
||||
- **针对选中图形提问**:在画布上选中图形,让 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
|
||||
{
|
||||
@@ -114,157 +105,64 @@ 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 的改动会被标出,按一次 Ctrl+Z 就能撤销,AI 还能读到你选中的图形
|
||||
- draw.io 编辑器随包一起安装,装好后预览不需要联网(也可以用 `DRAWIO_BASE_URL` 改用外部的 draw.io)
|
||||
- 截图工具,AI 可以看一眼画好的图并自行修正
|
||||
- 版本历史、多页图表,下载为 `.drawio`、`.png`、`.svg` 或 `.drawio.svg`
|
||||
- 自动保存到 `~/.next-ai-drawio/`,重启后接着画
|
||||
- 可以让 AI 撤销修改,也可以在 `~/.next-ai-drawio/instructions.md` 里写下自己的画图规则
|
||||
|
||||
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响应和多提供商支持
|
||||
- **draw.io**:编辑器使用打包在 `public/drawio` 里的副本(由 `npm run dev` / `npm run build` 自动下载),应用可以直接控制它
|
||||
|
||||
图表以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>
|
||||
|
||||
@@ -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 # 或其他豆包模型
|
||||
@@ -394,7 +392,7 @@ AI_MODEL=doubao-seed-1-8-251215,doubao-seed-1-6-flash,doubao-seed-1-6-pro
|
||||
| `provider` | 是 | 提供商类型(`openai`, `anthropic`, `google`, `bedrock` 等) |
|
||||
| `models` | 是 | 模型 ID 列表 |
|
||||
| `default` | 否 | 设为 `true` 表示默认选中该提供商的第一个模型 |
|
||||
| `apiKeyEnv` | 否 | 自定义 API Key 环境变量名(默认使用提供商标准变量如 `OPENAI_API_KEY`) |
|
||||
| `apiKeyEnv` | 否 | 自定义 API Key 环境变量名(默认使用提供商标准变量如 `OPENAI_API_KEY`)。也可以写成环境变量名数组,每次请求从有值的变量中随机选一个,把负载分摊到多个 Key 上 |
|
||||
| `baseUrlEnv` | 否 | 自定义 Base URL 环境变量名 |
|
||||
|
||||
### 说明
|
||||
|
||||
@@ -68,47 +68,15 @@ cp env.example .env.local
|
||||
|
||||
## 第三步 — 选择部署类型
|
||||
|
||||
### 选项 A:不使用 R2 部署(简单,免费)
|
||||
### 选项 A:不使用 R2 部署(默认,免费)
|
||||
|
||||
如果您不需要 ISR 缓存,可以选择不使用 R2 进行部署:
|
||||
|
||||
**1. 使用简单的 `open-next.config.ts`:**
|
||||
|
||||
```ts
|
||||
import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"
|
||||
|
||||
export default defineCloudflareConfig({})
|
||||
```
|
||||
|
||||
**2. 使用简单的 `wrangler.jsonc`(不包含 r2_buckets):**
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
"main": ".open-next/worker.js",
|
||||
"name": "next-ai-draw-io-worker",
|
||||
"compatibility_date": "2025-12-08",
|
||||
"compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
|
||||
"assets": {
|
||||
"directory": ".open-next/assets",
|
||||
"binding": "ASSETS"
|
||||
},
|
||||
"services": [
|
||||
{
|
||||
"binding": "WORKER_SELF_REFERENCE",
|
||||
"service": "next-ai-draw-io-worker"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
直接跳至 **第四步**。
|
||||
仓库自带的就是这套配置:`open-next.config.ts` 为 `defineCloudflareConfig({})`,`wrangler.jsonc` 中没有 `r2_buckets`。无需改动任何文件,直接跳至 **第四步**。
|
||||
|
||||
---
|
||||
|
||||
### 选项 B:使用 R2 部署(完整的 ISR 支持)
|
||||
### 选项 B:使用 R2 部署(可选,用于 ISR 缓存)
|
||||
|
||||
R2 开启了 **增量静态再生 (ISR)** 缓存功能。需要在您的 Cloudflare 账户中绑定支付方式。
|
||||
R2 为 OpenNext 提供存放 **增量静态再生 (ISR)** 页面的空间。本应用目前没有 ISR 页面,只有在您自己添加了此类页面时才需要这一步。需要在您的 Cloudflare 账户中绑定支付方式。
|
||||
|
||||
**1. 在 Cloudflare 控制台中创建 R2 存储桶:**
|
||||
|
||||
@@ -127,7 +95,7 @@ export default defineCloudflareConfig({
|
||||
})
|
||||
```
|
||||
|
||||
**3. 配置 `wrangler.jsonc`(包含 R2):**
|
||||
**3. 在 `wrangler.jsonc` 中加入 `r2_buckets`:**
|
||||
|
||||
```jsonc
|
||||
{
|
||||
@@ -157,6 +125,8 @@ export default defineCloudflareConfig({
|
||||
|
||||
> **重要提示:** `bucket_name` 必须与您在 Cloudflare 控制台中创建的名称完全一致。
|
||||
|
||||
> **注意:** 定时重新验证(页面或 fetch 上的 `revalidate`)还需要在 `open-next.config.ts` 中配置 `queue`,请参阅 OpenNext 的 Cloudflare 缓存文档。
|
||||
|
||||
---
|
||||
|
||||
## 第四步 — 注册 workers.dev 子域名(仅首次需要)
|
||||
@@ -264,4 +234,4 @@ npm run preview
|
||||
| API 路由 | 支持 | 支持 |
|
||||
| 配置复杂度 | 简单 | 中等 |
|
||||
|
||||
测试或简单应用请选择 **不使用 R2**。需要 ISR 缓存的生产环境应用请选择 **使用 R2**。
|
||||
仓库默认 **不使用 R2**。只有当您添加了需要 ISR 缓存的页面时,才选择 **使用 R2**。
|
||||
|
||||
@@ -14,7 +14,7 @@ Next AI Draw.io 自带一份 draw.io。`npm run build`(包括 Docker 构建)
|
||||
|
||||
构建会从 [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`。构建时就会使用这份副本。
|
||||
- 在另一台机器上下载 `packages/mcp-server/src/drawio-version.json` 里写明的那个版本的 `draw.war`,解压到 `public/drawio`(删掉 `WEB-INF` 和 `META-INF`),再把版本号(例如 `v32.0.2`)写进 `public/drawio/.version`。构建时就会使用这份副本。
|
||||
- 或者在能联网的机器上构建镜像,再拷到离线网络里。
|
||||
|
||||
## 来自其他网站的图片
|
||||
|
||||
@@ -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
|
||||
@@ -409,7 +407,7 @@ This is shorthand for the equivalent `ai-models.json`. For multiple providers or
|
||||
| `provider` | Yes | Provider type (`openai`, `anthropic`, `google`, `bedrock`, etc.) |
|
||||
| `models` | Yes | List of model IDs |
|
||||
| `default` | No | Set to `true` to auto-select this provider's first model as default |
|
||||
| `apiKeyEnv` | No | Custom API key env var name (defaults to provider's standard var like `OPENAI_API_KEY`) |
|
||||
| `apiKeyEnv` | No | Custom API key env var name (defaults to provider's standard var like `OPENAI_API_KEY`). May also be an array of env var names: each request picks one that has a value at random, spreading load over several keys |
|
||||
| `baseUrlEnv` | No | Custom base URL env var name |
|
||||
|
||||
### Notes
|
||||
|
||||
@@ -68,47 +68,15 @@ Fill in the same values there.
|
||||
|
||||
## Step 3 — Choose your deployment type
|
||||
|
||||
### Option A: Deploy WITHOUT R2 (Simple, Free)
|
||||
### Option A: Deploy WITHOUT R2 (Default, Free)
|
||||
|
||||
If you don't need ISR caching, you can deploy without R2:
|
||||
|
||||
**1. Use simple `open-next.config.ts`:**
|
||||
|
||||
```ts
|
||||
import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"
|
||||
|
||||
export default defineCloudflareConfig({})
|
||||
```
|
||||
|
||||
**2. Use simple `wrangler.jsonc` (without r2_buckets):**
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
"main": ".open-next/worker.js",
|
||||
"name": "next-ai-draw-io-worker",
|
||||
"compatibility_date": "2025-12-08",
|
||||
"compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
|
||||
"assets": {
|
||||
"directory": ".open-next/assets",
|
||||
"binding": "ASSETS"
|
||||
},
|
||||
"services": [
|
||||
{
|
||||
"binding": "WORKER_SELF_REFERENCE",
|
||||
"service": "next-ai-draw-io-worker"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Skip to **Step 4**.
|
||||
This is how the repository is configured: `open-next.config.ts` is `defineCloudflareConfig({})` and `wrangler.jsonc` has no `r2_buckets`. Nothing to change here. Skip to **Step 4**.
|
||||
|
||||
---
|
||||
|
||||
### Option B: Deploy WITH R2 (Full ISR Support)
|
||||
### Option B: Deploy WITH R2 (Optional, ISR caching)
|
||||
|
||||
R2 enables **Incremental Static Regeneration (ISR)** caching. Requires a payment method on your Cloudflare account.
|
||||
R2 gives OpenNext a place to store **Incremental Static Regeneration (ISR)** pages. This app currently has no ISR pages, so you only need this step if you add some. Requires a payment method on your Cloudflare account.
|
||||
|
||||
**1. Create an R2 bucket** in the Cloudflare Dashboard:
|
||||
|
||||
@@ -127,7 +95,7 @@ export default defineCloudflareConfig({
|
||||
})
|
||||
```
|
||||
|
||||
**3. Configure `wrangler.jsonc` (with R2):**
|
||||
**3. Add `r2_buckets` to `wrangler.jsonc`:**
|
||||
|
||||
```jsonc
|
||||
{
|
||||
@@ -157,6 +125,8 @@ export default defineCloudflareConfig({
|
||||
|
||||
> **Important:** The `bucket_name` must exactly match the name you created in the Cloudflare dashboard.
|
||||
|
||||
> **Note:** Time-based revalidation (`revalidate` on a page or fetch) also needs a `queue` in `open-next.config.ts`. See the OpenNext Cloudflare caching docs.
|
||||
|
||||
---
|
||||
|
||||
## Step 4 — Register a workers.dev subdomain (first-time only)
|
||||
@@ -264,4 +234,4 @@ npm run preview
|
||||
| API Routes | Yes | Yes |
|
||||
| Setup Complexity | Simple | Moderate |
|
||||
|
||||
Choose **without R2** for testing or simple apps. Choose **with R2** for production apps that need ISR caching.
|
||||
The repository defaults to **without R2**. Choose **with R2** only if you add pages that need ISR caching.
|
||||
|
||||
@@ -14,7 +14,7 @@ No separate draw.io container is needed.
|
||||
|
||||
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.
|
||||
- On another machine, download `draw.war` for the version in `packages/mcp-server/src/drawio-version.json`, 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
|
||||
|
||||
+81
-182
@@ -1,105 +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 が図を変更するたびに、サムネイル付きのバージョンカードがチャットに表示されます。キャンバスと比較したり、復元したり、その変更を取り消したりできます。キャンバスで Ctrl+Z を押しても AI の変更を一度に元に戻せます。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
|
||||
{
|
||||
@@ -112,158 +105,64 @@ 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 など)
|
||||
- プレビューは Web アプリと同じキャンバス。AI の変更には印が付き、Ctrl+Z 一回で元に戻せ、選択中の図形を AI が読み取れる
|
||||
- draw.io エディターはパッケージに同梱されているので、インストール後はオフラインでもプレビューが動く(外部の draw.io を使うなら `DRAWIO_BASE_URL` を設定する)
|
||||
- スクリーンショットツール。AI が描いた結果を確認して自分で直せる
|
||||
- バージョン履歴、複数ページのダイアグラム、`.drawio`、`.png`、`.svg`、`.drawio.svg` でのダウンロード
|
||||
- `~/.next-ai-drawio/` への自動保存。再起動後も続きから描ける
|
||||
- AI に元に戻す操作を頼める。独自の作図ルールは `~/.next-ai-drawio/instructions.md` に書ける
|
||||
|
||||
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レスポンスとマルチプロバイダーサポート
|
||||
- **draw.io**:エディターは `public/drawio` に同梱したコピー(`npm run dev` / `npm run build` で自動ダウンロード)で動作し、アプリから直接操作できます
|
||||
|
||||
ダイアグラムは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>
|
||||
|
||||
@@ -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 モデル
|
||||
@@ -394,7 +392,7 @@ AI_MODEL=doubao-seed-1-8-251215,doubao-seed-1-6-flash,doubao-seed-1-6-pro
|
||||
| `provider` | はい | プロバイダータイプ(`openai`, `anthropic`, `google`, `bedrock` など) |
|
||||
| `models` | はい | モデルIDのリスト |
|
||||
| `default` | いいえ | `true` に設定すると、そのプロバイダーの最初のモデルがデフォルトで選択されます |
|
||||
| `apiKeyEnv` | いいえ | カスタムAPIキー環境変数名(デフォルトは `OPENAI_API_KEY` などの標準変数) |
|
||||
| `apiKeyEnv` | いいえ | カスタムAPIキー環境変数名(デフォルトは `OPENAI_API_KEY` などの標準変数)。環境変数名の配列も指定でき、リクエストごとに値のある変数から1つがランダムに選ばれます(複数キーへの負荷分散) |
|
||||
| `baseUrlEnv` | いいえ | カスタムBase URL環境変数名 |
|
||||
|
||||
### 備考
|
||||
|
||||
@@ -68,47 +68,15 @@ cp env.example .env.local
|
||||
|
||||
## ステップ 3 — デプロイタイプの選択
|
||||
|
||||
### オプション A: R2 なしでのデプロイ(シンプル、無料)
|
||||
### オプション A: R2 なしでのデプロイ(デフォルト、無料)
|
||||
|
||||
ISR キャッシュが不要な場合は、R2 なしでデプロイできます:
|
||||
|
||||
**1. シンプルな `open-next.config.ts` を使用:**
|
||||
|
||||
```ts
|
||||
import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"
|
||||
|
||||
export default defineCloudflareConfig({})
|
||||
```
|
||||
|
||||
**2. シンプルな `wrangler.jsonc` を使用(r2_buckets なし):**
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
"main": ".open-next/worker.js",
|
||||
"name": "next-ai-draw-io-worker",
|
||||
"compatibility_date": "2025-12-08",
|
||||
"compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
|
||||
"assets": {
|
||||
"directory": ".open-next/assets",
|
||||
"binding": "ASSETS"
|
||||
},
|
||||
"services": [
|
||||
{
|
||||
"binding": "WORKER_SELF_REFERENCE",
|
||||
"service": "next-ai-draw-io-worker"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**ステップ 4** へ進んでください。
|
||||
リポジトリはこの構成のままです。`open-next.config.ts` は `defineCloudflareConfig({})` で、`wrangler.jsonc` に `r2_buckets` はありません。ファイルを変更する必要はないので、**ステップ 4** へ進んでください。
|
||||
|
||||
---
|
||||
|
||||
### オプション B: R2 ありでのデプロイ(完全な ISR サポート)
|
||||
### オプション B: R2 ありでのデプロイ(オプション、ISR キャッシュ用)
|
||||
|
||||
R2 を使用すると **Incremental Static Regeneration (ISR)** キャッシュが有効になります。これには Cloudflare アカウントに支払い方法の登録が必要です。
|
||||
R2 は OpenNext が **Incremental Static Regeneration (ISR)** ページを保存する場所になります。このアプリには現在 ISR ページがないため、自分で ISR ページを追加した場合にだけ必要です。Cloudflare アカウントに支払い方法の登録が必要です。
|
||||
|
||||
**1. R2 バケットの作成**(Cloudflare ダッシュボードにて):
|
||||
|
||||
@@ -127,7 +95,7 @@ export default defineCloudflareConfig({
|
||||
})
|
||||
```
|
||||
|
||||
**3. `wrangler.jsonc` の設定(R2 あり):**
|
||||
**3. `wrangler.jsonc` に `r2_buckets` を追加:**
|
||||
|
||||
```jsonc
|
||||
{
|
||||
@@ -157,6 +125,8 @@ export default defineCloudflareConfig({
|
||||
|
||||
> **重要:** `bucket_name` は Cloudflare ダッシュボードで作成した名前と完全に一致させる必要があります。
|
||||
|
||||
> **注意:** 時間ベースの再検証(ページや fetch の `revalidate`)には、`open-next.config.ts` で `queue` の設定も必要です。OpenNext の Cloudflare キャッシュドキュメントを参照してください。
|
||||
|
||||
---
|
||||
|
||||
## ステップ 4 — workers.dev サブドメインの登録(初回のみ)
|
||||
@@ -264,4 +234,4 @@ npm run preview
|
||||
| API ルート | あり | あり |
|
||||
| 設定の複雑さ | シンプル | 普通 |
|
||||
|
||||
テストやシンプルなアプリには **R2 なし** を選んでください。ISR キャッシュが必要な本番アプリには **R2 あり** を選んでください。
|
||||
リポジトリのデフォルトは **R2 なし** です。ISR キャッシュが必要なページを追加した場合にだけ **R2 あり** を選んでください。
|
||||
|
||||
@@ -14,7 +14,7 @@ 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` に書き込みます。ビルドはこのコピーを使います。
|
||||
- 別のマシンで `packages/mcp-server/src/drawio-version.json` に書かれたバージョンの `draw.war` をダウンロードし、`public/drawio` に展開します(`WEB-INF` と `META-INF` は削除)。さらにバージョン(例:`v32.0.2`)を `public/drawio/.version` に書き込みます。ビルドはこのコピーを使います。
|
||||
- インターネットに接続できるマシンでイメージをビルドし、オフライン環境に転送します。
|
||||
|
||||
## ほかのサイトの画像
|
||||
|
||||
@@ -29,6 +29,7 @@ const messageItemSchema = z
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
// The fields read here; every other field is passed on to AI.chatCompletions
|
||||
const messageSchema = z
|
||||
.object({
|
||||
messages: z.array(messageItemSchema),
|
||||
@@ -36,21 +37,6 @@ const messageSchema = z
|
||||
stream: z.boolean().optional(),
|
||||
tools: z.any().optional(),
|
||||
tool_choice: z.any().optional(),
|
||||
functions: z.any().optional(),
|
||||
function_call: z.any().optional(),
|
||||
temperature: z.number().optional(),
|
||||
top_p: z.number().optional(),
|
||||
max_tokens: z.number().optional(),
|
||||
presence_penalty: z.number().optional(),
|
||||
frequency_penalty: z.number().optional(),
|
||||
stop: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
response_format: z.any().optional(),
|
||||
seed: z.number().optional(),
|
||||
user: z.string().optional(),
|
||||
n: z.number().int().optional(),
|
||||
logit_bias: z.record(z.string(), z.number()).optional(),
|
||||
parallel_tool_calls: z.boolean().optional(),
|
||||
stream_options: z.any().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
@@ -61,12 +47,6 @@ const ALLOWED_MODELS = [
|
||||
"@tx/deepseek-ai/deepseek-v3-0324",
|
||||
]
|
||||
|
||||
const MODEL_ALIASES: Record<string, string> = {
|
||||
"deepseek-v3.2": "@tx/deepseek-ai/deepseek-v32",
|
||||
"deepseek-r1-0528": "@tx/deepseek-ai/deepseek-r1-0528",
|
||||
"deepseek-v3-0324": "@tx/deepseek-ai/deepseek-v3-0324",
|
||||
}
|
||||
|
||||
/**
|
||||
* Create standardized JSON response
|
||||
*/
|
||||
@@ -145,8 +125,16 @@ export async function onRequest({ request, env }: any) {
|
||||
)
|
||||
}
|
||||
|
||||
const { messages, model, stream, tools, tool_choice, ...extraParams } =
|
||||
parseResult.data
|
||||
// stream is taken out so it is not passed on: AI.chatCompletions
|
||||
// only streams, and every caller reads a stream
|
||||
const {
|
||||
messages,
|
||||
model,
|
||||
stream: _,
|
||||
tools,
|
||||
tool_choice,
|
||||
...extraParams
|
||||
} = parseResult.data
|
||||
|
||||
// Validate messages
|
||||
const userMessages = messages.filter(
|
||||
@@ -165,14 +153,13 @@ export async function onRequest({ request, env }: any) {
|
||||
}
|
||||
|
||||
// Resolve model
|
||||
const requestedModel = model || ALLOWED_MODELS[0]
|
||||
const selectedModel = MODEL_ALIASES[requestedModel] || requestedModel
|
||||
const selectedModel = model || ALLOWED_MODELS[0]
|
||||
|
||||
if (!ALLOWED_MODELS.includes(selectedModel)) {
|
||||
return createResponse(
|
||||
{
|
||||
error: {
|
||||
message: `Invalid model: ${requestedModel}.`,
|
||||
message: `Invalid model: ${selectedModel}.`,
|
||||
type: "invalid_request_error",
|
||||
},
|
||||
},
|
||||
@@ -181,39 +168,10 @@ export async function onRequest({ request, env }: any) {
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[EdgeOne] Model: ${selectedModel}, Tools: ${tools?.length || 0}, Stream: ${stream ?? true}`,
|
||||
`[EdgeOne] Model: ${selectedModel}, Tools: ${tools?.length || 0}`,
|
||||
)
|
||||
|
||||
try {
|
||||
const isStream = !!stream
|
||||
|
||||
// Non-streaming: return mock response for validation
|
||||
// AI.chatCompletions doesn't support non-streaming mode
|
||||
if (!isStream) {
|
||||
const mockResponse = {
|
||||
id: `chatcmpl-${Date.now()}`,
|
||||
object: "chat.completion",
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: selectedModel,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "OK",
|
||||
},
|
||||
finish_reason: "stop",
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
prompt_tokens: 10,
|
||||
completion_tokens: 1,
|
||||
total_tokens: 11,
|
||||
},
|
||||
}
|
||||
return createResponse(mockResponse)
|
||||
}
|
||||
|
||||
// Build AI.chatCompletions options for streaming
|
||||
const aiOptions: any = {
|
||||
...extraParams,
|
||||
|
||||
@@ -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
|
||||
|
||||
Vendored
+3
-69
@@ -2,29 +2,6 @@
|
||||
* Type declarations for Electron API exposed via preload script
|
||||
*/
|
||||
|
||||
/** Configuration preset interface */
|
||||
interface ConfigPreset {
|
||||
id: string
|
||||
name: string
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
config: {
|
||||
AI_PROVIDER?: string
|
||||
AI_MODEL?: string
|
||||
AI_API_KEY?: string
|
||||
AI_BASE_URL?: string
|
||||
TEMPERATURE?: string
|
||||
[key: string]: string | undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Result of applying a preset */
|
||||
interface ApplyPresetResult {
|
||||
success: boolean
|
||||
error?: string
|
||||
env?: Record<string, string>
|
||||
}
|
||||
|
||||
/** Proxy configuration interface */
|
||||
interface ProxyConfig {
|
||||
httpProxy?: string
|
||||
@@ -35,7 +12,6 @@ interface ProxyConfig {
|
||||
interface SetProxyResult {
|
||||
success: boolean
|
||||
error?: string
|
||||
devMode?: boolean
|
||||
}
|
||||
|
||||
/** Result of setting user locale */
|
||||
@@ -48,31 +24,17 @@ declare global {
|
||||
interface Window {
|
||||
/** Main window Electron API */
|
||||
electronAPI?: {
|
||||
/** Current platform (darwin, win32, linux) */
|
||||
platform: NodeJS.Platform
|
||||
/** Whether running in Electron environment */
|
||||
isElectron: boolean
|
||||
/** Get application version */
|
||||
getVersion: () => Promise<string>
|
||||
/** Minimize the window */
|
||||
minimize: () => void
|
||||
/** Maximize/restore the window */
|
||||
maximize: () => void
|
||||
/** Close the window */
|
||||
close: () => void
|
||||
/** Get proxy configuration */
|
||||
getProxy: () => Promise<ProxyConfig>
|
||||
/** Set proxy configuration (saves and restarts server) */
|
||||
setProxy: (config: ProxyConfig) => Promise<SetProxyResult>
|
||||
/** Get user's preferred locale */
|
||||
getUserLocale: () => Promise<
|
||||
"en" | "zh" | "ja" | "zh-Hant" | undefined
|
||||
>
|
||||
/** Set user's preferred locale */
|
||||
setUserLocale: (locale: string) => Promise<SetUserLocaleResult>
|
||||
/**
|
||||
* Call back after the server restarted on the same port (another
|
||||
* preset); returns a function that stops the calls
|
||||
* Call back after the server restarted on the same port (proxy
|
||||
* change); returns a function that stops the calls
|
||||
*/
|
||||
onServerRestarted?: (callback: () => void) => () => void
|
||||
/** A chat was saved: open this port next launch */
|
||||
@@ -80,35 +42,7 @@ declare global {
|
||||
/** The page loaded with this many chats */
|
||||
chatsLoaded?: (count: number) => Promise<void>
|
||||
}
|
||||
|
||||
/** Settings window Electron API */
|
||||
settingsAPI?: {
|
||||
/** Get all configuration presets */
|
||||
getPresets: () => Promise<ConfigPreset[]>
|
||||
/** Get current preset ID */
|
||||
getCurrentPresetId: () => Promise<string | null>
|
||||
/** Get current preset */
|
||||
getCurrentPreset: () => Promise<ConfigPreset | null>
|
||||
/** Save (create or update) a preset */
|
||||
savePreset: (preset: {
|
||||
id?: string
|
||||
name: string
|
||||
config: Record<string, string | undefined>
|
||||
}) => Promise<ConfigPreset>
|
||||
/** Delete a preset */
|
||||
deletePreset: (id: string) => Promise<boolean>
|
||||
/** Apply a preset (sets environment variables and restarts server) */
|
||||
applyPreset: (id: string) => Promise<ApplyPresetResult>
|
||||
/** Close settings window */
|
||||
close: () => void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type {
|
||||
ApplyPresetResult,
|
||||
ConfigPreset,
|
||||
ProxyConfig,
|
||||
SetProxyResult,
|
||||
SetUserLocaleResult,
|
||||
}
|
||||
export type { ProxyConfig }
|
||||
|
||||
+2
-161
@@ -1,23 +1,9 @@
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
dialog,
|
||||
Menu,
|
||||
type MenuItemConstructorOptions,
|
||||
shell,
|
||||
} from "electron"
|
||||
import {
|
||||
applyPresetToEnv,
|
||||
getAllPresets,
|
||||
getCurrentPresetId,
|
||||
setCurrentPreset,
|
||||
} from "./config-manager"
|
||||
import { app, Menu, type MenuItemConstructorOptions, shell } from "electron"
|
||||
import { getMenuTranslations, getPreferredLocale } from "./menu-i18n"
|
||||
import { restartNextServer } from "./next-server"
|
||||
import { showSettingsWindow } from "./settings-window"
|
||||
|
||||
/**
|
||||
* Build and set the application menu with i18n support
|
||||
* (call again when the language changes)
|
||||
*/
|
||||
export function buildAppMenu(): void {
|
||||
const template = getMenuTemplate()
|
||||
@@ -25,75 +11,6 @@ export function buildAppMenu(): void {
|
||||
Menu.setApplicationMenu(menu)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild the menu (call this when presets change or language changes)
|
||||
*/
|
||||
export function rebuildAppMenu(): void {
|
||||
buildAppMenu()
|
||||
}
|
||||
|
||||
// Number of the latest preset switch
|
||||
let lastSwitch = 0
|
||||
|
||||
/**
|
||||
* Apply a preset and restart the server so it takes effect.
|
||||
* If the restart fails, go back to the previous preset and restart again,
|
||||
* so the running server always matches the saved current preset.
|
||||
* Throws an error describing the outcome on failure.
|
||||
*/
|
||||
export async function switchPreset(
|
||||
id: string,
|
||||
): Promise<Record<string, string>> {
|
||||
const previousPresetId = getCurrentPresetId()
|
||||
const env = applyPresetToEnv(id)
|
||||
if (!env) {
|
||||
throw new Error("Preset not found")
|
||||
}
|
||||
const switchNumber = ++lastSwitch
|
||||
rebuildAppMenu()
|
||||
|
||||
// In development, scripts/electron-dev.mjs restarts the Next.js dev server
|
||||
if (!app.isPackaged) {
|
||||
return env
|
||||
}
|
||||
|
||||
try {
|
||||
await restartNextServer()
|
||||
return env
|
||||
} catch (error) {
|
||||
console.error("Failed to restart server:", error)
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
|
||||
// A newer switch started meanwhile (also of this same preset), or
|
||||
// the preset was deleted: its own restart follows, and undoing
|
||||
// would lose that choice
|
||||
if (switchNumber !== lastSwitch || getCurrentPresetId() !== id) {
|
||||
throw new Error(
|
||||
`The server could not be restarted.\n\nError: ${reason}`,
|
||||
)
|
||||
}
|
||||
|
||||
// Revert to previous preset on failure
|
||||
if (!previousPresetId || !applyPresetToEnv(previousPresetId)) {
|
||||
setCurrentPreset(null)
|
||||
}
|
||||
// Rebuild menu to restore previous checkmark state
|
||||
rebuildAppMenu()
|
||||
|
||||
try {
|
||||
await restartNextServer()
|
||||
} catch (retryError) {
|
||||
console.error("Failed to restart server again:", retryError)
|
||||
throw new Error(
|
||||
`The server could not be restarted.\n\nPlease restart the app.\n\nError: ${reason}`,
|
||||
)
|
||||
}
|
||||
throw new Error(
|
||||
`The server could not be restarted.\n\nThe previous configuration has been restored.\n\nError: ${reason}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the menu template with translations
|
||||
*/
|
||||
@@ -113,15 +30,6 @@ function getMenuTemplate(): MenuItemConstructorOptions[] {
|
||||
submenu: [
|
||||
{ role: "about" }, // System-translated
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: t.settings,
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => {
|
||||
const win = BrowserWindow.getFocusedWindow()
|
||||
showSettingsWindow(win || undefined)
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ role: "services" }, // System-translated
|
||||
{ type: "separator" },
|
||||
{ role: "hide" }, // System-translated
|
||||
@@ -137,19 +45,6 @@ function getMenuTemplate(): MenuItemConstructorOptions[] {
|
||||
template.push({
|
||||
label: t.file,
|
||||
submenu: [
|
||||
...(isMac
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: t.settings,
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => {
|
||||
const win = BrowserWindow.getFocusedWindow()
|
||||
showSettingsWindow(win || undefined)
|
||||
},
|
||||
},
|
||||
{ type: "separator" } as MenuItemConstructorOptions,
|
||||
]),
|
||||
isMac ? { role: "close" } : { role: "quit" }, // System-translated
|
||||
],
|
||||
})
|
||||
@@ -196,9 +91,6 @@ function getMenuTemplate(): MenuItemConstructorOptions[] {
|
||||
],
|
||||
})
|
||||
|
||||
// Configuration menu with presets
|
||||
template.push(buildConfigMenu(t))
|
||||
|
||||
// Window menu
|
||||
template.push({
|
||||
label: t.window,
|
||||
@@ -239,54 +131,3 @@ function getMenuTemplate(): MenuItemConstructorOptions[] {
|
||||
|
||||
return template
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the Configuration menu with presets
|
||||
*/
|
||||
function buildConfigMenu(
|
||||
t: ReturnType<typeof getMenuTranslations>,
|
||||
): MenuItemConstructorOptions {
|
||||
const presets = getAllPresets()
|
||||
const currentPresetId = getCurrentPresetId()
|
||||
|
||||
const presetItems: MenuItemConstructorOptions[] = presets.map((preset) => ({
|
||||
label: preset.name,
|
||||
type: "radio",
|
||||
checked: preset.id === currentPresetId,
|
||||
click: async () => {
|
||||
try {
|
||||
await switchPreset(preset.id)
|
||||
} catch (error) {
|
||||
// Show error dialog to notify user
|
||||
dialog.showErrorBox(
|
||||
"Configuration Error",
|
||||
`Failed to apply preset "${preset.name}". ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
return {
|
||||
label: t.configuration,
|
||||
submenu: [
|
||||
...(presetItems.length > 0
|
||||
? [
|
||||
{ label: t.switchPreset, enabled: false },
|
||||
{ type: "separator" } as MenuItemConstructorOptions,
|
||||
...presetItems,
|
||||
{ type: "separator" } as MenuItemConstructorOptions,
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label:
|
||||
presetItems.length > 0
|
||||
? t.managePresets
|
||||
: t.addConfigurationPreset,
|
||||
click: () => {
|
||||
const win = BrowserWindow.getFocusedWindow()
|
||||
showSettingsWindow(win || undefined)
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
+38
-551
@@ -1,570 +1,57 @@
|
||||
import { randomUUID } from "node:crypto"
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
renameSync,
|
||||
writeFileSync,
|
||||
} from "node:fs"
|
||||
import path from "node:path"
|
||||
import { app, safeStorage } from "electron"
|
||||
import { app } from "electron"
|
||||
import * as fs from "fs"
|
||||
import * as path from "path"
|
||||
|
||||
/**
|
||||
* Fields that contain sensitive data and should be encrypted
|
||||
*/
|
||||
const SENSITIVE_FIELDS = ["AI_API_KEY"] as const
|
||||
export const USER_LOCALES = ["en", "zh", "ja", "zh-Hant"] as const
|
||||
export type UserLocale = (typeof USER_LOCALES)[number]
|
||||
|
||||
/**
|
||||
* Prefix to identify encrypted values
|
||||
*/
|
||||
const ENCRYPTED_PREFIX = "encrypted:"
|
||||
// Earlier versions kept their configuration presets in this file too; the
|
||||
// name stays so the saved language survives the upgrade
|
||||
const CONFIG_FILE = "config-presets.json"
|
||||
|
||||
/**
|
||||
* Check if safeStorage encryption is available
|
||||
*/
|
||||
function isEncryptionAvailable(): boolean {
|
||||
return safeStorage.isEncryptionAvailable()
|
||||
function getConfigPath(): string {
|
||||
return path.join(app.getPath("userData"), CONFIG_FILE)
|
||||
}
|
||||
|
||||
/**
|
||||
* Track if we've already warned about plaintext storage
|
||||
* Load the config file as an object ({} if it is missing or invalid)
|
||||
*/
|
||||
let hasWarnedAboutPlaintext = false
|
||||
|
||||
/**
|
||||
* Encrypt a sensitive value using safeStorage
|
||||
* Warns if encryption is not available (API key stored in plaintext)
|
||||
*/
|
||||
function encryptValue(value: string): string {
|
||||
// Already encrypted (a value that could not be decrypted): keep it as is
|
||||
// instead of wrapping it in a second layer of encryption
|
||||
if (!value || value.startsWith(ENCRYPTED_PREFIX)) {
|
||||
return value
|
||||
}
|
||||
|
||||
if (!isEncryptionAvailable()) {
|
||||
if (!hasWarnedAboutPlaintext) {
|
||||
console.warn(
|
||||
"⚠️ SECURITY WARNING: safeStorage not available. " +
|
||||
"API keys will be stored in PLAINTEXT. " +
|
||||
"On Linux, install gnome-keyring or similar for secure storage.",
|
||||
)
|
||||
hasWarnedAboutPlaintext = true
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function loadConfig(): Record<string, unknown> {
|
||||
try {
|
||||
const encrypted = safeStorage.encryptString(value)
|
||||
return ENCRYPTED_PREFIX + encrypted.toString("base64")
|
||||
} catch (error) {
|
||||
console.error("Encryption failed:", error)
|
||||
// Fail secure: don't store if encryption fails
|
||||
throw new Error(
|
||||
"Failed to encrypt API key. Cannot securely store credentials.",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a sensitive value using safeStorage
|
||||
* Returns the original value if it's not encrypted or decryption fails
|
||||
* (so saving writes the stored ciphertext back unchanged)
|
||||
*/
|
||||
function decryptValue(value: string): string {
|
||||
if (!value || !value.startsWith(ENCRYPTED_PREFIX)) {
|
||||
return value
|
||||
}
|
||||
if (!isEncryptionAvailable()) {
|
||||
console.warn(
|
||||
"Cannot decrypt value: safeStorage encryption is not available",
|
||||
)
|
||||
return value
|
||||
}
|
||||
try {
|
||||
const base64Data = value.slice(ENCRYPTED_PREFIX.length)
|
||||
const buffer = Buffer.from(base64Data, "base64")
|
||||
return safeStorage.decryptString(buffer)
|
||||
} catch (error) {
|
||||
console.error("Failed to decrypt value:", error)
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt sensitive fields in a config object
|
||||
*/
|
||||
function encryptConfig(
|
||||
config: Record<string, string | undefined>,
|
||||
): Record<string, string | undefined> {
|
||||
const encrypted = { ...config }
|
||||
for (const field of SENSITIVE_FIELDS) {
|
||||
if (encrypted[field]) {
|
||||
encrypted[field] = encryptValue(encrypted[field] as string)
|
||||
}
|
||||
}
|
||||
return encrypted
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt sensitive fields in a config object
|
||||
*/
|
||||
function decryptConfig(
|
||||
config: Record<string, string | undefined>,
|
||||
): Record<string, string | undefined> {
|
||||
const decrypted = { ...config }
|
||||
for (const field of SENSITIVE_FIELDS) {
|
||||
if (decrypted[field]) {
|
||||
decrypted[field] = decryptValue(decrypted[field] as string)
|
||||
}
|
||||
}
|
||||
return decrypted
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration preset interface
|
||||
*/
|
||||
export interface ConfigPreset {
|
||||
id: string
|
||||
name: string
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
config: {
|
||||
AI_PROVIDER?: string
|
||||
AI_MODEL?: string
|
||||
AI_API_KEY?: string
|
||||
AI_BASE_URL?: string
|
||||
TEMPERATURE?: string
|
||||
[key: string]: string | undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration file structure
|
||||
*/
|
||||
interface ConfigPresetsFile {
|
||||
version: 1
|
||||
currentPresetId: string | null
|
||||
presets: ConfigPreset[]
|
||||
userLocale?: "en" | "zh" | "ja" | "zh-Hant"
|
||||
}
|
||||
|
||||
const CONFIG_FILE_NAME = "config-presets.json"
|
||||
|
||||
/**
|
||||
* Get the path to the config file
|
||||
*/
|
||||
function getConfigFilePath(): string {
|
||||
const userDataPath = app.getPath("userData")
|
||||
return path.join(userDataPath, CONFIG_FILE_NAME)
|
||||
}
|
||||
|
||||
// The presets file exists but the last read failed: a save now would
|
||||
// replace the user's presets with the empty list that read returned
|
||||
let presetsUnreadable = false
|
||||
|
||||
/**
|
||||
* Load presets from the config file
|
||||
* Decrypts sensitive fields automatically
|
||||
*/
|
||||
export function loadPresets(): ConfigPresetsFile {
|
||||
const configPath = getConfigFilePath()
|
||||
|
||||
if (!existsSync(configPath)) {
|
||||
// Nothing left that a save could overwrite
|
||||
presetsUnreadable = false
|
||||
return {
|
||||
version: 1,
|
||||
currentPresetId: null,
|
||||
presets: [],
|
||||
userLocale: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
let content: string
|
||||
try {
|
||||
content = readFileSync(configPath, "utf-8")
|
||||
presetsUnreadable = false
|
||||
} catch (error) {
|
||||
// Often only for now (on Windows an antivirus scanner can hold the
|
||||
// file): keep the file, and refuse saves based on this empty list
|
||||
console.error("Failed to read config presets:", error)
|
||||
presetsUnreadable = true
|
||||
return {
|
||||
version: 1,
|
||||
currentPresetId: null,
|
||||
presets: [],
|
||||
userLocale: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const data = JSON.parse(content) as ConfigPresetsFile
|
||||
|
||||
// Decrypt sensitive fields in each preset
|
||||
data.presets = data.presets.map((preset) => ({
|
||||
...preset,
|
||||
config: decryptConfig(preset.config) as ConfigPreset["config"],
|
||||
}))
|
||||
|
||||
const configPath = getConfigPath()
|
||||
if (fs.existsSync(configPath)) {
|
||||
const data = JSON.parse(fs.readFileSync(configPath, "utf-8"))
|
||||
if (data && typeof data === "object" && !Array.isArray(data)) {
|
||||
return data
|
||||
}
|
||||
console.error("Ignoring invalid config file:", data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load config presets:", error)
|
||||
// Move the unreadable file aside so the next save can't overwrite
|
||||
// the user's presets with an empty list
|
||||
const backupPath = `${configPath}.corrupt-${Date.now()}`
|
||||
try {
|
||||
renameSync(configPath, backupPath)
|
||||
console.error(`Unreadable config presets moved to ${backupPath}`)
|
||||
} catch (renameError) {
|
||||
// Still there: refuse saves that would overwrite it
|
||||
console.error("Failed to back up config presets:", renameError)
|
||||
presetsUnreadable = true
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
currentPresetId: null,
|
||||
presets: [],
|
||||
userLocale: undefined,
|
||||
}
|
||||
console.error("Failed to load config file:", error)
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save presets to the config file
|
||||
* Encrypts sensitive fields automatically
|
||||
* Get the menu locale the user chose, if any
|
||||
*/
|
||||
export function savePresets(data: ConfigPresetsFile): void {
|
||||
if (presetsUnreadable) {
|
||||
throw new Error(
|
||||
"The presets file could not be read, so it was not overwritten. Please try again.",
|
||||
)
|
||||
}
|
||||
const configPath = getConfigFilePath()
|
||||
const userDataPath = app.getPath("userData")
|
||||
export function getUserLocale(): UserLocale | undefined {
|
||||
const { userLocale } = loadConfig()
|
||||
return (USER_LOCALES as readonly unknown[]).includes(userLocale)
|
||||
? (userLocale as UserLocale)
|
||||
: undefined
|
||||
}
|
||||
|
||||
// Ensure the directory exists
|
||||
if (!existsSync(userDataPath)) {
|
||||
mkdirSync(userDataPath, { recursive: true })
|
||||
}
|
||||
|
||||
// Encrypt sensitive fields before saving
|
||||
const dataToSave: ConfigPresetsFile = {
|
||||
...data,
|
||||
presets: data.presets.map((preset) => ({
|
||||
...preset,
|
||||
config: encryptConfig(preset.config) as ConfigPreset["config"],
|
||||
})),
|
||||
}
|
||||
|
||||
try {
|
||||
/**
|
||||
* Save the menu locale the user chose
|
||||
*/
|
||||
export function setUserLocale(locale: UserLocale): void {
|
||||
const config = { ...loadConfig(), userLocale: locale }
|
||||
const configPath = getConfigPath()
|
||||
fs.mkdirSync(path.dirname(configPath), { recursive: true })
|
||||
// Write a temp file and rename it, so a crash mid-write can't leave
|
||||
// a truncated config file
|
||||
// a truncated file
|
||||
const tempPath = `${configPath}.tmp`
|
||||
writeFileSync(tempPath, JSON.stringify(dataToSave, null, 2), "utf-8")
|
||||
renameSync(tempPath, configPath)
|
||||
} catch (error) {
|
||||
console.error("Failed to save config presets:", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all presets
|
||||
*/
|
||||
export function getAllPresets(): ConfigPreset[] {
|
||||
const data = loadPresets()
|
||||
return data.presets
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current preset ID
|
||||
*/
|
||||
export function getCurrentPresetId(): string | null {
|
||||
const data = loadPresets()
|
||||
return data.currentPresetId
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current preset
|
||||
*/
|
||||
export function getCurrentPreset(): ConfigPreset | null {
|
||||
const data = loadPresets()
|
||||
if (!data.currentPresetId) {
|
||||
return null
|
||||
}
|
||||
return data.presets.find((p) => p.id === data.currentPresetId) || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new preset
|
||||
*/
|
||||
export function createPreset(
|
||||
preset: Omit<ConfigPreset, "id" | "createdAt" | "updatedAt">,
|
||||
): ConfigPreset {
|
||||
const data = loadPresets()
|
||||
const now = Date.now()
|
||||
|
||||
const newPreset: ConfigPreset = {
|
||||
id: randomUUID(),
|
||||
name: preset.name,
|
||||
config: preset.config,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
|
||||
data.presets.push(newPreset)
|
||||
savePresets(data)
|
||||
|
||||
return newPreset
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing preset
|
||||
*/
|
||||
export function updatePreset(
|
||||
id: string,
|
||||
updates: Partial<Omit<ConfigPreset, "id" | "createdAt">>,
|
||||
): ConfigPreset | null {
|
||||
const data = loadPresets()
|
||||
const index = data.presets.findIndex((p) => p.id === id)
|
||||
|
||||
if (index === -1) {
|
||||
return null
|
||||
}
|
||||
|
||||
const updatedPreset: ConfigPreset = {
|
||||
...data.presets[index],
|
||||
...updates,
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
|
||||
data.presets[index] = updatedPreset
|
||||
savePresets(data)
|
||||
|
||||
return updatedPreset
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a preset
|
||||
*/
|
||||
export function deletePreset(id: string): boolean {
|
||||
const data = loadPresets()
|
||||
const index = data.presets.findIndex((p) => p.id === id)
|
||||
|
||||
if (index === -1) {
|
||||
return false
|
||||
}
|
||||
|
||||
data.presets.splice(index, 1)
|
||||
|
||||
// Clear current preset (and its env vars) if it was deleted
|
||||
if (data.currentPresetId === id) {
|
||||
data.currentPresetId = null
|
||||
setPresetEnv(null)
|
||||
}
|
||||
|
||||
savePresets(data)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current preset
|
||||
*/
|
||||
export function setCurrentPreset(id: string | null): boolean {
|
||||
const data = loadPresets()
|
||||
|
||||
let preset: ConfigPreset | null = null
|
||||
if (id !== null) {
|
||||
preset = data.presets.find((p) => p.id === id) || null
|
||||
if (!preset) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
setPresetEnv(preset)
|
||||
data.currentPresetId = id
|
||||
savePresets(data)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Map generic AI_API_KEY and AI_BASE_URL to provider-specific environment variables
|
||||
*/
|
||||
const PROVIDER_ENV_MAP: Record<string, { apiKey: string; baseUrl: string }> = {
|
||||
openai: { apiKey: "OPENAI_API_KEY", baseUrl: "OPENAI_BASE_URL" },
|
||||
anthropic: { apiKey: "ANTHROPIC_API_KEY", baseUrl: "ANTHROPIC_BASE_URL" },
|
||||
google: {
|
||||
apiKey: "GOOGLE_GENERATIVE_AI_API_KEY",
|
||||
baseUrl: "GOOGLE_BASE_URL",
|
||||
},
|
||||
azure: { apiKey: "AZURE_API_KEY", baseUrl: "AZURE_BASE_URL" },
|
||||
openrouter: {
|
||||
apiKey: "OPENROUTER_API_KEY",
|
||||
baseUrl: "OPENROUTER_BASE_URL",
|
||||
},
|
||||
deepseek: { apiKey: "DEEPSEEK_API_KEY", baseUrl: "DEEPSEEK_BASE_URL" },
|
||||
siliconflow: {
|
||||
apiKey: "SILICONFLOW_API_KEY",
|
||||
baseUrl: "SILICONFLOW_BASE_URL",
|
||||
},
|
||||
modelscope: {
|
||||
apiKey: "MODELSCOPE_API_KEY",
|
||||
baseUrl: "MODELSCOPE_BASE_URL",
|
||||
},
|
||||
gateway: { apiKey: "AI_GATEWAY_API_KEY", baseUrl: "AI_GATEWAY_BASE_URL" },
|
||||
// bedrock doesn't use API keys in the same way
|
||||
bedrock: { apiKey: "", baseUrl: "" },
|
||||
ollama: { apiKey: "OLLAMA_API_KEY", baseUrl: "OLLAMA_BASE_URL" },
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a preset's config to environment variables
|
||||
* Maps generic AI_API_KEY/AI_BASE_URL to provider-specific keys
|
||||
*/
|
||||
function presetToEnv(preset: ConfigPreset): Record<string, string> {
|
||||
const env: Record<string, string> = {}
|
||||
const provider = preset.config.AI_PROVIDER?.toLowerCase()
|
||||
|
||||
for (const [key, value] of Object.entries(preset.config)) {
|
||||
if (value !== undefined && value !== "") {
|
||||
// A key that could not be decrypted is useless to the server
|
||||
if (value.startsWith(ENCRYPTED_PREFIX)) {
|
||||
console.warn(
|
||||
`Preset "${preset.name}": ${key} could not be decrypted. Please enter it again in Settings.`,
|
||||
)
|
||||
}
|
||||
// Map generic AI_API_KEY to provider-specific key
|
||||
else if (
|
||||
key === "AI_API_KEY" &&
|
||||
provider &&
|
||||
PROVIDER_ENV_MAP[provider]
|
||||
) {
|
||||
const providerApiKey = PROVIDER_ENV_MAP[provider].apiKey
|
||||
if (providerApiKey) {
|
||||
env[providerApiKey] = value
|
||||
}
|
||||
}
|
||||
// Map generic AI_BASE_URL to provider-specific key
|
||||
else if (
|
||||
key === "AI_BASE_URL" &&
|
||||
provider &&
|
||||
PROVIDER_ENV_MAP[provider]
|
||||
) {
|
||||
const providerBaseUrl = PROVIDER_ENV_MAP[provider].baseUrl
|
||||
if (providerBaseUrl) {
|
||||
env[providerBaseUrl] = value
|
||||
}
|
||||
}
|
||||
// Apply other env vars directly
|
||||
else {
|
||||
env[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
/**
|
||||
* Values that env vars had before a preset first set them
|
||||
* (from the system or .env files), and the keys the active preset set
|
||||
*/
|
||||
const originalEnv: Record<string, string | undefined> = {}
|
||||
let presetEnvKeys: string[] = []
|
||||
|
||||
/**
|
||||
* Replace the env vars of the previous preset with those of the given preset
|
||||
* (null leaves no preset applied). Restoring first means switching presets
|
||||
* never leaves the previous preset's base URL, model or key behind.
|
||||
*/
|
||||
function setPresetEnv(preset: ConfigPreset | null): Record<string, string> {
|
||||
for (const key of presetEnvKeys) {
|
||||
if (originalEnv[key] === undefined) {
|
||||
delete process.env[key]
|
||||
} else {
|
||||
process.env[key] = originalEnv[key]
|
||||
}
|
||||
}
|
||||
|
||||
const env = preset ? presetToEnv(preset) : {}
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
if (!(key in originalEnv)) {
|
||||
originalEnv[key] = process.env[key]
|
||||
}
|
||||
process.env[key] = value
|
||||
}
|
||||
presetEnvKeys = Object.keys(env)
|
||||
|
||||
writeDevPresetEnv(env)
|
||||
return env
|
||||
}
|
||||
|
||||
const DEV_ENV_FILE_NAME = "dev-preset-env.json"
|
||||
|
||||
/**
|
||||
* Development only: write the active preset's env vars (decrypted and mapped)
|
||||
* for scripts/electron-dev.mjs, which restarts the Next.js dev server when
|
||||
* this file changes. The dev server can't decrypt the config file itself.
|
||||
*/
|
||||
function writeDevPresetEnv(env: Record<string, string>): void {
|
||||
if (app.isPackaged) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const filePath = path.join(app.getPath("userData"), DEV_ENV_FILE_NAME)
|
||||
writeFileSync(filePath, JSON.stringify(env, null, 2), {
|
||||
encoding: "utf-8",
|
||||
mode: 0o600,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to write dev preset env:", error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply preset environment variables to the current process
|
||||
* Returns the environment variables that were applied
|
||||
*/
|
||||
export function applyPresetToEnv(id: string): Record<string, string> | null {
|
||||
const data = loadPresets()
|
||||
const preset = data.presets.find((p) => p.id === id)
|
||||
|
||||
if (!preset) {
|
||||
return null
|
||||
}
|
||||
|
||||
const appliedEnv = setPresetEnv(preset)
|
||||
|
||||
// Set as current preset
|
||||
data.currentPresetId = id
|
||||
savePresets(data)
|
||||
|
||||
return appliedEnv
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the saved current preset's environment variables (used at startup)
|
||||
*/
|
||||
export function applyCurrentPresetToEnv(): void {
|
||||
setPresetEnv(getCurrentPreset())
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user's preferred locale from config
|
||||
* Returns undefined if not set
|
||||
*/
|
||||
export function getUserLocale(): "en" | "zh" | "ja" | "zh-Hant" | undefined {
|
||||
const data = loadPresets()
|
||||
return data.userLocale
|
||||
}
|
||||
|
||||
/**
|
||||
* Set user's preferred locale in config
|
||||
*/
|
||||
export function setUserLocale(
|
||||
locale: "en" | "zh" | "ja" | "zh-Hant" | null,
|
||||
): void {
|
||||
const data = loadPresets()
|
||||
data.userLocale = locale === null ? undefined : locale
|
||||
savePresets(data)
|
||||
fs.writeFileSync(tempPath, JSON.stringify(config, null, 2), "utf-8")
|
||||
fs.renameSync(tempPath, configPath)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import { parse } from "dotenv"
|
||||
import { app } from "electron"
|
||||
|
||||
/**
|
||||
@@ -28,69 +29,13 @@ export function loadEnvFile(): void {
|
||||
console.log("No .env file found, using system environment variables")
|
||||
}
|
||||
|
||||
/**
|
||||
* Index of the quote that closes a value starting with a quote, or -1. A
|
||||
* backslash before the quote character escapes it, as in dotenv; the
|
||||
* backslash stays in the value. As in dotenv, an escaped quote with only a
|
||||
* comment or nothing after it still closes the value when no other quote
|
||||
* does ("C:\dir\" keeps its trailing backslash).
|
||||
*/
|
||||
function findClosingQuote(value: string): number {
|
||||
const quote = value[0]
|
||||
let lastEscaped = -1
|
||||
for (let i = 1; i < value.length; i++) {
|
||||
if (value[i] === "\\" && value[i + 1] === quote) {
|
||||
i++
|
||||
if (/^\s*(#.*)?$/.test(value.slice(i + 1))) lastEscaped = i
|
||||
} else if (value[i] === quote) return i
|
||||
}
|
||||
return lastEscaped
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse and load environment variables from a file
|
||||
*/
|
||||
function loadEnvFromFile(filePath: string): void {
|
||||
try {
|
||||
const content = fs.readFileSync(filePath, "utf-8")
|
||||
const lines = content.split("\n")
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
|
||||
// Skip comments and empty lines
|
||||
if (!trimmed || trimmed.startsWith("#")) continue
|
||||
|
||||
const equalIndex = trimmed.indexOf("=")
|
||||
if (equalIndex === -1) continue
|
||||
|
||||
const key = trimmed.slice(0, equalIndex).trim()
|
||||
let value = trimmed.slice(equalIndex + 1).trim()
|
||||
|
||||
const quote = value[0]
|
||||
const closingQuote =
|
||||
quote === '"' || quote === "'" ? findClosingQuote(value) : -1
|
||||
if (
|
||||
closingQuote > 0 &&
|
||||
/^\s*(#.*)?$/.test(value.slice(closingQuote + 1))
|
||||
) {
|
||||
// Quoted value, then nothing or a comment: keep what is
|
||||
// inside the quotes, as dotenv reads it
|
||||
value = value.slice(1, closingQuote)
|
||||
} else {
|
||||
// Unquoted value: drop an inline comment ("value # comment").
|
||||
// A value quoted from start to end with quotes inside (JSON
|
||||
// with an apostrophe) loses only the outer two, as in dotenv.
|
||||
value = value.replace(/\s+#.*$/, "")
|
||||
if (
|
||||
closingQuote > 0 &&
|
||||
value.length > 1 &&
|
||||
value.endsWith(quote)
|
||||
) {
|
||||
value = value.slice(1, -1)
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = parse(fs.readFileSync(filePath, "utf-8"))
|
||||
for (const [key, value] of Object.entries(parsed)) {
|
||||
// Don't override existing environment variables
|
||||
if (!(key in process.env)) {
|
||||
process.env[key] = value
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { app, BrowserWindow, dialog, shell } from "electron"
|
||||
import { buildAppMenu } from "./app-menu"
|
||||
import { applyCurrentPresetToEnv } from "./config-manager"
|
||||
import { loadEnvFile } from "./env-loader"
|
||||
import { registerIpcHandlers } from "./ipc-handlers"
|
||||
import { startNextServer, stopNextServer } from "./next-server"
|
||||
import { applyProxyToEnv } from "./proxy-manager"
|
||||
import { registerSettingsWindowHandlers } from "./settings-window"
|
||||
import {
|
||||
createWindow,
|
||||
getAppUrl,
|
||||
@@ -36,14 +34,8 @@ if (!gotTheLock) {
|
||||
const isDev = !app.isPackaged
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
// Apply saved preset environment variables (overrides .env).
|
||||
// Must run after ready: on Windows and Linux safeStorage can't
|
||||
// decrypt the API key before that.
|
||||
applyCurrentPresetToEnv()
|
||||
|
||||
// Register IPC handlers
|
||||
registerIpcHandlers()
|
||||
registerSettingsWindowHandlers()
|
||||
|
||||
// Build application menu
|
||||
buildAppMenu()
|
||||
|
||||
+11
-171
@@ -1,17 +1,6 @@
|
||||
import { app, BrowserWindow, type IpcMainInvokeEvent, ipcMain } from "electron"
|
||||
import { rebuildAppMenu, switchPreset } from "./app-menu"
|
||||
import {
|
||||
type ConfigPreset,
|
||||
createPreset,
|
||||
deletePreset,
|
||||
getAllPresets,
|
||||
getCurrentPreset,
|
||||
getCurrentPresetId,
|
||||
getUserLocale,
|
||||
setCurrentPreset,
|
||||
setUserLocale,
|
||||
updatePreset,
|
||||
} from "./config-manager"
|
||||
import { app, type IpcMainInvokeEvent, ipcMain } from "electron"
|
||||
import { buildAppMenu } from "./app-menu"
|
||||
import { setUserLocale, USER_LOCALES, type UserLocale } from "./config-manager"
|
||||
import { restartNextServer } from "./next-server"
|
||||
import { noteNoChats, rememberChatPort } from "./port-manager"
|
||||
import {
|
||||
@@ -23,37 +12,9 @@ import {
|
||||
import { isAppUrl } from "./window-manager"
|
||||
|
||||
/**
|
||||
* Allowed configuration keys for presets
|
||||
* This whitelist prevents arbitrary environment variable injection
|
||||
*/
|
||||
const ALLOWED_CONFIG_KEYS = new Set([
|
||||
"AI_PROVIDER",
|
||||
"AI_MODEL",
|
||||
"AI_API_KEY",
|
||||
"AI_BASE_URL",
|
||||
"TEMPERATURE",
|
||||
])
|
||||
|
||||
/**
|
||||
* Sanitize preset config to only include allowed keys
|
||||
*/
|
||||
function sanitizePresetConfig(
|
||||
config: Record<string, string | undefined>,
|
||||
): Record<string, string | undefined> {
|
||||
const sanitized: Record<string, string | undefined> = {}
|
||||
for (const key of ALLOWED_CONFIG_KEYS) {
|
||||
if (key in config && typeof config[key] === "string") {
|
||||
sanitized[key] = config[key]
|
||||
}
|
||||
}
|
||||
return sanitized
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an IPC handler that only answers the app's own pages
|
||||
* (the main window on the app server, or the local settings page).
|
||||
* A main window that somehow ends up on an external site still gets the
|
||||
* preload API, so its calls must be rejected here.
|
||||
* Register an IPC handler that only answers the app's own pages (on the app
|
||||
* server). A main window that somehow ends up on an external site still
|
||||
* gets the preload API, so its calls must be rejected here.
|
||||
*/
|
||||
function handle<Args extends unknown[]>(
|
||||
channel: string,
|
||||
@@ -61,7 +22,7 @@ function handle<Args extends unknown[]>(
|
||||
): void {
|
||||
ipcMain.handle(channel, (event, ...args) => {
|
||||
const url = event.senderFrame?.url
|
||||
if (!isAppUrl(url) && !url?.startsWith("file://")) {
|
||||
if (!isAppUrl(url)) {
|
||||
throw new Error(`Blocked "${channel}" from untrusted page: ${url}`)
|
||||
}
|
||||
return listener(event, ...(args as Args))
|
||||
@@ -72,12 +33,6 @@ function handle<Args extends unknown[]>(
|
||||
* Register all IPC handlers
|
||||
*/
|
||||
export function registerIpcHandlers(): void {
|
||||
// ==================== App Info ====================
|
||||
|
||||
handle("get-version", () => {
|
||||
return app.getVersion()
|
||||
})
|
||||
|
||||
// ==================== Where the chats are ====================
|
||||
|
||||
// The page saved a chat, or loaded without any: decides which port
|
||||
@@ -87,116 +42,6 @@ export function registerIpcHandlers(): void {
|
||||
if (count === 0) noteNoChats()
|
||||
})
|
||||
|
||||
// ==================== Window Controls ====================
|
||||
|
||||
ipcMain.on("window-minimize", (event) => {
|
||||
const win = BrowserWindow.fromWebContents(event.sender)
|
||||
win?.minimize()
|
||||
})
|
||||
|
||||
ipcMain.on("window-maximize", (event) => {
|
||||
const win = BrowserWindow.fromWebContents(event.sender)
|
||||
if (win?.isMaximized()) {
|
||||
win.unmaximize()
|
||||
} else {
|
||||
win?.maximize()
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.on("window-close", (event) => {
|
||||
const win = BrowserWindow.fromWebContents(event.sender)
|
||||
win?.close()
|
||||
})
|
||||
|
||||
// ==================== Config Presets ====================
|
||||
|
||||
handle("config-presets:get-all", () => {
|
||||
return getAllPresets()
|
||||
})
|
||||
|
||||
handle("config-presets:get-current", () => {
|
||||
return getCurrentPreset()
|
||||
})
|
||||
|
||||
handle("config-presets:get-current-id", () => {
|
||||
return getCurrentPresetId()
|
||||
})
|
||||
|
||||
handle(
|
||||
"config-presets:save",
|
||||
async (
|
||||
_event,
|
||||
preset: Omit<ConfigPreset, "id" | "createdAt" | "updatedAt"> & {
|
||||
id?: string
|
||||
},
|
||||
) => {
|
||||
// Validate preset name
|
||||
if (typeof preset?.name !== "string" || !preset.name.trim()) {
|
||||
throw new Error("Invalid preset name")
|
||||
}
|
||||
|
||||
// Sanitize config to only allow whitelisted keys
|
||||
const sanitizedConfig = sanitizePresetConfig(preset.config ?? {})
|
||||
|
||||
if (preset.id) {
|
||||
// Update existing preset
|
||||
const updated = updatePreset(preset.id, {
|
||||
name: preset.name.trim(),
|
||||
config: sanitizedConfig,
|
||||
})
|
||||
// Re-apply the active preset so the edit takes effect
|
||||
if (updated && updated.id === getCurrentPresetId()) {
|
||||
await switchPreset(updated.id)
|
||||
} else {
|
||||
rebuildAppMenu()
|
||||
}
|
||||
return updated
|
||||
}
|
||||
// Create new preset
|
||||
const created = createPreset({
|
||||
name: preset.name.trim(),
|
||||
config: sanitizedConfig,
|
||||
})
|
||||
rebuildAppMenu()
|
||||
return created
|
||||
},
|
||||
)
|
||||
|
||||
handle("config-presets:delete", async (_event, id: string) => {
|
||||
const wasCurrent = id === getCurrentPresetId()
|
||||
// Deleting the active preset also clears its env vars
|
||||
const deleted = deletePreset(id)
|
||||
rebuildAppMenu()
|
||||
|
||||
// Restart so the server stops using the deleted preset
|
||||
if (deleted && wasCurrent && app.isPackaged) {
|
||||
await restartNextServer()
|
||||
}
|
||||
return deleted
|
||||
})
|
||||
|
||||
handle("config-presets:apply", async (_event, id: string) => {
|
||||
try {
|
||||
const env = await switchPreset(id)
|
||||
// In development mode, electron-dev.mjs restarts Next.js
|
||||
return app.isPackaged
|
||||
? { success: true, env }
|
||||
: { success: true, env, devMode: true }
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to restart server",
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
handle("config-presets:set-current", (_event, id: string | null) => {
|
||||
return setCurrentPreset(id)
|
||||
})
|
||||
|
||||
// ==================== Proxy Settings ====================
|
||||
|
||||
handle("get-proxy", () => {
|
||||
@@ -228,7 +73,7 @@ export function registerIpcHandlers(): void {
|
||||
if (!app.isPackaged) {
|
||||
// In development, env vars are already applied
|
||||
// Next.js dev server may need manual restart
|
||||
return { success: true, devMode: true }
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
// Production: restart Next.js server to pick up new env vars
|
||||
@@ -247,20 +92,15 @@ export function registerIpcHandlers(): void {
|
||||
|
||||
// ==================== User Locale ====================
|
||||
|
||||
handle("get-user-locale", () => {
|
||||
return getUserLocale()
|
||||
})
|
||||
|
||||
handle("set-user-locale", (_event, locale: string) => {
|
||||
// Validate locale is one of the supported values
|
||||
if (!["en", "zh", "ja", "zh-Hant"].includes(locale)) {
|
||||
if (!(USER_LOCALES as readonly string[]).includes(locale)) {
|
||||
return { success: false, error: "Invalid locale" }
|
||||
}
|
||||
|
||||
try {
|
||||
setUserLocale(locale as "en" | "zh" | "ja" | "zh-Hant")
|
||||
setUserLocale(locale as UserLocale)
|
||||
// Rebuild the menu to reflect the new locale
|
||||
rebuildAppMenu()
|
||||
buildAppMenu()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return {
|
||||
|
||||
+23
-109
@@ -3,43 +3,11 @@
|
||||
* Translations for menu labels that don't use Electron's built-in roles
|
||||
*/
|
||||
|
||||
import { getUserLocale } from "./config-manager"
|
||||
import { getUserLocale, type UserLocale } from "./config-manager"
|
||||
|
||||
export type MenuLocale = "en" | "zh" | "ja" | "zh-Hant"
|
||||
|
||||
export interface MenuTranslations {
|
||||
// App menu (macOS only)
|
||||
settings: string
|
||||
|
||||
// File menu
|
||||
file: string
|
||||
|
||||
// Edit menu
|
||||
edit: string
|
||||
|
||||
// View menu
|
||||
view: string
|
||||
|
||||
// Configuration menu
|
||||
configuration: string
|
||||
switchPreset: string
|
||||
managePresets: string
|
||||
addConfigurationPreset: string
|
||||
|
||||
// Window menu
|
||||
window: string
|
||||
|
||||
// Help menu
|
||||
help: string
|
||||
documentation: string
|
||||
reportIssue: string
|
||||
}
|
||||
|
||||
const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
en: {
|
||||
// App menu
|
||||
settings: "Settings...",
|
||||
export type MenuLocale = UserLocale
|
||||
|
||||
const en = {
|
||||
// File menu
|
||||
file: "File",
|
||||
|
||||
@@ -49,12 +17,6 @@ const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
// View menu
|
||||
view: "View",
|
||||
|
||||
// Configuration menu
|
||||
configuration: "Configuration",
|
||||
switchPreset: "Switch Preset",
|
||||
managePresets: "Manage Presets...",
|
||||
addConfigurationPreset: "Add Configuration Preset...",
|
||||
|
||||
// Window menu
|
||||
window: "Window",
|
||||
|
||||
@@ -62,12 +24,14 @@ const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
help: "Help",
|
||||
documentation: "Documentation",
|
||||
reportIssue: "Report Issue",
|
||||
},
|
||||
}
|
||||
|
||||
type MenuTranslations = typeof en
|
||||
|
||||
const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
en,
|
||||
|
||||
zh: {
|
||||
// App menu
|
||||
settings: "设置...",
|
||||
|
||||
// File menu
|
||||
file: "文件",
|
||||
|
||||
@@ -77,12 +41,6 @@ const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
// View menu
|
||||
view: "查看",
|
||||
|
||||
// Configuration menu
|
||||
configuration: "配置",
|
||||
switchPreset: "切换预设",
|
||||
managePresets: "管理预设...",
|
||||
addConfigurationPreset: "添加配置预设...",
|
||||
|
||||
// Window menu
|
||||
window: "窗口",
|
||||
|
||||
@@ -93,9 +51,6 @@ const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
},
|
||||
|
||||
ja: {
|
||||
// App menu
|
||||
settings: "設定...",
|
||||
|
||||
// File menu
|
||||
file: "ファイル",
|
||||
|
||||
@@ -105,12 +60,6 @@ const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
// View menu
|
||||
view: "表示",
|
||||
|
||||
// Configuration menu
|
||||
configuration: "設定",
|
||||
switchPreset: "プリセット切り替え",
|
||||
managePresets: "プリセット管理...",
|
||||
addConfigurationPreset: "設定プリセットを追加...",
|
||||
|
||||
// Window menu
|
||||
window: "ウインドウ",
|
||||
|
||||
@@ -121,9 +70,6 @@ const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
},
|
||||
|
||||
"zh-Hant": {
|
||||
// App menu
|
||||
settings: "設定...",
|
||||
|
||||
// File menu
|
||||
file: "檔案",
|
||||
|
||||
@@ -133,12 +79,6 @@ const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
// View menu
|
||||
view: "檢視",
|
||||
|
||||
// Configuration menu
|
||||
configuration: "配置",
|
||||
switchPreset: "切換預設",
|
||||
managePresets: "管理預設...",
|
||||
addConfigurationPreset: "新增配置預設...",
|
||||
|
||||
// Window menu
|
||||
window: "視窗",
|
||||
|
||||
@@ -150,33 +90,22 @@ const translations: Record<MenuLocale, MenuTranslations> = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get menu translations for a given locale
|
||||
* Falls back to English if locale is not supported
|
||||
* Get menu translations for a locale (English for an unknown one)
|
||||
*/
|
||||
export function getMenuTranslations(locale: string): MenuTranslations {
|
||||
// Check for zh-Hant before normalizing
|
||||
if (
|
||||
locale === "zh-Hant" ||
|
||||
locale.toLowerCase().startsWith("zh-hant") ||
|
||||
locale.toLowerCase().startsWith("zh-tw") ||
|
||||
locale.toLowerCase().startsWith("zh-hk")
|
||||
) {
|
||||
return translations["zh-Hant"]
|
||||
}
|
||||
|
||||
// Normalize locale (e.g., "zh-CN" -> "zh", "ja-JP" -> "ja")
|
||||
const normalized = locale.toLowerCase().split("-")[0]
|
||||
|
||||
if (normalized === "zh") return translations.zh
|
||||
if (normalized === "ja") return translations.ja
|
||||
return translations.en
|
||||
export function getMenuTranslations(locale: MenuLocale): MenuTranslations {
|
||||
return translations[locale] ?? translations.en
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect system locale from Electron app
|
||||
* Returns one of: "en", "zh", "ja", "zh-Hant"
|
||||
* Get locale from stored preference or system default
|
||||
* Checks config file for user's language preference first
|
||||
*/
|
||||
export function detectSystemLocale(appLocale: string): MenuLocale {
|
||||
export function getPreferredLocale(appLocale: string): MenuLocale {
|
||||
const savedLocale = getUserLocale()
|
||||
if (savedLocale) {
|
||||
return savedLocale
|
||||
}
|
||||
|
||||
const lower = appLocale.toLowerCase()
|
||||
|
||||
// Distinguish Traditional Chinese locales (TW, HK, Hant) from Simplified
|
||||
@@ -188,24 +117,9 @@ export function detectSystemLocale(appLocale: string): MenuLocale {
|
||||
return "zh-Hant"
|
||||
}
|
||||
|
||||
const normalized = lower.split("-")[0]
|
||||
const language = lower.split("-")[0]
|
||||
|
||||
if (normalized === "zh") return "zh"
|
||||
if (normalized === "ja") return "ja"
|
||||
if (language === "zh") return "zh"
|
||||
if (language === "ja") return "ja"
|
||||
return "en"
|
||||
}
|
||||
|
||||
/**
|
||||
* Get locale from stored preference or system default
|
||||
* Checks config file for user's language preference first
|
||||
*/
|
||||
export function getPreferredLocale(appLocale: string): MenuLocale {
|
||||
// Try to get from saved preference first
|
||||
const savedLocale = getUserLocale()
|
||||
if (savedLocale) {
|
||||
return savedLocale
|
||||
}
|
||||
|
||||
// Fall back to system locale
|
||||
return detectSystemLocale(appLocale)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { setAppUrl } from "./window-manager"
|
||||
let serverProcess: UtilityProcess | null = null
|
||||
|
||||
// Start and restart run one at a time, so overlapping calls (e.g. two quick
|
||||
// preset switches) can't leave two servers running
|
||||
// proxy changes) can't leave two servers running
|
||||
let serverQueue: Promise<unknown> = Promise.resolve()
|
||||
|
||||
function runExclusive<T>(task: () => Promise<T>): Promise<T> {
|
||||
@@ -21,18 +21,6 @@ function runExclusive<T>(task: () => Promise<T>): Promise<T> {
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the standalone server resources
|
||||
* In packaged app: resources/standalone
|
||||
* In development: .next/standalone
|
||||
*/
|
||||
function getResourcePath(): string {
|
||||
if (app.isPackaged) {
|
||||
return path.join(process.resourcesPath, "standalone")
|
||||
}
|
||||
return path.join(app.getAppPath(), ".next", "standalone")
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the server to be ready by polling the health endpoint
|
||||
*/
|
||||
@@ -61,7 +49,8 @@ export function startNextServer(): Promise<string> {
|
||||
}
|
||||
|
||||
async function startServer(): Promise<string> {
|
||||
const resourcePath = getResourcePath()
|
||||
// The standalone server shipped in the packaged app's resources
|
||||
const resourcePath = path.join(process.resourcesPath, "standalone")
|
||||
const serverPath = path.join(resourcePath, "server.js")
|
||||
|
||||
console.log(`Starting Next.js server from: ${resourcePath}`)
|
||||
@@ -75,7 +64,7 @@ async function startServer(): Promise<string> {
|
||||
)
|
||||
}
|
||||
|
||||
// Find an available port (random in production, fixed in development)
|
||||
// Find an available port (the fixed ports 61337 / 13370, then fallbacks)
|
||||
const port = await findAvailablePort()
|
||||
console.log(`Using port: ${port}`)
|
||||
|
||||
@@ -86,7 +75,7 @@ async function startServer(): Promise<string> {
|
||||
HOSTNAME: "127.0.0.1",
|
||||
// Enable Node.js built-in proxy support for fetch (Node.js 24+)
|
||||
NODE_USE_ENV_PROXY: "1",
|
||||
// The preset keys are the user's own, not a server's
|
||||
// The local server's env keys are the user's own, not a shared server's
|
||||
NEXT_AI_DRAWIO_DESKTOP: "1",
|
||||
}
|
||||
|
||||
@@ -97,10 +86,7 @@ async function startServer(): Promise<string> {
|
||||
|
||||
// Set cache directory to a writable location (user's app data folder)
|
||||
// This is necessary because the packaged app might be on a read-only volume
|
||||
if (app.isPackaged) {
|
||||
const cacheDir = path.join(app.getPath("userData"), "cache")
|
||||
env.NEXT_CACHE_DIR = cacheDir
|
||||
}
|
||||
env.NEXT_CACHE_DIR = path.join(app.getPath("userData"), "cache")
|
||||
|
||||
// Copy existing environment variables
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
|
||||
@@ -9,8 +9,6 @@ import { app } from "electron"
|
||||
* (localStorage is origin-specific, so changing ports loses all saved data)
|
||||
*/
|
||||
const PORT_CONFIG = {
|
||||
// Development mode uses fixed port for hot reload compatibility
|
||||
development: 6002,
|
||||
// Legacy production port — tried first to preserve localStorage for existing users
|
||||
legacyProduction: 61337,
|
||||
// New production port below the ephemeral range (49152-65535)
|
||||
@@ -108,9 +106,8 @@ export function isPortAvailable(port: number): Promise<boolean> {
|
||||
|
||||
/**
|
||||
* Find an available port
|
||||
* - In development: uses fixed port (6002)
|
||||
* - In production: uses the legacy port (61337), then 13370, to preserve
|
||||
* localStorage; 13370 first when only it has saved chats
|
||||
* - Uses the legacy port (61337), then 13370, to preserve localStorage;
|
||||
* 13370 first when only it has saved chats
|
||||
* - Falls back to sequential ports if preferred port is unavailable
|
||||
* - Last resort: lets the OS assign a port (port 0)
|
||||
*
|
||||
@@ -118,10 +115,7 @@ export function isPortAvailable(port: number): Promise<boolean> {
|
||||
* @returns Promise<number> The available port
|
||||
*/
|
||||
export async function findAvailablePort(reuseExisting = true): Promise<number> {
|
||||
const isDev = !app.isPackaged
|
||||
const preferredPort = isDev
|
||||
? PORT_CONFIG.development
|
||||
: PORT_CONFIG.production
|
||||
const preferredPort = PORT_CONFIG.production
|
||||
|
||||
// Try to reuse cached port if requested and available
|
||||
if (reuseExisting && allocatedPort !== null) {
|
||||
@@ -135,14 +129,13 @@ export async function findAvailablePort(reuseExisting = true): Promise<number> {
|
||||
allocatedPort = null
|
||||
}
|
||||
|
||||
// In production, first the port where a chat was last saved. Without
|
||||
// one, the legacy port first to preserve existing users' data, unless
|
||||
// only the new port has data: their app started on 13370 while Windows
|
||||
// reserved 61337, and 61337 being free now would hide it
|
||||
const chatPort = isDev ? null : readChatPort()
|
||||
const candidates = isDev
|
||||
? [preferredPort]
|
||||
: chatPort !== null
|
||||
// First the port where a chat was last saved. Without one, the legacy
|
||||
// port first to preserve existing users' data, unless only the new port
|
||||
// has data: their app started on 13370 while Windows reserved 61337,
|
||||
// and 61337 being free now would hide it
|
||||
const chatPort = readChatPort()
|
||||
const candidates =
|
||||
chatPort !== null
|
||||
? [chatPort, ...HOME_PORTS.filter((p) => p !== chatPort)]
|
||||
: hasStoredData(PORT_CONFIG.production) &&
|
||||
!hasStoredData(PORT_CONFIG.legacyProduction)
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
import path from "node:path"
|
||||
import { app, BrowserWindow, ipcMain } from "electron"
|
||||
|
||||
let settingsWindow: BrowserWindow | null = null
|
||||
|
||||
/**
|
||||
* Create and show the settings window
|
||||
*/
|
||||
export function showSettingsWindow(parentWindow?: BrowserWindow): void {
|
||||
// If settings window already exists, focus it
|
||||
if (settingsWindow && !settingsWindow.isDestroyed()) {
|
||||
settingsWindow.focus()
|
||||
return
|
||||
}
|
||||
|
||||
// Determine path to settings preload script
|
||||
// In compiled output: dist-electron/preload/settings.js
|
||||
const preloadPath = path.join(__dirname, "..", "preload", "settings.js")
|
||||
|
||||
// Determine path to settings HTML
|
||||
// In packaged app: app.asar/dist-electron/settings/index.html
|
||||
// In development: electron/settings/index.html
|
||||
const settingsHtmlPath = app.isPackaged
|
||||
? path.join(__dirname, "..", "settings", "index.html")
|
||||
: path.join(__dirname, "..", "..", "electron", "settings", "index.html")
|
||||
|
||||
settingsWindow = new BrowserWindow({
|
||||
width: 600,
|
||||
height: 700,
|
||||
minWidth: 500,
|
||||
minHeight: 500,
|
||||
parent: parentWindow,
|
||||
modal: false,
|
||||
show: false,
|
||||
title: "Settings - Next AI Draw.io",
|
||||
webPreferences: {
|
||||
preload: preloadPath,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
},
|
||||
})
|
||||
settingsWindow.loadFile(settingsHtmlPath)
|
||||
|
||||
settingsWindow.once("ready-to-show", () => {
|
||||
settingsWindow?.show()
|
||||
})
|
||||
|
||||
settingsWindow.on("closed", () => {
|
||||
settingsWindow = null
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the settings window if it exists
|
||||
*/
|
||||
export function closeSettingsWindow(): void {
|
||||
if (settingsWindow && !settingsWindow.isDestroyed()) {
|
||||
settingsWindow.close()
|
||||
settingsWindow = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if settings window is open
|
||||
*/
|
||||
export function isSettingsWindowOpen(): boolean {
|
||||
return settingsWindow !== null && !settingsWindow.isDestroyed()
|
||||
}
|
||||
|
||||
/**
|
||||
* Register settings window IPC handlers
|
||||
*/
|
||||
export function registerSettingsWindowHandlers(): void {
|
||||
ipcMain.on("settings:close", () => {
|
||||
closeSettingsWindow()
|
||||
})
|
||||
}
|
||||
@@ -107,9 +107,9 @@ export function getAppUrl(): string | null {
|
||||
|
||||
/**
|
||||
* Point the main window at the restarted app server (it can come up on a
|
||||
* different port). On the same port the page fetches the new preset's
|
||||
* server models instead of sending the old preset's choice; it is not
|
||||
* reloaded, which would drop unsent attachments.
|
||||
* different port). On the same port the page is told so it can fetch the
|
||||
* server's models again; it is not reloaded, which would drop unsent
|
||||
* attachments.
|
||||
*/
|
||||
export function setAppUrl(url: string): void {
|
||||
if (url === appUrl) {
|
||||
|
||||
@@ -4,27 +4,15 @@ import { contextBridge, ipcRenderer } from "electron"
|
||||
* Expose safe APIs to the renderer process
|
||||
*/
|
||||
contextBridge.exposeInMainWorld("electronAPI", {
|
||||
// Platform information
|
||||
platform: process.platform,
|
||||
|
||||
// Check if running in Electron
|
||||
isElectron: true,
|
||||
|
||||
// Application version
|
||||
getVersion: () => ipcRenderer.invoke("get-version"),
|
||||
|
||||
// Window controls (optional, for custom title bar)
|
||||
minimize: () => ipcRenderer.send("window-minimize"),
|
||||
maximize: () => ipcRenderer.send("window-maximize"),
|
||||
close: () => ipcRenderer.send("window-close"),
|
||||
|
||||
// Proxy settings
|
||||
getProxy: () => ipcRenderer.invoke("get-proxy"),
|
||||
setProxy: (config: { httpProxy?: string; httpsProxy?: string }) =>
|
||||
ipcRenderer.invoke("set-proxy", config),
|
||||
|
||||
// User locale settings
|
||||
getUserLocale: () => ipcRenderer.invoke("get-user-locale"),
|
||||
setUserLocale: (locale: string) =>
|
||||
ipcRenderer.invoke("set-user-locale", locale),
|
||||
|
||||
@@ -33,7 +21,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
|
||||
chatSaved: () => ipcRenderer.invoke("chat-saved"),
|
||||
chatsLoaded: (count: number) => ipcRenderer.invoke("chats-loaded", count),
|
||||
|
||||
// The server restarted on the same port (another preset)
|
||||
// The server restarted on the same port (proxy change)
|
||||
onServerRestarted: (callback: () => void) => {
|
||||
const listener = () => callback()
|
||||
ipcRenderer.on("server-restarted", listener)
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
/**
|
||||
* Preload script for settings window
|
||||
* Exposes APIs for managing configuration presets
|
||||
*/
|
||||
import { contextBridge, ipcRenderer } from "electron"
|
||||
|
||||
// Expose settings API to the renderer process
|
||||
contextBridge.exposeInMainWorld("settingsAPI", {
|
||||
// Get all presets
|
||||
getPresets: () => ipcRenderer.invoke("config-presets:get-all"),
|
||||
|
||||
// Get current preset ID
|
||||
getCurrentPresetId: () =>
|
||||
ipcRenderer.invoke("config-presets:get-current-id"),
|
||||
|
||||
// Get current preset
|
||||
getCurrentPreset: () => ipcRenderer.invoke("config-presets:get-current"),
|
||||
|
||||
// Save (create or update) a preset
|
||||
savePreset: (preset: {
|
||||
id?: string
|
||||
name: string
|
||||
config: Record<string, string | undefined>
|
||||
}) => ipcRenderer.invoke("config-presets:save", preset),
|
||||
|
||||
// Delete a preset
|
||||
deletePreset: (id: string) =>
|
||||
ipcRenderer.invoke("config-presets:delete", id),
|
||||
|
||||
// Apply a preset (sets environment variables and restarts server)
|
||||
applyPreset: (id: string) => ipcRenderer.invoke("config-presets:apply", id),
|
||||
|
||||
// Close settings window
|
||||
close: () => ipcRenderer.send("settings:close"),
|
||||
})
|
||||
@@ -1,117 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self';">
|
||||
<title>Settings - Next AI Draw.io</title>
|
||||
<link rel="stylesheet" href="./settings.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="deprecation-notice">
|
||||
<strong>⚠️ Deprecation Notice</strong>
|
||||
<p>This settings panel will be removed in a future update.</p>
|
||||
<p>Please use the <strong>AI Model Configuration</strong> button (left of the Send button in the chat panel) to configure your AI providers. Your settings there will persist across updates.</p>
|
||||
</div>
|
||||
|
||||
<h1>Configuration Presets</h1>
|
||||
|
||||
<div class="section">
|
||||
<h2>Presets</h2>
|
||||
<div id="preset-list" class="preset-list">
|
||||
<!-- Presets will be loaded here -->
|
||||
</div>
|
||||
<button id="add-preset-btn" class="btn btn-primary">
|
||||
+ Add New Preset
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Add/Edit Preset Modal -->
|
||||
<div id="preset-modal" class="modal-overlay">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3 id="modal-title">Add Preset</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="preset-form">
|
||||
<input type="hidden" id="preset-id">
|
||||
|
||||
<div class="form-group">
|
||||
<label for="preset-name">Preset Name *</label>
|
||||
<input type="text" id="preset-name" required placeholder="e.g., Work, Personal, Testing">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="ai-provider">AI Provider</label>
|
||||
<select id="ai-provider">
|
||||
<option value="">-- Select Provider --</option>
|
||||
<option value="openai">OpenAI</option>
|
||||
<option value="anthropic">Anthropic (Claude)</option>
|
||||
<option value="google">Google AI (Gemini)</option>
|
||||
<option value="azure">Azure OpenAI</option>
|
||||
<option value="bedrock">AWS Bedrock</option>
|
||||
<option value="openrouter">OpenRouter</option>
|
||||
<option value="deepseek">DeepSeek</option>
|
||||
<option value="siliconflow">SiliconFlow</option>
|
||||
<option value="modelscope">ModelScope</option>
|
||||
<option value="ollama">Ollama (Local)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="ai-model">Model ID</label>
|
||||
<input type="text" id="ai-model" placeholder="e.g., gpt-4o, claude-sonnet-4-5">
|
||||
<div class="hint">The model identifier to use with the selected provider</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="ai-api-key">API Key</label>
|
||||
<input type="password" id="ai-api-key" placeholder="Your API key">
|
||||
<div class="hint">This will be stored locally on your device</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="ai-base-url">Base URL (Optional)</label>
|
||||
<input type="text" id="ai-base-url" placeholder="https://api.example.com/v1">
|
||||
<div class="hint">Custom API endpoint URL</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="temperature">Temperature (Optional)</label>
|
||||
<input type="text" id="temperature" placeholder="0.7">
|
||||
<div class="hint">Controls randomness (0.0 - 2.0)</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" id="cancel-btn" class="btn btn-secondary">Cancel</button>
|
||||
<button type="button" id="save-btn" class="btn btn-primary">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Delete Confirmation Modal -->
|
||||
<div id="delete-modal" class="modal-overlay">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3>Delete Preset</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Are you sure you want to delete "<span id="delete-preset-name"></span>"?</p>
|
||||
<p class="delete-warning">This action cannot be undone.</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" id="delete-cancel-btn" class="btn btn-secondary">Cancel</button>
|
||||
<button type="button" id="delete-confirm-btn" class="btn btn-danger">Delete</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toast notification -->
|
||||
<div id="toast" class="toast"></div>
|
||||
|
||||
<script src="./settings.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,344 +0,0 @@
|
||||
:root {
|
||||
--bg-primary: #ffffff;
|
||||
--bg-secondary: #f5f5f5;
|
||||
--bg-hover: #e8e8e8;
|
||||
--text-primary: #1a1a1a;
|
||||
--text-secondary: #666666;
|
||||
--border-color: #e0e0e0;
|
||||
--accent-color: #0066cc;
|
||||
--accent-hover: #0052a3;
|
||||
--danger-color: #dc3545;
|
||||
--success-color: #28a745;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg-primary: #1a1a1a;
|
||||
--bg-secondary: #2d2d2d;
|
||||
--bg-hover: #3d3d3d;
|
||||
--text-primary: #ffffff;
|
||||
--text-secondary: #a0a0a0;
|
||||
--border-color: #404040;
|
||||
--accent-color: #4da6ff;
|
||||
--accent-hover: #66b3ff;
|
||||
}
|
||||
}
|
||||
|
||||
.deprecation-notice {
|
||||
background-color: #fff3cd;
|
||||
border: 1px solid #ffc107;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.deprecation-notice strong {
|
||||
color: #856404;
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.deprecation-notice p {
|
||||
color: #856404;
|
||||
font-size: 13px;
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.deprecation-notice {
|
||||
background-color: #332701;
|
||||
border-color: #665200;
|
||||
}
|
||||
|
||||
.deprecation-notice strong,
|
||||
.deprecation-notice p {
|
||||
color: #ffc107;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
|
||||
sans-serif;
|
||||
background-color: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 560px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 24px;
|
||||
padding-bottom: 16px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 16px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.preset-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.preset-card {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.preset-card:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.preset-card.active {
|
||||
border-color: var(--accent-color);
|
||||
box-shadow: 0 0 0 1px var(--accent-color);
|
||||
}
|
||||
|
||||
.preset-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.preset-name {
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.preset-badge {
|
||||
background: var(--accent-color);
|
||||
color: white;
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.preset-info {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.preset-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 8px 16px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--accent-color);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: var(--danger-color);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 6px 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal-overlay {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
z-index: 100;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal-overlay.show {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: var(--bg-primary);
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 480px;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.modal-header h3 {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
padding: 16px 24px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-color);
|
||||
box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.2);
|
||||
}
|
||||
|
||||
.form-group .hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.loading {
|
||||
display: inline-block;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 2px solid var(--border-color);
|
||||
border-top-color: var(--accent-color);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: var(--text-primary);
|
||||
color: var(--bg-primary);
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
z-index: 200;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.toast.show {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.toast.success {
|
||||
background: var(--success-color);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.toast.error {
|
||||
background: var(--danger-color);
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Inline style replacements */
|
||||
.delete-warning {
|
||||
color: var(--text-secondary);
|
||||
margin-top: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
@@ -1,313 +0,0 @@
|
||||
// Settings page JavaScript
|
||||
// This file handles the UI interactions for the settings window
|
||||
|
||||
let presets = []
|
||||
let currentPresetId = null
|
||||
let editingPresetId = null
|
||||
let deletingPresetId = null
|
||||
|
||||
// DOM Elements
|
||||
const presetList = document.getElementById("preset-list")
|
||||
const addPresetBtn = document.getElementById("add-preset-btn")
|
||||
const presetModal = document.getElementById("preset-modal")
|
||||
const deleteModal = document.getElementById("delete-modal")
|
||||
const presetForm = document.getElementById("preset-form")
|
||||
const modalTitle = document.getElementById("modal-title")
|
||||
const toast = document.getElementById("toast")
|
||||
|
||||
// Form fields
|
||||
const presetIdField = document.getElementById("preset-id")
|
||||
const presetNameField = document.getElementById("preset-name")
|
||||
const aiProviderField = document.getElementById("ai-provider")
|
||||
const aiModelField = document.getElementById("ai-model")
|
||||
const aiApiKeyField = document.getElementById("ai-api-key")
|
||||
const aiBaseUrlField = document.getElementById("ai-base-url")
|
||||
const temperatureField = document.getElementById("temperature")
|
||||
|
||||
// Buttons
|
||||
const cancelBtn = document.getElementById("cancel-btn")
|
||||
const saveBtn = document.getElementById("save-btn")
|
||||
const deleteCancelBtn = document.getElementById("delete-cancel-btn")
|
||||
const deleteConfirmBtn = document.getElementById("delete-confirm-btn")
|
||||
|
||||
// Initialize
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
await loadPresets()
|
||||
setupEventListeners()
|
||||
})
|
||||
|
||||
// Load presets from main process
|
||||
async function loadPresets() {
|
||||
try {
|
||||
presets = await window.settingsAPI.getPresets()
|
||||
currentPresetId = await window.settingsAPI.getCurrentPresetId()
|
||||
renderPresets()
|
||||
} catch (error) {
|
||||
console.error("Failed to load presets:", error)
|
||||
showToast("Failed to load presets", "error")
|
||||
}
|
||||
}
|
||||
|
||||
// Render presets list
|
||||
function renderPresets() {
|
||||
if (presets.length === 0) {
|
||||
presetList.innerHTML = `
|
||||
<div class="empty-state">
|
||||
<p>No presets configured yet.</p>
|
||||
<p>Add a preset to quickly switch between different AI configurations.</p>
|
||||
</div>
|
||||
`
|
||||
return
|
||||
}
|
||||
|
||||
presetList.innerHTML = presets
|
||||
.map((preset) => {
|
||||
const isActive = preset.id === currentPresetId
|
||||
const providerLabel = getProviderLabel(preset.config.AI_PROVIDER)
|
||||
|
||||
return `
|
||||
<div class="preset-card ${isActive ? "active" : ""}" data-id="${preset.id}">
|
||||
<div class="preset-header">
|
||||
<span class="preset-name">${escapeHtml(preset.name)}</span>
|
||||
${isActive ? '<span class="preset-badge">Active</span>' : ""}
|
||||
</div>
|
||||
<div class="preset-info">
|
||||
${providerLabel ? `Provider: ${providerLabel}` : "No provider configured"}
|
||||
${preset.config.AI_MODEL ? ` • Model: ${escapeHtml(preset.config.AI_MODEL)}` : ""}
|
||||
</div>
|
||||
<div class="preset-actions">
|
||||
${!isActive ? `<button class="btn btn-primary btn-sm apply-btn" data-id="${preset.id}">Apply</button>` : ""}
|
||||
<button class="btn btn-secondary btn-sm edit-btn" data-id="${preset.id}">Edit</button>
|
||||
<button class="btn btn-secondary btn-sm delete-btn" data-id="${preset.id}">Delete</button>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
.join("")
|
||||
|
||||
// Add event listeners to buttons
|
||||
presetList.querySelectorAll(".apply-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
e.stopPropagation()
|
||||
applyPreset(btn.dataset.id)
|
||||
})
|
||||
})
|
||||
|
||||
presetList.querySelectorAll(".edit-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
e.stopPropagation()
|
||||
openEditModal(btn.dataset.id)
|
||||
})
|
||||
})
|
||||
|
||||
presetList.querySelectorAll(".delete-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
e.stopPropagation()
|
||||
openDeleteModal(btn.dataset.id)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Setup event listeners
|
||||
function setupEventListeners() {
|
||||
addPresetBtn.addEventListener("click", () => openAddModal())
|
||||
cancelBtn.addEventListener("click", () => closeModal())
|
||||
saveBtn.addEventListener("click", () => savePreset())
|
||||
deleteCancelBtn.addEventListener("click", () => closeDeleteModal())
|
||||
deleteConfirmBtn.addEventListener("click", () => confirmDelete())
|
||||
|
||||
// Close modal on overlay click
|
||||
presetModal.addEventListener("click", (e) => {
|
||||
if (e.target === presetModal) closeModal()
|
||||
})
|
||||
deleteModal.addEventListener("click", (e) => {
|
||||
if (e.target === deleteModal) closeDeleteModal()
|
||||
})
|
||||
|
||||
// Handle Enter key in form
|
||||
presetForm.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
savePreset()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Open add modal
|
||||
function openAddModal() {
|
||||
editingPresetId = null
|
||||
modalTitle.textContent = "Add Preset"
|
||||
presetForm.reset()
|
||||
presetIdField.value = ""
|
||||
presetModal.classList.add("show")
|
||||
presetNameField.focus()
|
||||
}
|
||||
|
||||
// Open edit modal
|
||||
function openEditModal(id) {
|
||||
const preset = presets.find((p) => p.id === id)
|
||||
if (!preset) return
|
||||
|
||||
editingPresetId = id
|
||||
modalTitle.textContent = "Edit Preset"
|
||||
|
||||
presetIdField.value = preset.id
|
||||
presetNameField.value = preset.name
|
||||
aiProviderField.value = preset.config.AI_PROVIDER || ""
|
||||
aiModelField.value = preset.config.AI_MODEL || ""
|
||||
aiApiKeyField.value = preset.config.AI_API_KEY || ""
|
||||
aiBaseUrlField.value = preset.config.AI_BASE_URL || ""
|
||||
temperatureField.value = preset.config.TEMPERATURE || ""
|
||||
|
||||
presetModal.classList.add("show")
|
||||
presetNameField.focus()
|
||||
}
|
||||
|
||||
// Close modal
|
||||
function closeModal() {
|
||||
presetModal.classList.remove("show")
|
||||
editingPresetId = null
|
||||
}
|
||||
|
||||
// Open delete modal
|
||||
function openDeleteModal(id) {
|
||||
const preset = presets.find((p) => p.id === id)
|
||||
if (!preset) return
|
||||
|
||||
deletingPresetId = id
|
||||
document.getElementById("delete-preset-name").textContent = preset.name
|
||||
deleteModal.classList.add("show")
|
||||
}
|
||||
|
||||
// Close delete modal
|
||||
function closeDeleteModal() {
|
||||
deleteModal.classList.remove("show")
|
||||
deletingPresetId = null
|
||||
}
|
||||
|
||||
// Save preset
|
||||
async function savePreset() {
|
||||
const name = presetNameField.value.trim()
|
||||
if (!name) {
|
||||
showToast("Please enter a preset name", "error")
|
||||
presetNameField.focus()
|
||||
return
|
||||
}
|
||||
|
||||
const preset = {
|
||||
id: editingPresetId || undefined,
|
||||
name: name,
|
||||
config: {
|
||||
AI_PROVIDER: aiProviderField.value || undefined,
|
||||
AI_MODEL: aiModelField.value.trim() || undefined,
|
||||
AI_API_KEY: aiApiKeyField.value.trim() || undefined,
|
||||
AI_BASE_URL: aiBaseUrlField.value.trim() || undefined,
|
||||
TEMPERATURE: temperatureField.value.trim() || undefined,
|
||||
},
|
||||
}
|
||||
|
||||
// Remove undefined values
|
||||
Object.keys(preset.config).forEach((key) => {
|
||||
if (preset.config[key] === undefined) {
|
||||
delete preset.config[key]
|
||||
}
|
||||
})
|
||||
|
||||
// closeModal() clears editingPresetId, so remember it for the toast
|
||||
const isEdit = Boolean(editingPresetId)
|
||||
|
||||
try {
|
||||
saveBtn.disabled = true
|
||||
saveBtn.innerHTML = '<span class="loading"></span>'
|
||||
|
||||
await window.settingsAPI.savePreset(preset)
|
||||
await loadPresets()
|
||||
closeModal()
|
||||
showToast(isEdit ? "Preset updated" : "Preset created", "success")
|
||||
} catch (error) {
|
||||
console.error("Failed to save preset:", error)
|
||||
showToast("Failed to save preset", "error")
|
||||
} finally {
|
||||
saveBtn.disabled = false
|
||||
saveBtn.textContent = "Save"
|
||||
}
|
||||
}
|
||||
|
||||
// Confirm delete
|
||||
async function confirmDelete() {
|
||||
if (!deletingPresetId) return
|
||||
|
||||
try {
|
||||
deleteConfirmBtn.disabled = true
|
||||
deleteConfirmBtn.innerHTML = '<span class="loading"></span>'
|
||||
|
||||
await window.settingsAPI.deletePreset(deletingPresetId)
|
||||
await loadPresets()
|
||||
closeDeleteModal()
|
||||
showToast("Preset deleted", "success")
|
||||
} catch (error) {
|
||||
console.error("Failed to delete preset:", error)
|
||||
showToast("Failed to delete preset", "error")
|
||||
} finally {
|
||||
deleteConfirmBtn.disabled = false
|
||||
deleteConfirmBtn.textContent = "Delete"
|
||||
}
|
||||
}
|
||||
|
||||
// Apply preset
|
||||
async function applyPreset(id) {
|
||||
try {
|
||||
const btn = presetList.querySelector(`.apply-btn[data-id="${id}"]`)
|
||||
if (btn) {
|
||||
btn.disabled = true
|
||||
btn.innerHTML = '<span class="loading"></span>'
|
||||
}
|
||||
|
||||
const result = await window.settingsAPI.applyPreset(id)
|
||||
if (result.success) {
|
||||
showToast("Preset applied, server restarting...", "success")
|
||||
} else {
|
||||
showToast(result.error || "Failed to apply preset", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to apply preset:", error)
|
||||
showToast("Failed to apply preset", "error")
|
||||
} finally {
|
||||
// Reload to show the active preset and reset the Apply button
|
||||
await loadPresets()
|
||||
}
|
||||
}
|
||||
|
||||
// Get provider display label
|
||||
function getProviderLabel(provider) {
|
||||
const labels = {
|
||||
openai: "OpenAI",
|
||||
anthropic: "Anthropic",
|
||||
google: "Google AI",
|
||||
azure: "Azure OpenAI",
|
||||
bedrock: "AWS Bedrock",
|
||||
openrouter: "OpenRouter",
|
||||
deepseek: "DeepSeek",
|
||||
siliconflow: "SiliconFlow",
|
||||
modelscope: "ModelScope",
|
||||
ollama: "Ollama",
|
||||
}
|
||||
return labels[provider] || provider
|
||||
}
|
||||
|
||||
// Show toast notification
|
||||
function showToast(message, type = "") {
|
||||
toast.textContent = message
|
||||
toast.className = "toast show" + (type ? ` ${type}` : "")
|
||||
|
||||
setTimeout(() => {
|
||||
toast.classList.remove("show")
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
// Escape HTML to prevent XSS
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement("div")
|
||||
div.textContent = text
|
||||
return div.innerHTML
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user