feat: MCP feature parity, the web app on the MCP core, and provider fixes (#951)

* fix(chat): close credential leaks and harden the chat route

- Vertex: a client-supplied base URL only works with the client's own Vertex key
- Accept only data: URLs for file parts in every message, so the server never downloads them
- Output budget retry accounts for the thinking budget Bedrock/Anthropic add, and reads
  Volcengine, DashScope, SGLang and vLLM rejections; falls back to 16000 once
- x-max-output-tokens can only lower the budget on server credentials
- On server credentials only server models or AI_MODEL entries can be used
- Drop tool results together with the invalid tool calls they belong to
- Count quota tokens as input + output (cached tokens were counted twice)
- Private-URL check for custom base URLs, end Langfuse traces on error/abort/early return
- Fix repairToolCall ordering and placeholder, align edit_diagram prompt with operations
- Panel Bedrock keys are read from ADMIN_AWS_*; forward the access code to EdgeOne
- isMinimalDiagram only treats root cells as an empty canvas

* fix(api): require access codes and limit sizes on helper routes

- Shared checkAccessCode for validate-diagram, validate-model, parse-url, verify-access-code
- parse-url: 5 MB streamed body limit; validate-diagram: 5 MB image limit
- validate-model refuses redirects when private URLs are blocked
- Admin settings state shared across module instances via globalThis
- Server model ids: unique slugs (non-ASCII names encoded), duplicates rejected
- Panel Bedrock credentials stored as ADMIN_AWS_* so the DynamoDB client keeps its own
- Locale redirect keeps basePath and query; EdgeOne function drops open CORS and checks the access code
- Providers payload reports whether .env sets a default model

* fix(chat): keep saved diagrams and pages when restoring, editing and retrying

- Restored sessions no longer replay the last display_diagram over the saved diagram
- Failed or stopped edit_diagram restores the canvas
- Message snapshots keep the full multi-page document
- "Improve with suggestions" uses the normal send path (headers, xml, retry counters)
- Editing a message keeps its file/URL sections; cached example edits work
- New chat's first autosave no longer resets the UI
- Validation retries counted per user turn; validate-diagram sends the access code
- Cached examples only match the example files on an empty canvas
- Template sends keep attachments and wait for extraction

* fix(diagram): fix autosave staleness and XML repair corrupting valid diagrams

- Autosave guard reads refs, so edits after a theme or dark mode switch are kept
- Duplicate-id check and rename run per page; repair loop no longer quadratic
- autoFixXml no longer breaks style values, rich text " or single-line cells
- extractCompleteMxCells keeps the cell after a self-closing cell
- Better truncation detection; object/UserObject wrapped cells are editable
- Exports for thumbnail, PNG and save are routed by tag instead of a shared resolver
- History stores the full document; storage errors are reported, no auto-deletion of chats
- IndexedDB connection reopens after errors; focus refresh throttled
- Keep ?session= on locale redirect, map zh-Hant to zh-tw for draw.io

* fix(chat-input): stop template dialogs from sending and fix attachment races

- Template dialogs no longer submit the outer chat form
- Sending is blocked while files or URLs are still extracting
- File and URL extraction no longer drop or resurrect entries
- IME composition Enter no longer sends
- Tool call cards show the error text; keyboard handling on cards fixed
- Template import available when empty, edit dialog resets, saved templates refresh
- Only png/jpeg/gif/webp images accepted, SVG sent as text; PDF objects released
- parse-url request sends the access code

* fix(model-config): keep model selection valid and fix admin panel edge cases

- Fall back to the default server model when a saved one disappears
- Sync model config across tabs
- Validation uses the base path and sends the access code
- Model ids edited as drafts (no empty, duplicate or padded ids)
- Credential changes reset validation; stale validation results are dropped
- Admin: generateId over HTTP, env-locked group switches, discard and toggle fixes,
  clearing a secret field keeps the saved key, first provider not auto-default when .env sets AI_MODEL
- Model selector items use unique values

* fix(electron): decrypt keys after ready and harden navigation and IPC

- Apply preset env after app ready, so Windows/Linux get decrypted keys
- Never re-encrypt ciphertext; restore env when switching or removing presets
- Block navigation away from the app, open external links in the browser, check IPC senders
- Keep inherited proxy settings, default NO_PROXY for localhost
- Serialize server start/restart, kill stuck processes, follow port changes
- Atomic config writes, keep corrupt files as backups, remember the server port
- Menu and settings window stay in sync; dev script gets the decrypted preset env
- Use app.isPackaged, parse inline .env comments, drop .env files from the bundle

* fix(mcp-server): fix XSS and crashes, make XML validation strict

- Validate and escape the mcp session id; only serve localhost Host/Origin
- Malformed URLs and session ids return errors instead of crashing the process
- Strict XML syntax check with saxes (linkedom never reports parse errors)
- autoFixXml no longer corrupts valid XML; attribute newlines serialized as entities
- Sessions stay alive while polled; browser pushes carry a base version (409 on conflict)
- Page tools respect the edit gate; UTF-8 bodies decoded correctly
- Export replies matched to requests and serialized; xml sync export handled
- UserObject/object cells addressable by id; history restored by stable id; logs off stdout

* fix(mcp-server): make edit_diagram all-or-nothing and fix preview sync races

- edit_diagram applies nothing when any operation fails, rejects invalid or
  multi-cell new_xml, validates only the target page, and returns the
  current page XML on every rejection (including stale edits)
- Fix get_diagram reading the old diagram right after an AI write: the
  preview pushed its sync reply with a newer version than it was taken at
- Keep a user edit that loses the race with an AI write in history and
  tell the user in the preview
- Autofix removes only exact foreign tags (a stray <mxGraph/> deleted
  <mxGraphModel>), fixes tag case, drops orphan <mxPoint>s, and rejects
  unknown element names in model XML
- Edit empty and compressed pages; PNG exports use the page on screen;
  tag download exports; reload from the server after a page export
- Expand ~ in paths, tell the model when the browser sync timed out,
  use registerPrompt, require SDK ^1.31.0

* feat(mcp-server): bring the web app's drawing knowledge to MCP

- Add a drawing guide adapted from the web system prompt (layout, edge
  routing, styles, minimal style, editing rules), returned by
  start_session, a new get_drawing_guide tool and the diagram-workflow prompt
- Add get_shape_library with the 30 icon libraries; the build copies
  docs/shape-libraries into dist and CI checks the packed files
- Accept bare mxCell lists in create_new_diagram and add_page; the server
  adds the wrapper and root cells
- Send server instructions, shorten create_new_diagram's description to
  fit Claude Code's 2,048 character limit, and annotate every tool
- Fix dead links and the totals in docs/shape-libraries/README.md

* feat(mcp-server): add screenshot_diagram so the model can check its render

- New read-only screenshot_diagram tool returns the rendered page as a PNG
  plus the web app's visual checklist (overlaps, edges crossing shapes,
  readability, layout, rendering errors), replacing the web app's
  separate vision model with the host model's own vision
- PNG exports use draw.io's width and pageId options: screenshots stay
  under ~140,000 base64 characters and page exports no longer swap the
  page on screen
- Fail fast with a clear message when the preview tab stopped polling
  (browsers throttle background tabs)
- Mention the screenshot step in the drawing guide and instructions

* feat(mcp-server): auto-save each session's diagram to a .drawio file

- Save the latest diagram of every session 1 second after each change
  (AI write, browser edit, history restore) to ~/.next-ai-drawio/<id>.drawio,
  keep the newest 50, flush on shutdown; DRAWIO_DATA_DIR changes the folder
  and "off" disables it, like the web app's IndexedDB sessions
- start_session names the file, so a resumed conversation can reopen the
  diagram with load_diagram after the MCP process restarted
- Fix PNG/SVG exports randomly timing out: a previous export's 10 second
  timer cleared the export in progress, and a late reply could be taken
  for the current one; exports are now numbered

* refactor(mcp-server): move the preview page into src/preview

The 580-line page template in http-server.ts becomes index.html,
preview.css and preview.js, copied to dist/preview by the build and
filled at request time. The rendered page is unchanged apart from the
session id and draw.io origin now coming from a small config script.
Biome skips the folder because of the {{placeholders}}, as it never
linted the old template string either.

* feat(mcp-server): add theme menu, dark mode and editable SVG to the preview

- Pass themes=1 and dark=auto to the draw.io iframe, so the Extras menu
  offers the Theme submenu and draw.io follows the system dark mode; the
  header and dialogs follow it too through prefers-color-scheme
- Download dialog: new Editable SVG (.drawio.svg) format through draw.io's
  xmlsvg export, default name diagram-YYYY-MM-DD, Enter saves and Escape
  closes it and the history dialog
- export_diagram accepts format "drawio.svg" and detects the .drawio.svg
  extension
- Use system fonts instead of Google Fonts, so the page works offline with
  a self-hosted draw.io (DRAWIO_BASE_URL)

* docs(mcp-server): describe the new MCP features in all READMEs

- MCP server README: 13 tools, drawing rules and shape libraries,
  screenshots, all-or-nothing edits, auto-save and how to continue a
  diagram later, DRAWIO_DATA_DIR and DEBUG, offline use with a local
  draw.io, and what to do when a background tab makes exports time out
- Fix two errors: History is a button at the top right of the preview
  page, and exports are not limited to .drawio
- Claude Code plugin README: same tool list, formats and settings
- Root READMEs (English, Chinese, Japanese): short list of what the MCP
  server can do

* fix(mcp-server): fix duplicate page exports and auto-save deleting user files

- Preview page: keep an MCP export open until the server has its result.
  A poll answered before that still saw the request and started the same
  export again, so a parallel page export could write the previous
  page's image into its file
- Auto-save only removes its own mcp-*.drawio files, so a DRAWIO_DATA_DIR
  that also holds the user's diagrams keeps them
- screenshot_diagram captures a page that has no id attribute by loading
  just that page, like export_diagram
- An empty <Array as="points"/> no longer hides orphan mxPoints that
  come after it
- POST /api/state refuses a push without xml, which used to wipe the
  stored diagram
- Clear exportOptions when an export ends, reuse hasCells for the empty
  diagram check, and reword two log lines

* fix: log Editable SVG saves, use local dates in file names, drop unused Electron dialogs

- /api/log-save accepted only drawio, png and svg, so saving as Editable
  SVG (xmlsvg) got a 400 and was never recorded in Langfuse
- The default download name and the template export name used the UTC
  date, which is the previous day on mornings in East Asia
- Remove the Electron openFile/saveFile IPC handlers, their preload
  bindings and types; nothing in the app calls them

* refactor(mcp-server): make the diagram modules usable from the web app

The web app will reuse the MCP server's XML engine instead of its own
copy in lib/utils.ts, so these modules now run in the browser too.

- Relative imports end in .ts, rewritten to .js by tsc
  (rewriteRelativeImportExtensions); Next.js resolves them directly
- Every module uses the global DOMParser/XMLSerializer: native in the
  browser, linkedom in Node via installDomPolyfill. pages.ts parsed with
  linkedom but serialized with the global serializer, which throws in
  the browser
- The saxes syntax check moves to xml-syntax.ts, so the browser does not
  pull in linkedom; it now also rejects undeclared prefixes such as
  xlink:, as the browser does
- Page decompression uses pako and atob instead of node:zlib and Buffer
- hasCells moves to pages.ts, away from the file system code
- The duplicate cell id check counts UserObject/object ids
- wrapCellsInModel drops comments and text before the first cell, which
  the web app accepts today
- validateAndFixXml takes { strict: false } for diagrams with user content
- Web tests run these modules with a browser DOM (jsdom)
- saxes becomes a direct dependency of the web app

* refactor(web): validate and repair diagram XML with the MCP server's engine

- Delete the web app's own copy of the XML checks and repairs from
  lib/utils.ts (1,074 lines). loadDiagram now uses the MCP server's
  validateAndFixXml without the strict checks, because the XML may hold
  the user's own diagram
- display_diagram and append_diagram prepare the model's XML with the new
  shared prepareNewDiagram, also used by the MCP create_new_diagram: wrap,
  validate strictly and auto-fix while it is still a bare model (where
  duplicate ids are renamed), then turn it into an mxfile
- The streaming preview of display_diagram no longer redraws the model's
  raw cells after the tool handler loaded the checked diagram, and drops
  a queued preview once the input is complete. That redraw lost
  auto-fixes and UserObject/object wrappers, so a linked cell lost its
  label; it also showed a second error toast
- The web repair regression tests now run against the MCP functions
- New e2e test checks the canvas content after display_diagram
- Fix the e2e upload tests, whose file input locator also matched the
  template import input

* refactor(web): edit and wrap diagrams with the MCP server's code

- edit_diagram runs the MCP server's editDiagram: every new_xml is checked
  first, one cell per operation, and after the edit only the target page
  is checked, rejecting only errors this edit introduced. An unrelated
  problem elsewhere in the document no longer blocks every edit. The
  error lists each failed operation
- The streaming edit preview uses the MCP applyDiagramOperations
- Delete applyDiagramOperations (292 lines) and wrapWithMxFile from
  lib/utils.ts, and the unused hand-copied scripts/test-diagram-operations.mjs
- One blank document (BLANK_MXFILE) for the web app and the MCP preview,
  replacing four copies
- Saving a .drawio wraps a bare model with normalizeToMxfile
- The empty-diagram check uses hasCells, which also counts cells wrapped
  in a UserObject/object
- DiagramOperation is the MCP type
- The wrapped-cell and empty-diagram tests now run against the MCP code
- New e2e test: edit_diagram changes the canvas, and a failing edit
  leaves it as it was

* refactor(web): share prompt examples and the shape library with the MCP server

- The three XML examples (swimlanes, two edges, waypoints) that the web
  system prompt, the display_diagram description and the MCP drawing
  guide each had a copy of now live in packages/mcp-server/src/xml-examples.ts
- The shape library group list and reader come from the MCP
  shape-library.ts; getShapeLibrary takes the folder, and the web route
  passes docs/shape-libraries under the working directory as before.
  Only the 30 known library names are read. Error texts differ slightly
- next.config.ts traces docs/shape-libraries/*.md for /api/chat, since
  the read now happens in another module
- Every prompt is byte-for-byte unchanged: the web system prompt for five
  model ids with and without minimal style, and the MCP drawing guide,
  compared before and after; the library list and swimlane example match
  the old tool description text exactly

* fix(providers): update the v6 SDK packages and fix Claude and Gemini settings

- Update ai to 6.0.300 and the @ai-sdk providers to their latest v6-line
  versions. @ai-sdk/anthropic 3.0.47 did not know claude-opus-4-7/4-8
  and capped their output at 32000 tokens; 3.0.127 allows 128000
- Drop the fine-grained-tool-streaming beta header for the Anthropic API:
  the provider now streams tool input per tool (eager_input_streaming)
- Claude 4.7 and later reject a non-default temperature/top_p/top_k and
  the extended thinking budget with a 400. A middleware retries once
  without them, so TEMPERATURE and *_THINKING_BUDGET_TOKENS no longer
  break those models
- Prompt caching also reaches Claude on the Anthropic API and OpenRouter;
  before, only Bedrock got a cache marker
- GOOGLE_TOP_K and GOOGLE_TOP_P never reached Gemini: they were sent as
  Google provider options, which drops them. They are call settings now.
  GOOGLE_CANDIDATE_COUNT and GOOGLE_REASONING_EFFORT, which the provider
  does not support, are removed
- Add @ai-sdk/openai-compatible as a direct dependency

* refactor: simpler streaming preview and small AI SDK cleanups

- useChat throttles streamed message updates (experimental_throttle,
  150 ms), replacing the two hand-written 150 ms timers of the
  display_diagram and edit_diagram previews (94 lines less). The preview
  now only runs while the input streams; once it is complete the tool
  handler takes over, so a queued preview can no longer redraw an edit
  the handler rejected and rolled back. Measured on a streamed 60-cell
  diagram: 41 redraws at least 97 ms apart, before 37 with gaps down to
  48 ms
- The diagram check endpoint uses streamText with Output.object instead
  of the deprecated streamObject, and returns its fixed result as a plain
  text response; new route test
- Import createGateway/gateway from ai and drop the direct
  @ai-sdk/gateway dependency
- The per-request message structure logs only print with
  DEBUG_LLM_PAYLOAD=true
- Remove an empty onFinish callback

* refactor(chat): check the last tool part with the SDK's isToolUIPart

Drop the hand-written MessagePart and ChatMessage types that only served
this check.

* refactor(providers): one model factory for chat and the settings Test button

- getAIModel resolves credentials (client key, server env vars, the
  existing SSRF rules) and createModel builds the model by SDK. The
  provider-by-provider switch shrinks from 24 cases to the few that
  differ (lib/ai-providers.ts 1531 -> 1106 lines)
- /api/validate-model calls getAIModel instead of its own 24-case switch
  (503 -> 175 lines), which had drifted from the chat: it built Azure
  with createOpenAI, Kimi and MiMo with createOpenAI instead of
  createDeepSeek, and the official OpenAI endpoint with Chat Completions.
  A passing test now means the chat works
- Plain OpenAI-compatible providers (SiliconFlow, SGLang, ModelScope,
  GLM, Qwen, Qiniu, Novita, Atlas Cloud, EdgeOne, Doubao, MiniMax in
  OpenAI mode, AIHubMix on a custom URL) use @ai-sdk/openai-compatible,
  which reads reasoning_content, so their reasoning shows, and accepts
  SGLang's stream as is (its 95-line stream rewrite is gone).
  includeUsage keeps token usage for quotas. <think> tags in their text
  become reasoning (extractReasoningMiddleware)
- SGLang without a base URL used OpenAI's endpoint; it now defaults to
  http://127.0.0.1:8000/v1 like the Test button did
- Chat requests to a client base URL refuse redirects, as the Test
  button already did (redirectGuardedFetch moves to lib/ssrf-protection)
- The Test button streams like the chat (the ModelScope special case is
  gone), times out after 15 s, does not retry, asks the model to call a
  ping tool and warns when it answers without one, and tests all models
  at once. The time each test took shows on its check mark
- Unknown provider names are rejected with Object.hasOwn, and the error
  texts list providers from PROVIDER_INFO instead of hand-kept lists

* feat(settings): link to each provider's key page and clean up base URLs

- A "Get API key" link next to the API Key field for the 19 providers
  that have a key page (from env.example and the providers' docs). 17
  answered 200 to curl; OpenAI's is behind a Cloudflare challenge and
  DeepSeek's behind a regional block, both checked in Chrome
- Base URLs drop spaces, trailing slashes and a pasted endpoint path
  (/chat/completions, /completions, /messages, /responses), which the
  SDK would otherwise append a second time and get a 404. getAIModel does
  this for the chat and the Test button; the field does it on blur and
  shows the URL requests go to

* feat(errors): classify provider errors and show a hint the user can act on

- lib/llm-errors.ts sorts an error into about a dozen kinds (key
  rejected, no access, unknown model, no credit, rate limited, context
  too long, no image input, no tool calls, output cut off, provider down,
  cannot connect, timeout): first texts that name the cause precisely,
  then the HTTP status code, then general texts. It unwraps RetryError and
  hides keys and Bearer tokens in the provider's message
- The chat route uses it for errors before the stream and, through
  toUIMessageStreamResponse's onError, for errors in the stream. Errors
  of the model's own tool call stay as they are: the same text goes back
  to the model so it can fix the call
- The chat shows the hint in the user's language, then the provider's
  message; a rejected key, missing access or unknown model adds an "Open
  model settings" button. The Test button shows the same hints
- Fixes: our message "API key is required when using a custom base URL"
  was replaced by "Authentication failed" because it contains "key"; a
  provider's "Rate limit exceeded" opened this site's quota toast; an
  error body like {"error": ...} was shown as raw JSON; the Test button
  matched "401" in the message, where providers rarely put it
- Remove the string matching fallbacks in the chat panel

* refactor(settings): drop an unused index parameter

* feat(settings): fetch the model list from any provider and flag models that cannot draw

The "Fetch models" button asks the provider for its models (OpenAI-style
/models, Anthropic, Google, Ollama, OpenRouter, Vercel Gateway, AIHubMix)
and shows them in a searchable picker. This replaces the route that only
worked for AIHubMix.

A snapshot of models.dev (MIT) says which models support tool calls.
Models without them get a "no tool calls" badge in the picker and a hint
in the model list, since drawing needs tool calls. Refresh the snapshot
with scripts/update-model-catalog.mjs.

* fix(mcp-server): reject text between tags, which draw.io cannot open

draw.io reads any text inside a page as compressed page data, so a stray
text node makes the whole page fail with an atob error. gpt-5-mini sends
new cells with a literal "\n" between the tags; the edit card said
Complete while draw.io showed the error and kept the old diagram.

Validation now reports text between tags, and auto-fix turns a literal
\n, \t or \r between tags into whitespace. Other text goes back to the
model as an error. The compressed data directly under <diagram> is fine.

* fix(chat): clearer provider errors and no empty bubble, found with real models

- An error object sent inside the stream (OpenRouter's { code, message })
  showed as "[object Object]"; its message and status code are read now.
- A problem+json "detail" is added to the message: NVIDIA only said
  "Gone" for a retired model. 410 counts as model not found.
- "Cannot connect to API" from the SDK gets the connection hint.
- Text that is only whitespace (Kimi K2.6 sends a space before a tool
  call) no longer shows an empty bubble.
- allowSystemInMessages stops the warning on every request. Our system
  messages carry cache points; a client's own system messages are already
  dropped by the empty-content filter.

* feat(providers): suggest the Claude 5 and GPT 6 models, show GPT 6 reasoning

The suggested models stopped at Claude Opus 4.8 and GPT 5.5. They now
start with Claude Opus 5.5, Sonnet 5.5 and Fable 5.1, and gpt-6.1-sol,
gpt-6-sol, gpt-6-luna and gpt-6-astra (ids checked against the provider
lists). The Bedrock list is unchanged until its ids are checked.

The reasoning summary was only turned on for model ids containing o1,
o3, o4 or gpt-5, so GPT 6 models showed no thinking. It now matches the
o-series and gpt-5 or later by version, like the OpenAI SDK.

* fix(providers): keep thinking on the newest Claude models, fix the Bedrock ids

Measured on Bedrock: Claude Opus 4.7, 4.8 and every Claude 5 model reject
a thinking budget ("thinking.type.enabled") and a temperature, and all of
them accept adaptive thinking. The retry used to drop thinking, so with
a thinking budget set these models did not think at all. It now switches
to adaptive thinking with display "summarized"; without that setting the
models think but send no thinking text to show.

The suggested Bedrock ids had no region prefix, and the newer models only
answer through an inference profile id: "anthropic.claude-sonnet-5-5"
fails with "on-demand throughput isn't supported". Each suggested id was
called once; the Claude ones now start with "global.", Llama, Pixtral and
Nova 2 Lite with "us.". Nova Premier (end of life) and the ids without a
working profile are gone. The docs example had the same problem and a
wrong date.

* fix(chat): an edit after a broken edit call no longer fails, found with Opus 5.5

- Claude Opus 5.5 sent an edit with invalid JSON, then the same edit
  again. The first call's streamed preview was never undone: its input
  has no operations, and the undo sat behind that check. The second edit
  then started from the preview, failed on a duplicate id, and the model
  had to try a third time. The undo now runs first, and an edit that
  starts in the same render uses the undone diagram.
- The SDK passes an invalid tool call's error as a string, which was
  wrapped as a provider error. streamErrorText keeps it as the text the
  model reads.
- Bedrock's "on-demand throughput isn't supported" gets the model id hint.
- The thinking header uses the page language ("Thought for 1 second" in
  English), from the dictionary entries that were already there.

* chore(mcp-server): release the new features as 0.3.0

npm has 0.2.3. The earlier commits raised the version step by step to
0.6.0, but they ship together as one release.

* style: auto-format with Biome

* fix(chat): draw the built-in examples again and undo edit previews on errors

Found by the PR review:
- The built-in examples showed a finished card and an empty canvas. They
  are answered in the browser, never reach the tool handler, and relied
  on the final redraw that an earlier commit removed. The example branch
  now loads its diagram itself.
- When the request failed while an edit was streaming (a provider error,
  a lost connection), its preview stayed on the canvas. The error handler
  now restores the diagram from before the preview.
- The model picker could not scroll with the wheel or touch: the settings
  dialog blocks those events outside itself, and the picker is rendered
  outside it. The popover is modal now.
- A fetch error and the open picker stayed when switching providers.
- Editing a model id kept the old test warning and response time, which
  also hid the "may not be able to draw" hint for the new id.

* fix(mcp-server): keep both pages when get_diagram meets a page export, and more review fixes

Found by the PR review, each with a test that failed first:
- get_diagram during a page export returned the one-page projection on
  screen as the whole document (6 of 6 times when timed so). The preview
  page no longer answers a sync while a projection shows, and syncs after
  reloading, so the poll that restores the real document exports it.
- Exports are numbered on the server too: a late result of an export that
  timed out was saved as the next export's file.
- In Chrome, a new_xml with a syntax error counted the <parsererror>
  element as a second cell, so the web app rejected edits that auto-fix
  repairs ("must contain exactly one cell").
- hasCells missed single-quoted ids, so screenshot_diagram called such a
  diagram empty and auto-save never created its file.
- A literal \n directly under a <diagram> that has a model passed
  validation; only text-only pages are compressed data.
- A wrapped mxCell repeating its UserObject's id took the wrapper's place
  in edits, so delete and update left an empty or nested wrapper.
- Bare cells with a shape or edge id of "0" or "1" are rejected with a
  clear message instead of being renamed, which broke their edges.
- DRAWIO_DATA_DIR expands ~, which JSON configs pass on as it is.

* fix(server): count quota by the key actually used, and more review fixes

Found by the PR review, each with a test that failed first:
- Quota: any key header skipped it, even one the provider never reads
  (x-aws-access-key-id with OpenAI), so a request ran on the server's
  key without being counted. The check now runs after the model is
  resolved and uses usesServerCredentials. On main already.
- usesServerCredentials read the raw base URL; "/" cleans up to none, so
  an Ollama request ran on the server's key past the server-model check.
- SGLang's default 127.0.0.1:8000 only fills the settings form. Chat and
  the model list used it as a real address, so the server called its own
  machine even with private URLs blocked. Now a base URL is required.
- With a user's OpenAI key and no base URL, the SDK read the server's
  OPENAI_BASE_URL. The official endpoint is now passed. On main already.
- The Test button refused nothing on the server's keys (Ollama Cloud),
  and a 15 s timeout reported "connected, no tool call".
- The model list for Ollama without a base URL came from ollama.com while
  chat went to the server's Ollama.
- Bedrock's "Too many tokens, please wait" counted as context too long.
- On the server's keys the provider's error text stays in the server log;
  it can name the server's AWS account, role or internal hosts.
- Desktop app: the preset keys are the user's own (NEXT_AI_DRAWIO_DESKTOP),
  so Max Output Tokens can be raised and keyless models in settings work
  again. A launch that found the remembered port taken no longer replaces
  it, which hid the user's chats and settings for good.

* ci: run auto-format with the Biome version in package.json again

package.json moved to Biome 2.5.7 but the auto-format job stayed on
2.4.13. The two format some files differently, so on this PR the bot
reformatted tests/unit/log-save-route.test.ts with 2.4.13 and the lint
job, on 2.5.7, then failed on it. The pin now matches package.json, as
its comment asks, and the file is back in 2.5.7's format.

* fix(chat): keep the canvas after an unrelated error, and more review fixes

Found by the second PR review:
- After a streamed edit, an older render of the stream stored the edit's
  original diagram again, and the next failed request (no quota, a lost
  connection) put that old diagram back on the canvas. The tool handler
  now marks its call as handled, so the preview code leaves it alone.
- An edit applied before the UI showed an earlier broken edit's error was
  erased when that error undid its preview, or was built on that preview.
  The handler now starts from the diagram before all unhandled previews,
  and reads the diagram state that updates at once.
- A failed or stopped display_diagram left its half drawn diagram on the
  canvas. Its preview is undone now, like an edit's.
- "New chat" cleared a chat that could not be saved (storage full).
- The settings dialog showed a model list, a fetch error or a test result
  on the provider that was opened after the request started, and marked a
  model id changed during the test as tested.
- A tool call with broken JSON was shown as cut off by the output limit.
- History entries and session thumbnails could pair with a later diagram
  when draw.io answered an export late.
- A server model saved before non-ASCII provider names got into the id
  was reset to the default model.

* fix(mcp-server): count a one-page view only for that page, and more review fixes

Found by the second PR review:
- get_diagram with a page selector, or a rejected edit's error, counted
  the whole document as seen, so an edit on another page could overwrite
  the user's change there. A one-page view now counts for all pages only
  if the others are unchanged; otherwise the reply says to get them.
- add_page accepted shapes with the root cell ids "0" and "1" and renamed
  them, breaking their edges. The check also missed ids on UserObject
  wrappers and ids written with spaces around the "=".
- Root cells written over two lines were kept as an extra layer, cells
  with id = "a" did not count as cells, and CDATA text before a page's
  model passed the check although draw.io cannot open the page.
- Auto-save cleanup deleted the user's own files that start with mcp-.
  Only names in the session id format are removed now.
- Restoring a history entry dropped edits made in the browser since the
  last entry. They are added to history first.
- A session whose state expired showed a blank page, and the next change
  overwrote its auto-save file. The saved file is loaded instead.
- An edit on a page export's one-page projection, made before the real
  document was back, replaced the whole document.
- A late sync reply could overwrite a newer edit: each sync export is
  numbered, and the server ignores replies older than the current state.
- screenshot_diagram could return another session's image after
  start_session ran during its retries.

* fix(server): use the keys the user sent, and more review fixes

Found by the second PR review:
- With AWS_BEARER_TOKEN_BEDROCK set on the server, a request with the
  user's AWS keys ran on the server's token: the Bedrock SDK prefers it.
  Checked with Bedrock: invalid user keys used to get an answer.
- An OpenAI key with the official URL filled in (the settings form does
  that) went to the Responses API. Back to main's rule: a configured base
  URL uses Chat Completions.
- A user's Ollama key went to the server's OLLAMA_BASE_URL, for chat and
  for the model list. Like every other provider, it goes to the user's
  base URL or Ollama Cloud.
- The server's keyless Ollama and EdgeOne were not counted in the quota.
- AI_MODEL models on the server's keys ran on any provider with a server
  key, not only on AI_PROVIDER.
- A user's Azure key without a base URL used the server's resource name.
- The admin panel's Test button failed whenever access codes were set.
- DeepSeek's errors in the stream (plain text) were shown as they were,
  without a hint and also on the server's keys. Bedrock's throttling in
  the stream was not recognised as a rate limit.
- The EdgeOne function accepted text/plain; x=application/json, which
  other sites can send without a CORS preflight.
- Desktop app: a launch that found the old port taken for a moment (the
  previous version still quitting after an update) remembered the new
  port for good. The new port is kept only when Windows reserves the old
  one. A failed read of the presets file moved it aside as corrupt, and a
  save could then replace the presets. Switching presets on the same port
  now reloads the page. The dev launcher no longer misses a preset change
  made before or during a restart.

* fix(chat): undo rejected or stopped previews, and more fixes from the third review

- A call the server runs (get_shape_library) still reaches the browser's
  tool handler, and it dropped the stored diagram of an earlier broken
  edit, whose preview then stayed. Only the tools that draw take it now.
- A display_diagram whose final XML fails the checks loads the diagram
  from before its preview again, as a failed edit does.
- After Stop, a tool result that arrives later (a screenshot check still
  running) no longer sends a new request; Stop also skips calls the tool
  handler already took.
- New chat and opening another chat kept nothing of a diagram drawn
  without messages when it could not be saved; now they stay on it.
- The settings dialog drops a model list or test result whose provider
  credentials changed meanwhile, also in another tab.
- A saved provider this version does not know crashed the whole page on
  load; it is skipped.
- The input emptied a moment after the message showed in the chat, so it
  briefly appeared twice (seen as a flaky e2e test).
- The desktop app's preset switch on the same port refetches the server
  models instead of reloading the page, which lost unsent attachments.

* fix(mcp-server): recover sessions in one place, and more fixes from the third review

- A session whose state expired was recovered from its auto-save file only
  for the preview page; the tools built on their older copy and then
  overwrote the file. They now recover it first (restoreSavedSession).
- A preview tab that missed the last AI write pushed its older diagram
  over the recovered one after a restart. It now shows the recovered
  diagram and keeps its own copy in History.
- An empty record of what the model has seen (after load_diagram or a
  page tool on unseen changes) no longer lets one page of a multi-page
  document count for all, and get_diagram counts a page only once found.
- History: a thumbnail goes only to the entry it shows, the cached image
  never belongs to an older diagram, a re-serialized copy adds no entry,
  and a cleared document with its own pages is kept before a restore.
- The root cell id check reads attributes one by one: rack-id="1" or id
  text inside a label no longer counts.
- A compressed page counts as having cells; a saved file that could not
  be read is never written over.

* fix(server): keep users' keys at their own endpoints, and more fixes from the third review

- Bedrock: a user's AWS keys no longer go to an endpoint the server sets
  in AWS_ENDPOINT_URL_BEDROCK_RUNTIME / AWS_ENDPOINT_URL (read by the
  upgraded SDK), and admin panel keys win over AWS_BEARER_TOKEN_BEDROCK,
  as the Test button checks them. Checked with Bedrock.
- Ollama: a server key without a base URL (admin panel, OLLAMA_API_KEY)
  goes to Ollama Cloud, as env.example says, instead of 127.0.0.1.
- Quota: EdgeOne counts whatever key header comes along, keyless Ollama at
  a private address counts, and their provider texts stay in the log.
- An EdgeOne server model (admin panel, ai-models.json) works: the route
  checked the raw provider header, which holds the name's slug.
- parse-url ends downloads it does not read (too large, PDF, errors).
- Desktop app: the port follows where the chats are (IndexedDB per
  origin) instead of a remembered port, which could hide them for good;
  a same-port restart tells the page to refetch the server models; a
  failed preset switch no longer undoes a newer choice; a presets file
  removed after a failed read can be saved again; .env values quoted from
  start to end keep their inner quotes, as dotenv reads them.

* fix(security): check request sources, regions and endpoints

- Bedrock: a request's AWS region must be a region name. It becomes part
  of the endpoint's host name, so a value such as
  "us-east-1.attacker.example/" sent the server's bearer token or signed
  request to another host.
- MCP preview server: only the preview page itself (Origin equal to the
  Host) or a non-browser client may call it; a page on another localhost
  port could replace the diagram with a plain text POST. History builds
  its thumbnails element by element and shows only SVG data images, so a
  stored value can no longer run script in the preview.
- chat, validate-model, validate-diagram, provider-models and parse-url
  take JSON bodies only, so another website cannot make the user's own
  server (the desktop app, a local install) run models with their keys;
  the desktop app also refuses a foreign Host (DNS rebinding).
- The model list reads at most 2 MB, also through the Gateway SDK, and
  answers only with its own error texts: the URL is the caller's and may
  be an internal address.
- An admin panel provider with its own key and no URL no longer inherits
  the global <P>_BASE_URL, which may be a proxy for another key; OpenAI
  then gets the official endpoint, as its Test. Azure keeps the server's
  resource.

* fix: what the third round broke, and the first batch's review

MCP preview after the server lost a session (it expired, or the MCP
process restarted):
- Every server state has an id, made when the state is created. The tab
  notices a new id even when the version numbers happen to match, and
  every push names the state it was based on, so one based on a lost state
  is refused, also when it comes before the tab's first poll (the server
  recovers the saved file first).
- The tab keeps the newest canvas XML, saved or not. When the server knows
  nothing (no file) or exactly what the tab last saved, the canvas wins and
  is saved, so edits made while the server was down are kept. Otherwise
  the server's diagram (an AI write the tab missed, a cleared document
  that was saved) is shown and the tab's copy goes to History.
- Late answers to an old state's push or poll are dropped; a failed push
  says the server is unreachable; Download as .drawio saves the canvas.

Settings and server:
- Saved providers this version does not know stay in storage with their
  keys, and sending no longer trips over them.
- The desktop "Ollama (Local)" preset with a key goes to local Ollama
  again; a server model's Ollama URL variable is read; the admin panel
  writes Ollama Cloud's URL for a key without one.
- Provider error texts show again in the desktop app and for EdgeOne.
- .env: a quoted value followed by a comment ending in a quote is read as
  dotenv reads it; unquoted values are unchanged.
- Desktop app: the next launch opens the port where a chat was last
  saved; a launch elsewhere that saves nothing does not move it, and a
  page with no chats lets the next launch try the other port once.
- The Test button no longer stays busy after another tab changed the key.
- A completed append_diagram is no longer undone by an earlier failed
  edit's preview; a file read once in vain is saved again once it is read
  or gone.

From the first batch's review:
- The admin panel's Test of an entry without a URL now tests the server's
  <P>_BASE_URL, where chat sends the entry's key; chat is unchanged (the
  first fix rerouted working setups).
- The model list ends downloads that are too large, accepts answers
  without a body, and keeps the "redirects are not allowed" explanation.
- A test covers the preview's History rendering.

* fix: older defects (batch C) and the second batch's review

Chats:
- New Chat right after an answer saves that chat once. Saves run one at
  a time and read the chat on screen when their turn comes; a save
  scheduled for a chat that is no longer on screen is dropped. A chat
  whose id was still on its way to the URL no longer comes back after
  New Chat (the next answer went into it).
- Crossing the 768 px breakpoint keeps the chat panel: a streaming answer,
  unsaved messages and attachments stay. The panel gets the sizes of each
  side, and a panel collapsed on desktop opens on mobile.
- The chat's export waits for its own reply: an edit's history export
  still on its way no longer answers it with the older diagram, and two
  file saves at once no longer swap results.
- A second edit in one answer is previewed on the first edit's result.
- Stop also ends a running screenshot check; a chat that cannot be saved
  (storage full) can be left with "Continue without saving".
- Small diagrams with shapes count as diagrams; the tool card no longer
  crashes on malformed operations.

Quota and providers:
- Requests that reach the server's own endpoints count toward the quota:
  EdgeOne (always its own endpoint now), a private base URL whatever key
  header is sent, keyless Ollama without a URL. With the quota on, a
  redirect is followed only to a public address. The output cap applies
  to these requests too.
- Stop records the tokens of the steps that finished; the screenshot check
  counts its tokens without counting a request.
- EdgeOne configured only by AI_PROVIDER works, also in the admin Test,
  which forwards the access code. Azure set up only in the admin panel
  works in chat. The Test sends a Bedrock session token.
- The admin panel's Test of an entry without a URL uses the server's URL
  as the server does (no private address check for it); the admin panel
  no longer writes an Ollama URL.

MCP server:
- Write tools and start_session run one at a time, so two at once never
  drop each other's change; a cancelled call waiting its turn is skipped.
  get_diagram and export_diagram keep the session they started with.
- Export to .drawio first gets the user's latest edits from the browser.
- History thumbnails: one that arrives after the next AI write is
  dropped; a sync reply keeps the image; a version that changed only page
  settings is its own entry.
- A diagram over the 10 MB limit is saved without its image, or the user
  is told to download it (the server now answers 413 instead of cutting
  the connection).
- Labels holding text like id='1' or parent='1' are no longer read as
  attributes (a layer or a parent was deleted). A broken bare
  <mxGraphModel> file is refused.
- After a sync reply the tab no longer sends its autosave copy again.

Desktop and files:
- A newer switch of the same preset is not rolled back by an older one
  that failed. .env values with escaped quotes are read whole.
- MCP saved files: a file that could not be read stays protected while a
  folder without permission hides it, and is saved again once deleted.
- The desktop app reports "no chats" only when the count was read and no
  model settings are stored.

* fix: what the batch C review found

- A redirect followed for a custom base URL (quota on) no longer carries
  the user's key or cookies to another origin, as fetch itself does, and
  a private address may redirect to another private one (already counted).
- The admin Test of an Ollama or Vertex AI entry without a URL goes where
  chat sends that entry's key: the environment's own URL variable, for
  Ollama else the local default. The Test of an Ollama Cloud key without
  a URL went to the cloud while chat went to local Ollama.
- Chat saves: each save notes the chat on screen and the order of the
  reads before reading its data. A save read before switching chats no
  longer writes into the chat switched to, and a copy that waited for its
  thumbnail no longer replaces a newer one.
- "Continue without saving" keeps its button when a later auto-save fails,
  and goes away when a new message is sent.
- A screenshot check that was waiting for its image when the user pressed
  Stop stays skipped after the next message.
- MCP History: draw.io's own copy of a diagram (after get_diagram) no
  longer adds an entry without a picture; a change of background is still
  its own version. The tab ignores an edit's answer that arrives after a
  newer AI write loaded.
- Desktop: a deleted preset is not brought back by a failed switch, and a
  request naming no preset does not stop a rollback. An origin keeping
  an access code counts as having settings.
- .env: a quoted value ending in a backslash ("C:\dir\") is read as dotenv
  reads it.
- The tool card no longer crashes on an id that does not turn into text;
  an older Test's success timer no longer ends a newer Test's spinner.
- Tests that passed without their fix now check it.

* fix: what the whole-PR review and Copilot found

- A redirect followed for a custom base URL also drops the key headers of
  providers that do not use Authorization (x-api-key, x-goog-api-key,
  api-key) when it goes to another origin.
- A second Enter or click while a message is being prepared (attachments
  read, diagram exported) no longer sends it twice.
- The admin Test on the deployment's own endpoints (EdgeOne, the server's
  keyless Ollama, an address on the server's network) counts toward the
  quota like a chat; the chat and the Test share one rule for it. The
  Test of an Azure entry set up by AZURE_RESOURCE_NAME only goes where chat
  goes.
- EdgeOne's function is called at the site root again, as on main: EdgeOne
  serves edge functions there, outside Next's base path.
- MCP History: the state before a write is kept unless the browser saved
  no change of the user's since the last server write (draw.io's sync copy
  of it adds no entry), and the dedupe compares the exact text again, so a
  change of page size or other settings only is its own version.
- MCP: an edit keeps untouched labels as draw.io shows them (a literal line
  break in an attribute is a space); a new document of empty pages the
  user named is auto-saved; load_diagram reads only regular files, so a
  pipe cannot hold up the other write tools; the preview does not load
  back its own push still on its way (an undo made meanwhile is saved).
- Two overlapping saves of a new chat no longer reload the canvas from the
  older copy.
- At most three screenshot checks per user turn, passed or failed, as
  documented.
- Desktop: the main window navigates only within the app (draw.io stays in
  its frame); a presets file that is not JSON and cannot be moved aside is
  not overwritten.
- A last self-closing cell with a raw "<" in a value is not taken for cut
  off output.
- README: Material Design shapes load their icons from fonts.gstatic.com.

* fix(chat): stop saving and exporting an idle chat every second

Each auto-save takes a thumbnail, and draw.io's SVG gets a new random id
every time, so latestSvg changed and the diagram context rendered again.
getThumbnailSvg was a new function on every render, the auto-save depends
on it, so the next save was scheduled a second later: a chat with some
diagrams was saved and exported once a second for as long as it was open.
getThumbnailSvg (and the export helper it uses) now keep one identity;
they read refs only.

Found by hand in the production build; the new e2e test fails without the
fix on a production build (as CI runs it).

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
This commit is contained in:
Dayuan Jiang
2026-10-05 22:39:32 +09:00
committed by GitHub
co-authored by github-actions[bot]
parent a45e5b6796
commit 0b63e28e5a
192 changed files with 20781 additions and 6839 deletions
+100 -35
View File
@@ -7,7 +7,10 @@
* first page is targeted (the "active page by convention" — see pages.ts).
*/
import { findPageElement, hasPageSelector, type PageSelector } from "./pages.js"
import { decompressPageContent } from "./load-diagram.ts"
import { log } from "./logger.ts"
import { findPageElement, hasPageSelector, type PageSelector } from "./pages.ts"
import { getXmlSyntaxError } from "./xml-syntax.ts"
export interface DiagramOperation {
operation: "update" | "add" | "delete"
@@ -26,6 +29,56 @@ export interface ApplyOperationsResult {
errors: OperationError[]
}
// Cells with links, tooltips or custom data are stored as
// <UserObject id="..."><mxCell .../></UserObject> (or <object>): the id sits
// on the wrapper, so the wrapper is treated as the cell.
const CELL_SELECTOR = "mxCell, UserObject, object"
/**
* Return the <root> of a <diagram> page, creating it when missing. An empty
* page gets a blank model with the "0" and "1" root cells; a page whose text
* is draw.io's compressed format is decompressed in place. Returns null if
* the text is neither empty nor decompressible.
*/
function ensurePageRoot(doc: Document, page: Element): Element | null {
const existing = page.querySelector("root")
if (existing) return existing
let model = page.querySelector("mxGraphModel")
if (!model) {
const text = page.textContent?.trim() ?? ""
if (text) {
const xml = decompressPageContent(text)
if (!xml || getXmlSyntaxError(xml)) return null
const parsed = new DOMParser().parseFromString(xml, "text/xml")
if (parsed.documentElement?.tagName !== "mxGraphModel") return null
page.textContent = ""
model = page.appendChild(
doc.importNode(parsed.documentElement, true),
) as Element
const decompressedRoot = model.querySelector("root")
if (decompressedRoot) return decompressedRoot
} else {
model = page.appendChild(doc.createElement("mxGraphModel"))
}
}
const blank = new DOMParser().parseFromString(
`<root><mxCell id="0"/><mxCell id="1" parent="0"/></root>`,
"text/xml",
)
return model.appendChild(
doc.importNode(blank.documentElement, true),
) as Element
}
/** Read parent/source/target, which a wrapped cell keeps on its inner mxCell. */
function cellAttr(cell: Element, name: string): string | null {
const inner =
cell.tagName === "mxCell" ? cell : cell.querySelector("mxCell")
return inner?.getAttribute(name) ?? null
}
/**
* Apply diagram operations (update/add/delete) using ID-based lookup.
*
@@ -43,12 +96,8 @@ export function applyDiagramOperations(
): ApplyOperationsResult {
const errors: OperationError[] = []
// Parse the XML
const parser = new DOMParser()
const doc = parser.parseFromString(xmlContent, "text/xml")
// Check for parse errors
const parseError = doc.querySelector("parsererror")
// Check for syntax errors, then parse the XML
const parseError = getXmlSyntaxError(xmlContent)
if (parseError) {
return {
result: xmlContent,
@@ -56,11 +105,13 @@ export function applyDiagramOperations(
{
type: "update",
cellId: "",
message: `XML parse error: ${parseError.textContent}`,
message: `XML parse error: ${parseError}`,
},
],
}
}
const parser = new DOMParser()
const doc = parser.parseFromString(xmlContent, "text/xml")
// Locate the <root> element to operate on.
//
@@ -86,7 +137,7 @@ export function applyDiagramOperations(
],
}
}
root = found.element.querySelector("root")
root = ensurePageRoot(doc as unknown as Document, found.element)
if (!root) {
const pageId =
found.element.getAttribute("id") || `(index ${found.index})`
@@ -96,7 +147,7 @@ export function applyDiagramOperations(
{
type: "update",
cellId: "",
message: `Page "${pageId}" has no <root> element`,
message: `Page "${pageId}" has no <root> element and its content could not be decompressed`,
},
],
}
@@ -132,10 +183,16 @@ export function applyDiagramOperations(
// Build a map of cell IDs to elements (scoped to the resolved page).
const cellMap = new Map<string, Element>()
root.querySelectorAll("mxCell").forEach((cell) => {
root.querySelectorAll(CELL_SELECTOR).forEach((cell) => {
const id = cell.getAttribute("id")
if (id) cellMap.set(id, cell)
// A wrapped mxCell may repeat its wrapper's id; the wrapper is the cell
const wrapped =
cell.tagName === "mxCell" &&
/^(UserObject|object)$/.test(cell.parentElement?.tagName ?? "")
if (id && !wrapped) cellMap.set(id, cell)
})
// Ids deleted so far in this batch; deleting one again is a no-op
const deletedIds = new Set<string>()
// Process each operation
for (const op of operations) {
@@ -164,7 +221,7 @@ export function applyDiagramOperations(
`<wrapper>${op.new_xml}</wrapper>`,
"text/xml",
)
const newCell = newDoc.querySelector("mxCell")
const newCell = newDoc.querySelector(CELL_SELECTOR)
if (!newCell) {
errors.push({
type: "update",
@@ -216,7 +273,7 @@ export function applyDiagramOperations(
`<wrapper>${op.new_xml}</wrapper>`,
"text/xml",
)
const newCell = newDoc.querySelector("mxCell")
const newCell = newDoc.querySelector(CELL_SELECTOR)
if (!newCell) {
errors.push({
type: "add",
@@ -256,8 +313,15 @@ export function applyDiagramOperations(
const existingCell = cellMap.get(op.cell_id)
if (!existingCell) {
// Cell not found - might have been cascade-deleted by a previous operation
// Skip silently instead of erroring (AI may redundantly list children/edges)
// Skip cells already cascade-deleted by a previous operation
// (AI may redundantly list children/edges); warn otherwise
if (!deletedIds.has(op.cell_id)) {
errors.push({
type: "delete",
cellId: op.cell_id,
message: `Cell with id="${op.cell_id}" not found`,
})
}
continue
}
@@ -270,17 +334,17 @@ export function applyDiagramOperations(
cellsToDelete.add(cellId)
// Find children (cells where parent === cellId)
// Scoped to `root` so other pages' cells with the same parent id
// (notably "1") are never touched.
const children = root!.querySelectorAll(
`mxCell[parent="${cellId}"]`,
)
children.forEach((child) => {
const childId = child.getAttribute("id")
if (childId && childId !== "0" && childId !== "1") {
// cellMap only holds this page's cells, so other pages' cells
// with the same parent id (notably "1") are never touched.
for (const [childId, child] of cellMap) {
if (
childId !== "0" &&
childId !== "1" &&
cellAttr(child, "parent") === cellId
) {
collectDescendants(childId)
}
})
}
}
// Collect the target cell and all its descendants
@@ -289,23 +353,23 @@ export function applyDiagramOperations(
// Find edges referencing any of the cells to be deleted
// Also recursively collect children of those edges (e.g., edge labels)
for (const cellId of cellsToDelete) {
const referencingEdges = root.querySelectorAll(
`mxCell[source="${cellId}"], mxCell[target="${cellId}"]`,
)
referencingEdges.forEach((edge) => {
const edgeId = edge.getAttribute("id")
for (const [edgeId, edge] of cellMap) {
// Protect root cells from being added via edge references
if (edgeId && edgeId !== "0" && edgeId !== "1") {
if (edgeId === "0" || edgeId === "1") continue
if (
cellAttr(edge, "source") === cellId ||
cellAttr(edge, "target") === cellId
) {
// Recurse to collect edge's children (like labels)
collectDescendants(edgeId)
}
})
}
}
// Log what will be deleted
// Log what will be deleted (stderr: stdout carries JSON-RPC)
if (cellsToDelete.size > 1) {
console.log(
`[applyDiagramOperations] Cascade delete "${op.cell_id}" → deleting ${cellsToDelete.size} cells: ${Array.from(cellsToDelete).join(", ")}`,
log.debug(
`Cascade delete "${op.cell_id}" → deleting ${cellsToDelete.size} cells: ${Array.from(cellsToDelete).join(", ")}`,
)
}
@@ -316,6 +380,7 @@ export function applyDiagramOperations(
cell.parentNode?.removeChild(cell)
cellMap.delete(cellId)
}
deletedIds.add(cellId)
}
}
}
+98
View File
@@ -0,0 +1,98 @@
/**
* DOM setup for Node. The XML helpers use the global DOMParser and
* XMLSerializer, which the browser has and Node gets from here.
*
* linkedom gives us a DOM with querySelector, but it is lenient: it never
* reports syntax errors (no <parsererror>; xml-syntax.ts checks them), and
* its serializer writes raw newlines inside attribute values, which the
* browser reads back as spaces. serializeXml writes attribute values safely.
*/
import { DOMParser } from "linkedom"
const ESCAPES: Record<string, string> = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"\t": "&#9;",
"\n": "&#xa;",
"\r": "&#xd;",
}
const escapeChars = (text: string, chars: RegExp) =>
text.replace(chars, (c) => ESCAPES[c])
/**
* Serialize a linkedom node as XML. Attribute values escape tabs and line
* breaks too, so multi-line labels (value="a&#xa;b") survive a round trip.
*/
export function serializeXml(node: Node): string {
switch (node.nodeType) {
case 9: {
// Document
const root = (node as Document).documentElement
return root ? serializeXml(root) : ""
}
case 1: {
// Element
const el = node as Element
let out = `<${el.tagName}`
for (const attr of Array.from(el.attributes)) {
out += ` ${attr.name}="${escapeChars(attr.value, /[&<>"\t\n\r]/g)}"`
}
if (el.childNodes.length === 0) return `${out}/>`
out += ">"
for (const child of Array.from(el.childNodes)) {
out += serializeXml(child)
}
return `${out}</${el.tagName}>`
}
case 3:
// Text
return escapeChars(node.textContent ?? "", /[&<>]/g)
case 4:
// CDATA
return `<![CDATA[${node.textContent ?? ""}]]>`
case 8:
// Comment
return `<!--${node.textContent ?? ""}-->`
default:
return ""
}
}
/**
* XML parsers read a literal tab or line break inside an attribute value as
* a space (a line break written as &#xa; stays one). linkedom keeps it, and
* serializeXml would then write it as a real line break, so an edit would
* change labels it never touched. Applied to the text before linkedom.
*/
function normalizeAttributeWhitespace(xml: string): string {
return xml.replace(
/<[A-Za-z][^"'<>]*(?:(?:"[^"]*"|'[^']*')[^"'<>]*)*>/g,
(tag) =>
tag.replace(/"[^"]*"|'[^']*'/g, (value) =>
value.replace(/\r\n|[\t\n\r]/g, " "),
),
)
}
class XmlDomParser extends DOMParser {
parseFromString(text: string, type: string) {
return super.parseFromString(
type.includes("xml") ? normalizeAttributeWhitespace(text) : text,
type as any,
)
}
}
class XMLSerializerPolyfill {
serializeToString(node: Node): string {
return serializeXml(node)
}
}
/** Install the DOMParser and XMLSerializer globals the XML helpers use. */
export function installDomPolyfill(): void {
;(globalThis as any).DOMParser = XmlDomParser
;(globalThis as any).XMLSerializer = XMLSerializerPolyfill
}
+107
View File
@@ -0,0 +1,107 @@
/**
* Drawing guide for the model, returned by start_session, get_drawing_guide
* and the diagram-workflow prompt.
*
* Adapted from the web app's system prompt (lib/system-prompts.ts) and its
* tool descriptions (app/api/chat/route.ts). When drawing rules change there,
* update this file too.
*/
import {
indent,
SWIMLANE_EXAMPLE,
TWO_EDGES_EXAMPLE,
WAYPOINT_EXAMPLE,
} from "./xml-examples.ts"
export const DRAWING_GUIDE = `# Draw.io drawing guide
## Workflow
- create_new_diagram draws a new diagram and REPLACES the whole document. add_page adds another tab. edit_diagram changes cells of an existing page. load_diagram opens a .drawio file (the server reads the file itself). get_diagram returns the current XML, including the user's manual edits. export_diagram saves to a file.
- Before drawing, describe your layout plan in 2-3 sentences, so shapes do not overlap and edges do not cross shapes.
- Send XML only through tool calls, never in chat text. Never draw a box just to send the user a message.
- Before using any icon library (AWS, Azure, GCP, Kubernetes, Cisco, BPMN, Material Design, web icons...), call get_shape_library and use the exact style names it returns. NEVER guess icon style names. For AWS, use the AWS 2025 icons (library aws4).
- After drawing or heavily editing a complex diagram, call screenshot_diagram once to see the result, and fix overlapping shapes and edges that cross shapes.
- When replicating a diagram from an image, match its style and layout closely: straight or curved lines, rounded or square shapes.
- The preview page has History (it saves a snapshot before every AI change and can restore any of the last 20 versions) and Download. You can make changes freely; nothing is lost.
## The XML you send
Single page (create_new_diagram, add_page): send ONLY the mxCell elements. The server adds <mxfile>, <mxGraphModel>, <root> and the root cells id="0" and id="1".
<mxCell id="2" value="Label" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="3" style="edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.5;entryX=0;entryY=0.5;endArrow=classic;html=1;" edge="1" parent="1" source="2" target="4">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
Several pages at once (create_new_diagram only): send a full <mxfile> with one <diagram id="..." name="..."> per page. Every page's <root> must start with <mxCell id="0"/><mxCell id="1" parent="0"/>.
Rules (XML that breaks them is rejected):
1. All mxCell elements are siblings. NEVER nest an mxCell inside another mxCell.
2. Ids are unique within a page and start from "2" ("0" and "1" are the root cells).
3. parent="1" for top-level shapes, parent="<container id>" for shapes inside a container.
4. Edge source and target must reference existing cell ids.
5. Escape special characters in attribute values: &lt; for <, &gt; for >, &amp; for &, &quot; for ".
6. NEVER include XML comments (<!-- -->). draw.io strips them.
7. In tool arguments (JSON), every " inside the XML must be escaped as \\".
Containers and swimlanes: children use the container id as parent and coordinates relative to the container.
${indent(SWIMLANE_EXAMPLE)}
## Layout
- Keep every element of a page within x 0 to 800 and y 0 to 600, so the whole diagram fits one view without a page break.
- Containers (for example AWS cloud boxes) are at most 700 pixels wide and 550 pixels tall.
- Start near x=40, y=40 and keep elements grouped closely.
- For large diagrams, stack vertically or use a grid instead of spreading wide.
## Edge routing rules
Rule 1: Never let two edges share a path. Two edges between the same nodes exit and enter at different points (exitY=0.3 for the first, exitY=0.7 for the second, not both 0.5).
Rule 2: For bidirectional connections (A to B and B to A), use opposite sides: A exits right (exitX=1) into the left of B (entryX=0); B exits left (exitX=0) into the right of A (entryX=1).
Rule 3: Always set exitX, exitY, entryX and entryY in the edge style, e.g. style="edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.3;entryX=0;entryY=0.3;endArrow=classic;".
Rule 4: Route edges AROUND shapes in the way. Before drawing an edge, find every shape between source and target; if one is in the path, add waypoints. Route diagonal connections along the outside of the diagram, not through the middle. Keep 20-30px clearance from shapes. An edge must never cross another shape's box.
Rule 5: Plan the layout first. Organize shapes into rows or columns following the flow, space them 150-200px apart so edges have room, and prefer one flow direction (left to right or top to bottom).
Rule 6: Use 2-3 waypoints for L-shaped or U-shaped paths. Each change of direction needs a waypoint, and segments should be horizontal or vertical.
Rule 7: Use natural connection points. Never connect at corners (both X and Y 0 or 1). Top-to-bottom flow: exitY=1 into entryY=0. Left-to-right flow: exitX=1 into entryX=0. Diagonal: the side closest to the target.
Before sending XML, check:
1. Does any edge cross a shape that is not its source or target? Add waypoints.
2. Do two edges share a path? Change their exit or entry points.
3. Is any connection point at a corner? Use the middle of a side.
4. Could moving shapes remove edge crossings? Revise the layout.
Two edges between the same nodes:
${indent(TWO_EDGES_EXAMPLE)}
Waypoints go inside <Array as="points"> in the edge geometry. Example: Hotfix (right, bottom) connects to Main (center, top) while Develop (center, middle) is in between, so the edge goes right to x=750 first, then up, and enters Main from the right:
${indent(WAYPOINT_EXAMPLE)}
## Styles
- Shapes: rounded=1, fillColor=#hex, strokeColor=#hex, whiteSpace=wrap;html=1;
- Edges: endArrow=classic, block, open or none; startArrow=none or classic; curved=1; edgeStyle=orthogonalEdgeStyle
- Text: fontSize=14, fontStyle=1 (bold), align=center, left or right
- Animated connectors: add flowAnimation=1 to the edge style.
## Minimal style
When the user asks for a minimal, plain, black-and-white or unstyled diagram, use these rules instead of the styles above:
- No fillColor, strokeColor, rounded, fontSize, fontStyle or hex colors.
- Shapes use style "whiteSpace=wrap;html=1;", edges use "html=1;endArrow=classic;".
- Containers that hold other shapes use "whiteSpace=wrap;html=1;fillColor=none;" so they do not cover their children.
- Keep at least 50px between elements, and follow all edge routing rules strictly.
## Editing with edit_diagram
- update replaces a cell: send the complete mxCell including mxGeometry, with the same id as cell_id.
- add inserts a new cell with a new id. One cell per operation.
- delete removes a cell. Its children and every edge connected to it are deleted too, so give only the container's id.
- All-or-nothing: if any operation fails, nothing is applied. A rejected call includes the current XML of the page; rebuild your operations on it and retry.
- If the diagram is large, change it with edit_diagram instead of redrawing it.
{"operations": [{"operation": "update", "cell_id": "3", "new_xml": "<mxCell id=\\"3\\" value=\\"New Label\\" style=\\"rounded=1;\\" vertex=\\"1\\" parent=\\"1\\"><mxGeometry x=\\"100\\" y=\\"100\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/></mxCell>"}]}
{"page_name": "CNN", "operations": [{"operation": "add", "cell_id": "conv-1", "new_xml": "<mxCell id=\\"conv-1\\" value=\\"Conv\\" vertex=\\"1\\" parent=\\"1\\"><mxGeometry x=\\"40\\" y=\\"40\\" width=\\"120\\" height=\\"60\\" as=\\"geometry\\"/></mxCell>"}]}
{"page_index": 1, "operations": [{"operation": "delete", "cell_id": "5"}]}
Pages: list_pages shows every page's id, name and index. edit_diagram, get_diagram and export_diagram take an optional page_id, page_name or page_index; without one they use the first page.
`
+109
View File
@@ -0,0 +1,109 @@
/**
* Core of the edit_diagram tool, kept free of session state so it can be
* unit tested.
*
* All-or-nothing, like the web app (hooks/use-diagram-tool-handlers.ts):
* if any operation fails, nothing is written and every failure is reported,
* so the model never builds on a half-applied edit.
*/
import {
applyDiagramOperations,
type DiagramOperation,
} from "./diagram-operations.ts"
import { type PageSelector, projectPage } from "./pages.ts"
import { validateAndFixXml, validateMxCellStructure } from "./xml-validation.ts"
export type EditOutcome =
| { ok: true; xml: string; applied: number; fixes: string[] }
| { ok: false; errors: string[]; pageError: boolean }
/** Number of top-level elements in an XML fragment. */
function countTopLevelElements(fragment: string): number {
const doc = new DOMParser().parseFromString(
`<wrapper>${fragment}</wrapper>`,
"text/xml",
)
// On a syntax error the browser adds a <parsererror> element (Chrome
// next to the cells, Firefox as the root); the syntax is checked later
const root = doc.documentElement
if (!root || root.tagName === "parsererror") return 1
return Array.from(root.children).filter(
(el) => el.tagName !== "parsererror",
).length
}
/** The target page as a one-page <mxfile>, or the whole document. */
export function targetPageXml(xml: string, selector: PageSelector): string {
const projection = projectPage(xml, selector)
return projection.ok ? projection.xml : xml
}
export function editDiagram(
xml: string,
operations: DiagramOperation[],
selector: PageSelector,
): EditOutcome {
const errors: string[] = []
const fixes: string[] = []
const prepared: DiagramOperation[] = []
for (const op of operations) {
if (op.operation === "delete" || !op.new_xml) {
prepared.push(op)
continue
}
// Checked before validation: several cells fail the strict parser
// with a misleading "only one root" syntax error.
if (countTopLevelElements(op.new_xml) > 1) {
errors.push(
`${op.operation} ${op.cell_id}: new_xml must contain exactly one cell; use one add operation per cell`,
)
continue
}
const check = validateAndFixXml(op.new_xml)
if (!check.valid) {
errors.push(
`${op.operation} ${op.cell_id}: invalid new_xml: ${check.error}`,
)
continue
}
if (check.fixed) {
fixes.push(`${op.cell_id}: ${check.fixes.join(", ")}`)
}
prepared.push({ ...op, new_xml: check.fixed ?? op.new_xml })
}
if (errors.length > 0) return { ok: false, errors, pageError: false }
const { result, errors: opErrors } = applyDiagramOperations(
xml,
prepared,
selector,
)
// An empty cellId means the page itself could not be edited
const pageLevel = opErrors.find((e) => e.cellId === "")
if (pageLevel) {
return { ok: false, errors: [pageLevel.message], pageError: true }
}
if (opErrors.length > 0) {
return {
ok: false,
errors: opErrors.map((e) => `${e.type} ${e.cellId}: ${e.message}`),
pageError: false,
}
}
// Validate only the target page, and reject only errors this edit
// introduced: problems already in other pages or in a loaded file must
// not block every edit.
const after = validateMxCellStructure(targetPageXml(result, selector))
if (after && !validateMxCellStructure(targetPageXml(xml, selector))) {
return {
ok: false,
errors: [`the edit would make the page invalid: ${after}`],
pageError: false,
}
}
return { ok: true, xml: result, applied: operations.length, fixes }
}
+43 -1
View File
@@ -17,7 +17,14 @@
* change: the set of pages, each page's name, and each page's cell tree
* (tags + sorted attributes + text). Byte equality is kept as a fast path.
*/
import { isMxGraphModel, normalizeToMxfile, parseMxfile } from "./pages.js"
import {
findPageElement,
isMxGraphModel,
normalizeToMxfile,
type PageSelector,
parseMxfile,
serializeMxfile,
} from "./pages.ts"
export type EditGateResult =
| { ok: true }
@@ -100,3 +107,38 @@ export function checkEditGate(
}
return { ok: true }
}
/**
* The model was shown only the selected page of liveXml (get_diagram with a
* page selector, or a rejected edit's error). It has seen the whole document
* if the other pages are as it last saw them, or if it saw nothing before
* (it then has no old copy of them to edit from). Returns the new
* lastSeenXml: liveXml, or lastSeenXml unchanged.
*/
export function markPageSeen(
lastSeenXml: string,
liveXml: string,
selector: PageSelector,
): string {
const parse = (xml: string) => {
const normalized = normalizeToMxfile(xml)
return normalized ? parseMxfile(normalized) : null
}
// An empty record also follows load_diagram and page tools that wrote
// over unseen changes, when the model may remember older pages: only
// a one-page document is then fully seen
if (!lastSeenXml) {
const pages = parse(liveXml)?.querySelectorAll("diagram").length ?? 1
return pages <= 1 ? liveXml : lastSeenXml
}
const otherPages = (xml: string) => {
const doc = parse(xml)
if (!doc) return null
findPageElement(doc, selector)?.element.remove()
return contentFingerprint(serializeMxfile(doc))
}
const before = otherPages(lastSeenXml)
return before !== null && before === otherPages(liveXml)
? liveXml
: lastSeenXml
}
+25
View File
@@ -0,0 +1,25 @@
/**
* A queue for tool handlers: each call waits until the previous one ended.
* A tool call the client cancelled while it waited (the MCP SDK aborts its
* extra.signal, the handler's last argument) is skipped.
*/
export function createExclusive() {
let tail: Promise<unknown> = Promise.resolve()
return function exclusive<T extends (...args: any[]) => Promise<unknown>>(
handler: T,
): T {
return ((...args: unknown[]) => {
const extra = args.at(-1) as { signal?: AbortSignal } | undefined
const run = tail.then(() =>
extra?.signal?.aborted
? {
content: [{ type: "text", text: "Cancelled." }],
isError: true,
}
: handler(...args),
)
tail = run.catch(() => {})
return run
}) as T
}
}
+31 -14
View File
@@ -3,10 +3,18 @@
* Stores {xml, svg} entries in a circular buffer
*/
import { log } from "./logger.js"
import { log } from "./logger.ts"
const MAX_HISTORY = 20
const historyStore = new Map<string, Array<{ xml: string; svg: string }>>()
interface HistoryEntry {
id: number // Stable across shifts of the circular buffer
xml: string
svg: string
}
let nextEntryId = 0
const historyStore = new Map<string, HistoryEntry[]>()
export function addHistory(sessionId: string, xml: string, svg = ""): number {
let history = historyStore.get(sessionId)
@@ -15,13 +23,16 @@ export function addHistory(sessionId: string, xml: string, svg = ""): number {
historyStore.set(sessionId, history)
}
// Dedupe: skip if same as last entry
// Dedupe: skip if same as last entry (any other change, also of page
// settings only, is a new version; keepInHistory leaves out draw.io's
// copy of a server write)
const last = history[history.length - 1]
if (last?.xml === xml) {
if (last && last.xml === xml) {
if (svg && !last.svg) last.svg = svg
return history.length - 1
}
history.push({ xml, svg })
history.push({ id: nextEntryId++, xml, svg })
// Circular buffer
if (history.length > MAX_HISTORY) {
@@ -32,29 +43,35 @@ export function addHistory(sessionId: string, xml: string, svg = ""): number {
return history.length - 1
}
export function getHistory(
sessionId: string,
): Array<{ xml: string; svg: string }> {
export function getHistory(sessionId: string): HistoryEntry[] {
return historyStore.get(sessionId) || []
}
/** Look up an entry by its id; the array index shifts as old entries drop. */
export function getHistoryEntry(
sessionId: string,
index: number,
): { xml: string; svg: string } | undefined {
const history = historyStore.get(sessionId)
return history?.[index]
id: number,
): HistoryEntry | undefined {
return historyStore.get(sessionId)?.find((entry) => entry.id === id)
}
export function clearHistory(sessionId: string): void {
historyStore.delete(sessionId)
}
export function updateLastHistorySvg(sessionId: string, svg: string): boolean {
/**
* Give the last entry the image the browser took of shownXml, the diagram
* it just loaded, when that entry is this diagram
*/
export function updateLastHistorySvg(
sessionId: string,
svg: string,
shownXml: string,
): boolean {
const history = historyStore.get(sessionId)
if (!history || history.length === 0) return false
const last = history[history.length - 1]
if (!last.svg) {
if (!last.svg && last.xml === shownXml) {
last.svg = svg
return true
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+15 -11
View File
@@ -7,15 +7,15 @@
* diagram's text content. The rest of the server assumes plain XML inside
* every <diagram>, so loading decompresses all pages up front.
*/
import { inflateRawSync } from "node:zlib"
import { DOMParser } from "linkedom"
import { inflateRaw } from "pako"
import {
isMxFile,
isMxGraphModel,
normalizeToMxfile,
parseMxfile,
serializeMxfile,
} from "./pages.js"
} from "./pages.ts"
import { getXmlSyntaxError } from "./xml-syntax.ts"
export type LoadResult =
| { ok: true; xml: string }
@@ -27,9 +27,11 @@ export type LoadResult =
*/
export function decompressPageContent(compressed: string): string | null {
try {
const inflated = inflateRawSync(
Buffer.from(compressed.trim(), "base64"),
).toString("utf-8")
// atob and pako work in Node and in the browser
const bytes = Uint8Array.from(atob(compressed.trim()), (c) =>
c.charCodeAt(0),
)
const inflated = inflateRaw(bytes, { to: "string" })
try {
return decodeURIComponent(inflated)
} catch {
@@ -48,14 +50,16 @@ export function decompressPageContent(compressed: string): string | null {
* any compressed pages.
*/
export function parseDrawioFileContent(content: string): LoadResult {
const trimmed = content.trim()
let trimmed = content.trim()
if (!trimmed) return { ok: false, error: "File is empty." }
if (isMxGraphModel(trimmed)) {
const normalized = normalizeToMxfile(trimmed)
return normalized
? { ok: true, xml: normalized }
: { ok: false, error: "Failed to parse <mxGraphModel> XML." }
if (!normalized) {
return { ok: false, error: "Failed to parse <mxGraphModel> XML." }
}
// Parsed below like any <mxfile>, so a broken model is an error
trimmed = normalized
}
if (!isMxFile(trimmed)) {
return {
@@ -82,7 +86,7 @@ export function parseDrawioFileContent(content: string): LoadResult {
}
const inner = new DOMParser().parseFromString(xml, "text/xml")
if (
inner.querySelector("parsererror") ||
getXmlSyntaxError(xml) ||
inner.documentElement?.tagName !== "mxGraphModel"
) {
return {
+2 -1
View File
@@ -14,7 +14,8 @@ export const log = {
console.error(`[MCP-DrawIO] [ERROR] ${msg}`, ...args)
},
debug: (msg: string, ...args: unknown[]) => {
if (process.env.DEBUG === "true") {
// process is missing when the web app runs this code in the browser
if (typeof process !== "undefined" && process.env.DEBUG === "true") {
console.error(`[MCP-DrawIO] [DEBUG] ${msg}`, ...args)
}
},
+70
View File
@@ -0,0 +1,70 @@
/**
* A whole new diagram written by the model, for the create_new_diagram tool
* and the web app's display_diagram tool.
*/
import { normalizeToMxfile, wrapCellsInModel } from "./pages.ts"
import { readAttributes } from "./xml-attributes.ts"
import { validateAndFixXml } from "./xml-validation.ts"
export type NewDiagram =
| { ok: true; xml: string; fixes: string[] }
| { ok: false; error: string }
/**
* Bare cells get the root cells "0" and "1". A shape or edge with one of
* these ids would be renamed as a duplicate, breaking its edges. Its id may
* be on a <UserObject> or <object> wrapper. Returns the error for the model,
* or null.
*/
export function reservedIdError(input: string): string | null {
if (/<(mxGraphModel|mxfile)\b/.test(input)) return null
// Each opening tag with its attributes; quoted values are read as a
// whole, so text such as label="id='1'" is not an attribute
const tags = input.matchAll(
/<(mxCell|UserObject|object)\b((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*\/?>/g,
)
for (const [, tag, attrText] of tags) {
const attrs = new Map(
readAttributes(attrText).map((a) => [a.name, a.value]),
)
const id = attrs.get("id")
if (id !== "0" && id !== "1") continue
// A wrapper's id is its cell's; an mxCell counts as a shape or edge
if (
tag !== "mxCell" ||
attrs.get("vertex") === "1" ||
attrs.get("edge") === "1"
) {
return 'Cell ids "0" and "1" are the root cells, which are added automatically. Give shapes and edges ids starting at "2".'
}
}
return null
}
/**
* Bare cells get the wrapper and root cells first, since the strict parser
* rejects several top-level elements. Then the XML is validated and
* auto-fixed while it is still a bare model, where duplicate ids are
* renamed, and finally turned into an <mxfile>.
*/
export function prepareNewDiagram(
input: string,
page: { pageId?: string; pageName?: string } = {},
): NewDiagram {
const reserved = reservedIdError(input)
if (reserved) return { ok: false, error: reserved }
let xml = wrapCellsInModel(input)
const { valid, error, fixed, fixes } = validateAndFixXml(xml)
if (fixed) xml = fixed
if (!valid) {
return { ok: false, error: `XML validation failed - ${error}` }
}
const normalized = normalizeToMxfile(xml, page)
if (!normalized) {
return {
ok: false,
error: "XML must be the mxCell elements of one page, a <mxGraphModel>, or an <mxfile> with one or more <diagram> children.",
}
}
return { ok: true, xml: normalized, fixes }
}
+67 -9
View File
@@ -17,7 +17,8 @@
* - how to add/rename/delete pages without re-parsing ad-hoc.
*/
import { DOMParser } from "linkedom"
import { readAttributes } from "./xml-attributes.ts"
import { getXmlSyntaxError } from "./xml-syntax.ts"
export interface PageInfo {
id: string
@@ -52,6 +53,15 @@ export function generatePageId(): string {
return `${a}-${b}`
}
/**
* Any cell besides the root cells "0" and "1", or a page in draw.io's
* compressed format (text instead of a model), which is not checked further
*/
export const hasCells = (xml: string) =>
/<(mxCell\b[^>]*\bid\s*=\s*["'](?![01]["'])|UserObject\b|object\b)|<diagram\b[^>]*>\s*[^\s<]/.test(
xml,
)
/** Cheap regex check — does the XML start with an <mxfile> root? */
export function isMxFile(xml: string): boolean {
return /^\s*(<\?xml[^>]*\?>\s*)?<mxfile[\s>]/i.test(xml)
@@ -80,6 +90,53 @@ function stripXmlDeclaration(xml: string): string {
return xml.replace(/^\s*<\?xml[^>]*\?>\s*/i, "")
}
const ROOT_CELLS = '<mxCell id="0"/><mxCell id="1" parent="0"/>'
/** A one-page document with only the root cells */
export const BLANK_MXFILE = `<mxfile><diagram name="Page-1" id="page-1"><mxGraphModel><root>${ROOT_CELLS}</root></mxGraphModel></diagram></mxfile>`
/**
* Turn a list of bare cells (optionally inside <root>) into a one-page
* <mxGraphModel>, adding the "0" and "1" root cells. The model then only
* writes its own cells, as in the web app (wrapWithMxFile in lib/utils.ts).
* Root cells the model wrote anyway are replaced, and comments or text
* before the first cell and trailing closing tags some providers append
* are dropped. <mxfile>, <mxGraphModel> and anything else are returned
* unchanged.
*/
export function wrapCellsInModel(xml: string): string {
let content = stripXmlDeclaration(xml.trim())
const start = content.search(/<(mxCell|UserObject|object|root)[\s/>]/)
if (start === -1) return xml
// Only comments and plain text may come before the first cell
if (!/^(?:<!--[\s\S]*?-->|[^<])*$/.test(content.slice(0, start))) {
return xml
}
content = content
.slice(start)
.replace(/<\/?root>/g, "")
.trim()
// End of the last cell, counting wrapped cells (</UserObject>, </object>)
let end = -1
for (const close of ["/>", "</mxCell>", "</UserObject>", "</object>"]) {
const at = content.lastIndexOf(close)
if (at !== -1) end = Math.max(end, at + close.length)
}
if (end !== -1 && /^(\s*<\/[^>]+>)*\s*$/.test(content.slice(end))) {
content = content.slice(0, end)
}
// The root cells come with the wrapper (a label holding id='1' is not
// an id)
content = content
.replace(/<mxCell\b[^>]*?(?:\/>|>\s*<\/mxCell>)/g, (cell) => {
const id = readAttributes(cell).find((a) => a.name === "id")?.value
return id === "0" || id === "1" ? "" : cell
})
.trim()
return `<mxGraphModel><root>${ROOT_CELLS}${content}</root></mxGraphModel>`
}
/**
* Wrap a bare <mxGraphModel> XML string in <mxfile><diagram>...</diagram></mxfile>.
* If the input is already an mxfile, returns it unchanged.
@@ -110,8 +167,8 @@ export function normalizeToMxfile(
*/
export function parseMxfile(xml: string): Document | null {
try {
if (getXmlSyntaxError(xml)) return null
const doc = new DOMParser().parseFromString(xml, "text/xml")
if (doc.querySelector("parsererror")) return null
if (doc.documentElement?.tagName !== "mxfile") return null
return doc as unknown as Document
} catch {
@@ -254,16 +311,16 @@ export function addPageToDoc(
}
inner = trimmed
} else {
inner = `<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>`
inner = `<mxGraphModel><root>${ROOT_CELLS}</root></mxGraphModel>`
}
const snippet = `<wrapper><diagram id="${escapeAttr(id)}" name="${escapeAttr(name)}">${inner}</diagram></wrapper>`
const tempDoc = new DOMParser().parseFromString(snippet, "text/xml")
if (tempDoc.querySelector("parsererror")) {
if (getXmlSyntaxError(snippet)) {
throw new Error(
"Failed to parse new page xml — make sure it is a valid <mxGraphModel>",
)
}
const tempDoc = new DOMParser().parseFromString(snippet, "text/xml")
const newDiagram = tempDoc.querySelector("diagram")
if (!newDiagram) {
throw new Error("Failed to construct <diagram> element for new page")
@@ -301,14 +358,15 @@ export function deletePageFromDoc(
doc: Document,
selector: PageSelector,
): { ok: boolean; reason?: string; deletedId?: string; deletedIndex?: number } {
const pages = listPagesFromDoc(doc)
if (pages.length <= 1) {
return { ok: false, reason: "Cannot delete the only remaining page" }
}
// Match first, so a wrong selector reports "not found" even on a
// one-page document
const found = findPageElement(doc, selector)
if (!found) {
return { ok: false, reason: "Page not found" }
}
if (listPagesFromDoc(doc).length <= 1) {
return { ok: false, reason: "Cannot delete the only remaining page" }
}
const id = found.element.getAttribute("id") || ""
const index = found.index
found.element.parentNode?.removeChild(found.element)
+161
View File
@@ -0,0 +1,161 @@
/**
* Auto-save of each session's latest diagram as a plain .drawio file, so a
* diagram survives the MCP process (hosts start a new one when a
* conversation is resumed). Like the web app's IndexedDB sessions
* (lib/session-storage.ts): saved 1 second after the last change, at most
* 50 kept. History is not saved.
*/
import {
existsSync,
mkdirSync,
readdirSync,
readFileSync,
renameSync,
statSync,
unlinkSync,
writeFileSync,
} from "node:fs"
import { homedir } from "node:os"
import { join } from "node:path"
import { contentFingerprint } from "./edit-gate.ts"
import { log } from "./logger.ts"
import { BLANK_MXFILE, hasCells } from "./pages.ts"
// The blank page the browser shows before any drawing (page names count:
// empty pages the user named or added are kept)
const isBlank = (xml: string) =>
!hasCells(xml) &&
contentFingerprint(xml) === contentFingerprint(BLANK_MXFILE)
const DELAY_MS = 1000
const MAX_FILES = 50
/** Expand a leading ~ to the home directory (shells do this, MCP hosts don't). */
export function expandHome(p: string): string {
if (p === "~") return homedir()
if (p.startsWith("~/") || p.startsWith("~\\")) return homedir() + p.slice(1)
return p
}
/** DRAWIO_DATA_DIR, default ~/.next-ai-drawio; "off" disables saving. */
export function defaultDataDir(): string | null {
const dir = process.env.DRAWIO_DATA_DIR
if (dir === "off") return null
return dir ? expandHome(dir) : join(homedir(), ".next-ai-drawio")
}
/** The file surely does not exist (not merely out of reach) */
function isGone(path: string): boolean {
try {
statSync(path)
return false
} catch (error) {
return (error as NodeJS.ErrnoException).code === "ENOENT"
}
}
export class Autosaver {
private pending = new Map<
string,
{ xml: string; timer: ReturnType<typeof setTimeout> }
>()
constructor(
private dir: string | null,
private delayMs = DELAY_MS,
private maxFiles = MAX_FILES,
) {}
/** Path of a session's file, or null when saving is off. */
pathFor(sessionId: string): string | null {
return this.dir ? join(this.dir, `${sessionId}.drawio`) : null
}
// Saved files that could not be read back: never written over, since
// the session then shows something else than what they hold. Cleared
// once the file is read, or is surely gone (a folder without permission
// also makes a file look missing).
private unreadable = new Set<string>()
/** The session's saved diagram, or null. */
load(sessionId: string): string | null {
const path = this.pathFor(sessionId)
if (!path) return null
try {
const xml = readFileSync(path, "utf-8")
this.unreadable.delete(path)
return xml
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
this.unreadable.delete(path)
return null
}
log.warn(`Could not read the saved diagram ${path}: ${error}`)
this.unreadable.add(path)
return null
}
}
schedule(sessionId: string, xml: string): void {
if (!this.dir) return
const previous = this.pending.get(sessionId)
if (previous) clearTimeout(previous.timer)
const timer = setTimeout(() => this.write(sessionId), this.delayMs)
timer.unref?.()
this.pending.set(sessionId, { xml, timer })
}
/** Write every pending save now (on shutdown). */
flush(): void {
for (const [sessionId, { timer }] of this.pending) {
clearTimeout(timer)
this.write(sessionId)
}
}
private write(sessionId: string): void {
const entry = this.pending.get(sessionId)
this.pending.delete(sessionId)
const path = this.pathFor(sessionId)
if (!entry || !this.dir || !path) return
if (this.unreadable.has(path)) {
// Deleted meanwhile: nothing left to protect
if (isGone(path)) {
this.unreadable.delete(path)
} else {
log.warn(
`Not saving ${path}: it could not be read, so it may hold work this session does not show`,
)
return
}
}
try {
const isNew = !existsSync(path)
// A blank page the browser shows before any drawing: nothing to keep
if (isNew && isBlank(entry.xml)) return
mkdirSync(this.dir, { recursive: true })
// Write to a temporary file first so a crash never leaves half a file
writeFileSync(`${path}.tmp`, entry.xml, "utf-8")
renameSync(`${path}.tmp`, path)
if (isNew) this.removeOldest()
} catch (error) {
log.warn(`Auto-save failed for ${path}: ${error}`)
}
}
private removeOldest(): void {
if (!this.dir) return
const dir = this.dir
// Only our own session files (mcp-<time in base 36>-<random>, made
// by start_session): DRAWIO_DATA_DIR may be a folder that also holds
// the user's diagrams
const files = readdirSync(dir)
.filter((f) => /^mcp-[0-9a-z]{8}-[0-9a-z]{1,6}\.drawio$/.test(f))
.map((f) => ({ f, mtime: statSync(join(dir, f)).mtimeMs }))
.sort((a, b) => b.mtime - a.mtime)
for (const { f } of files.slice(this.maxFiles)) {
unlinkSync(join(dir, f))
}
}
}
@@ -0,0 +1,94 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Next AI Draw.io</title>
<style>
{{CSS}}
</style>
</head>
<body>
<div id="container">
<div id="header">
<div class="brand">
<div class="logo">
<svg viewBox="0 0 1536 1536" fill="#ffffff">
<g transform="translate(0,1536) scale(0.1,-0.1)">
<path d="M2765 14404 c-100 -29 -181 -58 -225 -82 -227 -125 -359 -296 -431 -560 -19 -70 -19 -108 -19 -1175 0 -1068 1 -1104 20 -1172 58 -206 159 -356 319 -474 71 -53 199 -121 226 -121 9 0 26 -5 38 -12 12 -6 62 -19 112 -29 85 -17 207 -18 2219 -19 1172 0 2133 -3 2138 -8 4 -4 7 -246 6 -538 l-3 -529 -2330 -5 c-2506 -6 -2373 -3 -2470 -54 -61 -31 -150 -113 -194 -178 -87 -128 -82 -77 -90 -1025 l-6 -838 -360 -6 c-292 -4 -368 -8 -405 -21 -194 -68 -303 -177 -373 -372 l-22 -61 1 -2887 c1 -2716 2 -2890 18 -2935 56 -153 161 -276 286 -334 126 -59 0 -54 1400 -54 1394 0 1290 -4 1410 53 95 45 198 148 242 241 62 133 58 -93 58 3026 0 2992 1 2883 -40 2990 -59 156 -183 272 -360 337 -25 9 -146 14 -440 18 l-405 5 0 540 0 540 2020 3 c1111 1 2030 0 2043 -3 l22 -5 -2 -538 -3 -537 -380 -6 c-312 -4 -388 -8 -426 -21 -195 -68 -326 -204 -383 -399 -15 -51 -16 -295 -16 -2921 0 -2778 1 -2867 19 -2920 36 -104 72 -167 134 -230 75 -78 115 -105 222 -151 l50 -22 1219 -3 c672 -1 1255 1 1300 6 109 12 217 63 298 140 73 69 107 118 144 208 l29 69 3 2880 c2 2687 1 2884 -15 2945 -48 183 -188 332 -373 398 -37 13 -114 17 -430 21 l-385 6 -3 534 c-2 421 0 536 10 543 7 4 925 8 2039 8 1718 0 2028 -2 2038 -14 8 -10 11 -154 11 -531 -1 -284 -4 -523 -7 -531 -4 -12 -69 -14 -392 -14 -354 0 -391 -2 -448 -20 -168 -52 -282 -148 -353 -295 -22 -45 -40 -91 -40 -103 0 -11 -5 -33 -10 -47 -7 -18 -10 -988 -10 -2875 0 -2393 2 -2858 14 -2902 43 -167 148 -298 293 -369 57 -27 107 -44 151 -50 88 -11 2429 -11 2508 0 210 31 416 238 445 450 6 39 8 1245 7 2926 -3 2713 -4 2862 -21 2900 -41 93 -74 150 -110 191 -46 52 -149 134 -169 134 -8 0 -19 5 -24 10 -6 6 -42 19 -80 30 -63 18 -100 20 -415 20 -307 0 -348 2 -353 16 -3 9 -6 390 -6 848 0 797 -1 834 -19 886 -31 87 -50 118 -111 183 -66 70 -141 119 -221 144 -50 16 -228 18 -2389 23 l-2335 5 0 535 0 535 2165 5 c1191 3 2170 8 2176 12 6 4 35 12 65 17 201 35 435 198 539 376 55 93 82 153 110 245 19 63 20 94 20 1167 0 1047 -1 1106 -19 1180 -70 290 -275 523 -539 613 -160 54 232 50 -5028 49 -4182 0 -4856 -2 -4899 -15z"/>
</g>
</svg>
</div>
<span class="title">Next AI Draw.io</span>
{{SESSION_BADGE}}
</div>
<div class="right">
<button id="history-btn" title="History" {{DISABLED}}>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline>
</svg>
History
</button>
<button id="save-btn" {{DISABLED}}>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
Download
</button>
</div>
</div>
<iframe id="drawio" src="{{DRAWIO_URL}}/?embed=1&proto=json&spin=1&libraries=1&noSaveBtn=1&noExitBtn=1&saveAndExit=0&themes=1&dark=auto" title="draw.io editor"></iframe>
</div>
<div id="notice" role="status"></div>
<div id="history-modal">
<div class="modal-content">
<div class="modal-header"><h2>History</h2></div>
<div class="modal-body">
<div id="history-grid" class="history-grid"></div>
<div id="history-empty" class="empty" style="display:none;">No history yet</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" id="cancel-btn">Cancel</button>
<button class="btn btn-primary" id="restore-btn" disabled>Restore</button>
</div>
</div>
</div>
<div id="save-modal">
<div class="modal-content">
<div class="modal-header"><h2>Download Diagram</h2></div>
<div class="modal-body">
<div class="form-group">
<label>Format</label>
<select id="save-format">
<option value="drawio">Draw.io (.drawio)</option>
<option value="png">PNG Image (.png)</option>
<option value="svg">SVG Vector (.svg)</option>
<option value="xmlsvg">Editable SVG (.drawio.svg)</option>
</select>
</div>
<div class="form-group">
<label>Filename</label>
<div class="filename-group">
<input type="text" id="save-filename" value="diagram" placeholder="Enter filename" autocomplete="off">
<span class="ext" id="save-ext">.drawio</span>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" id="save-cancel-btn">Cancel</button>
<button class="btn btn-primary" id="save-confirm-btn">Save</button>
</div>
</div>
</div>
<script>
const sessionId = {{SESSION_JSON}};
const DRAWIO_ORIGIN = {{ORIGIN_JSON}};
</script>
<script>
{{SCRIPT}}
</script>
</body>
</html>
+190
View File
@@ -0,0 +1,190 @@
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; overflow: hidden; }
#container { width: 100%; height: 100%; display: flex; flex-direction: column; }
#header {
padding: 0 20px; height: 52px;
background: linear-gradient(to bottom, #ffffff, #fafbfc);
border-bottom: 1px solid #e8ecf0;
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
display: flex; justify-content: space-between; align-items: center;
box-shadow: 0 1px 3px rgba(0,0,0,0.04);
position: relative; z-index: 10;
}
#header .brand {
display: flex; align-items: center; gap: 10px;
}
#header .logo {
width: 28px; height: 28px; border-radius: 6px;
background: #18181b;
display: flex; align-items: center; justify-content: center;
overflow: hidden;
}
#header .logo img { width: 20px; height: 20px; filter: brightness(0) invert(1); }
#header .title {
font-size: 15px; font-weight: 600; color: #1a1a2e;
letter-spacing: -0.3px;
}
#header .session {
font-size: 11px; color: #8b95a5; font-weight: 400;
background: #f1f3f9; padding: 3px 8px; border-radius: 4px;
margin-left: 12px; font-family: 'SF Mono', Monaco, monospace;
}
#header .right { display: flex; align-items: center; gap: 12px; }
#save-btn {
display: flex; align-items: center; gap: 6px;
padding: 7px 14px; border-radius: 8px; font-size: 13px;
background: linear-gradient(to bottom, #18181b, #27272a);
color: white; border: none; cursor: pointer;
font-weight: 500; font-family: inherit;
box-shadow: 0 1px 2px rgba(0,0,0,0.1), inset 0 1px 0 rgba(255,255,255,0.1);
transition: all 0.15s ease;
}
#save-btn svg { width: 14px; height: 14px; }
#save-btn:hover {
background: linear-gradient(to bottom, #27272a, #3f3f46);
transform: translateY(-1px);
box-shadow: 0 3px 8px rgba(0,0,0,0.15), inset 0 1px 0 rgba(255,255,255,0.1);
}
#save-btn:active { transform: translateY(0); }
#save-btn:disabled, #history-btn:disabled {
background: #e5e7eb; color: #9ca3af;
cursor: not-allowed; transform: none; box-shadow: none;
}
#history-btn {
display: flex; align-items: center; gap: 6px;
padding: 7px 14px; border-radius: 8px; font-size: 13px;
background: #f4f4f5; color: #3f3f46; border: 1px solid #e4e4e7;
cursor: pointer; font-weight: 500; font-family: inherit;
transition: all 0.15s ease;
}
#history-btn svg { width: 14px; height: 14px; }
#history-btn:hover {
background: #e4e4e7; border-color: #d4d4d8;
}
#drawio { flex: 1; border: none; }
#history-modal, #save-modal {
display: none; position: fixed; inset: 0;
background: rgba(0,0,0,0.4); backdrop-filter: blur(4px);
z-index: 2000; align-items: center; justify-content: center;
}
#history-modal.open, #save-modal.open { display: flex; }
.modal-content {
background: white; border-radius: 16px;
width: 90%; max-width: 480px; max-height: 70vh;
display: flex; flex-direction: column;
box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
animation: modalIn 0.2s ease-out;
}
@keyframes modalIn {
from { opacity: 0; transform: scale(0.95) translateY(-10px); }
to { opacity: 1; transform: scale(1) translateY(0); }
}
.modal-header {
padding: 20px 24px 16px; border-bottom: 1px solid #f1f3f5;
}
.modal-header h2 {
font-size: 17px; font-weight: 600; margin: 0; color: #18181b;
letter-spacing: -0.3px;
}
.modal-body { flex: 1; overflow-y: auto; padding: 20px 24px; }
.modal-footer {
padding: 16px 24px; border-top: 1px solid #f1f3f5;
display: flex; gap: 10px; justify-content: flex-end;
}
.history-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
.history-item {
border: 2px solid #e4e4e7; border-radius: 10px; padding: 10px;
cursor: pointer; text-align: center; transition: all 0.15s ease;
background: #fafafa;
}
.history-item:hover { border-color: #a1a1aa; background: white; }
.history-item.selected {
border-color: #18181b; background: white;
box-shadow: 0 0 0 3px rgba(24,24,27,0.1);
}
.history-item .thumb {
aspect-ratio: 4/3; background: #f4f4f5; border-radius: 6px;
display: flex; align-items: center; justify-content: center;
margin-bottom: 6px; overflow: hidden;
}
.history-item .thumb img { max-width: 100%; max-height: 100%; object-fit: contain; }
.history-item .label { font-size: 11px; color: #71717a; font-weight: 500; }
.btn {
padding: 9px 18px; border-radius: 8px; font-size: 13px;
cursor: pointer; border: none; font-weight: 500;
font-family: inherit; transition: all 0.15s ease;
}
.btn-primary {
background: linear-gradient(to bottom, #18181b, #27272a);
color: white;
box-shadow: 0 1px 2px rgba(0,0,0,0.1), inset 0 1px 0 rgba(255,255,255,0.1);
}
.btn-primary:hover {
background: linear-gradient(to bottom, #27272a, #3f3f46);
transform: translateY(-1px);
}
.btn-primary:disabled {
background: #e4e4e7; color: #a1a1aa;
cursor: not-allowed; transform: none; box-shadow: none;
}
.btn-secondary {
background: #f4f4f5; color: #3f3f46; border: 1px solid #e4e4e7;
}
.btn-secondary:hover { background: #e4e4e7; }
.empty { text-align: center; padding: 40px; color: #71717a; font-size: 14px; }
.form-group { margin-bottom: 18px; }
.form-group label {
display: block; font-size: 13px; font-weight: 500;
margin-bottom: 8px; color: #3f3f46;
}
.form-group select, .form-group input {
width: 100%; padding: 10px 14px; border: 1px solid #e4e4e7;
border-radius: 8px; font-size: 14px; outline: none;
font-family: inherit; background: white;
transition: all 0.15s ease;
}
.form-group select:focus, .form-group input:focus {
border-color: #18181b;
box-shadow: 0 0 0 3px rgba(24,24,27,0.08);
}
.filename-group { display: flex; }
.filename-group input { border-radius: 8px 0 0 8px; border-right: none; }
#notice {
display: none; position: fixed; left: 50%; bottom: 24px;
transform: translateX(-50%); z-index: 3000; max-width: 480px;
padding: 10px 16px; border-radius: 8px; font-size: 13px;
background: #18181b; color: white;
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
#notice.open { display: block; }
.filename-group .ext {
padding: 10px 14px; background: #f4f4f5; border: 1px solid #e4e4e7;
border-radius: 0 8px 8px 0; font-size: 13px; color: #71717a;
font-family: 'SF Mono', Monaco, monospace;
}
/* Dark mode follows the system, like draw.io with dark=auto */
@media (prefers-color-scheme: dark) {
#header { background: #1c1c20; border-bottom-color: #2e2e34; box-shadow: none; }
#header .title { color: #f4f4f5; }
#header .session { background: #2a2a30; color: #a1a1aa; }
#history-btn, .btn-secondary { background: #2a2a30; color: #e4e4e7; border-color: #3f3f46; }
#history-btn:hover, .btn-secondary:hover { background: #3f3f46; border-color: #52525b; }
#save-btn, .btn-primary { background: #f4f4f5; color: #18181b; }
#save-btn:hover, .btn-primary:hover { background: #e4e4e7; }
#save-btn:disabled, #history-btn:disabled, .btn-primary:disabled { background: #2a2a30; color: #71717a; }
.modal-content { background: #1c1c20; color: #e4e4e7; }
.modal-header, .modal-footer { border-color: #2e2e34; }
.modal-header h2 { color: #f4f4f5; }
.history-item { background: #27272a; border-color: #3f3f46; }
.history-item:hover { background: #2e2e34; border-color: #71717a; }
.history-item.selected { background: #2e2e34; border-color: #f4f4f5; box-shadow: 0 0 0 3px rgba(244,244,245,0.15); }
.history-item .label, .empty { color: #a1a1aa; }
.form-group label { color: #d4d4d8; }
.form-group select, .form-group input { background: #27272a; color: #f4f4f5; border-color: #3f3f46; }
.form-group select:focus, .form-group input:focus { border-color: #a1a1aa; box-shadow: 0 0 0 3px rgba(244,244,245,0.1); }
.filename-group .ext { background: #2a2a30; border-color: #3f3f46; color: #a1a1aa; }
#notice { background: #f4f4f5; color: #18181b; }
}
+527
View File
@@ -0,0 +1,527 @@
const iframe = document.getElementById('drawio');
let currentVersion = 0, isReady = false, pendingXml = null, lastXml = null;
// The server state this tab is in step with (see stateId in http-server.ts);
// null until the first poll
let stateId = null;
// The newest diagram on the canvas, saved to the server or not: lastXml is
// the last one the server has
let latestXml = null;
let pushFailing = false; // the last push could not reach the server
const pushesInFlight = []; // XML of pushes not answered yet
// After recovery replaced the canvas, until draw.io reports the load: an
// autosave still on its way belongs to the canvas being replaced
let awaitingLoad = false;
let pollSeq = 0, lastHandledPoll = 0; // polls overlap; older answers are dropped
let pendingSvgExport = null;
let pendingSvgBase = 0; // version the pending autosave was based on
let pendingSvgStateId = null; // and the state it belonged to
// The latest thumbnail export of a loaded server write: its number (echoed
// by draw.io), the state and version it showed, and the XML loaded
let thumbExportSeq = 0, thumbExport = null;
let pendingMcpExport = null; // 'png', 'svg' or 'xmlsvg' when MCP requested export
let mcpExportSeq = 0; // number of the latest MCP export
let mcpExportId = null; // the server's id for it, sent back with the result
let projectionExportActive = false; // page-targeted export: showing a transient single-page projection
let forceReload = false; // reload the server state on the next poll even if the version is unchanged
let noticeTimer = null;
window.addEventListener('message', (e) => {
if (e.origin !== DRAWIO_ORIGIN) return;
try {
const msg = JSON.parse(e.data);
if (msg.event === 'init') {
isReady = true;
if (pendingXml) { loadDiagram(pendingXml); pendingXml = null; }
} else if (msg.event === 'load') {
awaitingLoad = false;
} else if ((msg.event === 'save' || msg.event === 'autosave') && msg.xml) {
// Ignore autosave while a single-page projection is on screen
// for a page-targeted export — otherwise we'd push the
// transient projection back as the canonical session state.
if (projectionExportActive) return;
// An edit of the canvas that recovery is replacing: kept in
// History, never over the recovered diagram
if (awaitingLoad) { pushState(msg.xml, '', currentVersion, 'recover'); return; }
// Also an edit undone back to what the server has
latestXml = msg.xml;
if (msg.xml === lastXml) return;
// Request SVG export, then push state with SVG. Remember the
// version and state this edit is based on, so the server can
// reject it if the AI wrote a newer version that is not loaded
// yet, or if it lost that state.
pendingSvgExport = msg.xml;
pendingSvgBase = currentVersion;
pendingSvgStateId = stateId;
iframe.contentWindow.postMessage(JSON.stringify({ action: 'export', format: 'svg' }), '*');
// Fallback if export doesn't respond
setTimeout(() => { if (pendingSvgExport === msg.xml) { pushState(msg.xml, '', pendingSvgBase, 'edit', pendingSvgStateId); pendingSvgExport = null; } }, 2000);
} else if (msg.event === 'export' && msg.format === 'xml') {
// Sync export requested by the server (get_diagram).
// draw.io returns the XML in msg.xml, with no msg.data. A late
// reply to an earlier request was taken at another version.
if (pendingSyncExport && msg.xml && msg.message?.syncExport === syncExportSeq) {
pendingSyncExport = false;
// Push with the version the export was taken at: a
// newer AI write may have loaded meanwhile, and this
// older XML must not overwrite it.
pushState(msg.xml, '', pendingSyncBase, 'sync', pendingSyncStateId);
}
} else if (msg.event === 'export' && msg.data) {
// Handle MCP server export request (png/svg). fireExport tags
// the request with mcpExport and draw.io echoes the request
// back in msg.message, which tells it apart from autosave and
// preview SVG exports.
if (msg.message && msg.message.mcpExport) {
// A late reply to an export that already timed out
if (msg.message.mcpExport !== mcpExportSeq) return;
const d = msg.data;
const isPng = pendingMcpExport === 'png' && d.startsWith('data:image/png');
const isSvg = (pendingMcpExport === 'svg' || pendingMcpExport === 'xmlsvg') && (d.startsWith('data:image/svg') || d.startsWith('<svg'));
if (isPng || isSvg) {
// Keep pendingMcpExport set until the server has the
// result: a poll answered before that still sees the
// request and would start the same export again.
const seq = msg.message.mcpExport;
fetch('/api/state', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, exportData: d, exportId: mcpExportId })
}).catch(() => {}).finally(() => {
// The timeout already ended this export
if (seq !== mcpExportSeq) return;
pendingMcpExport = null;
// Page-targeted export: restore the user's real
// multi-page document now that we have the image.
restoreFromProjection();
});
}
return;
}
// Handle file download export (PNG/SVG only, drawio uses
// lastXml directly). Tagged with dlExport like mcpExport,
// so an autosave SVG export can never be saved instead.
if (msg.message && msg.message.dlExport) {
if (!pendingDownload) return;
const dl = pendingDownload;
pendingDownload = null;
let dataUrl = msg.data;
if (!dataUrl.startsWith('data:')) {
const mime = dl.format === 'png' ? 'image/png' : 'image/svg+xml';
dataUrl = 'data:' + mime + ';base64,' + btoa(unescape(encodeURIComponent(msg.data)));
}
const a = document.createElement('a');
a.href = dataUrl; a.download = dl.filename;
document.body.appendChild(a); a.click(); document.body.removeChild(a);
saveModal.classList.remove('open');
saveConfirmBtn.disabled = false;
saveConfirmBtn.textContent = 'Save';
return;
}
// Handle SVG export
let svg = msg.data;
if (!svg.startsWith('data:')) svg = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
if (msg.message && msg.message.thumbExport) {
// Only for the latest load, and only if the canvas still
// shows it: the export pictures the canvas as it is now
const t = thumbExport;
if (!t || msg.message.thumbExport !== t.n || latestXml !== t.xml) return;
thumbExport = null;
fetch('/api/history-svg', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, svg, stateId: t.stateId, version: t.version })
}).catch(() => {});
} else if (pendingSvgExport) {
const xml = pendingSvgExport;
pendingSvgExport = null;
pushState(xml, svg, pendingSvgBase, 'edit', pendingSvgStateId);
}
}
} catch {}
});
function loadDiagram(xml, capturePreview = false) {
if (!isReady) { pendingXml = xml; return; }
lastXml = xml;
latestXml = xml;
iframe.contentWindow.postMessage(JSON.stringify({ action: 'load', xml, autosave: 1 }), '*');
if (capturePreview) {
// A server write: currentVersion is its version
const t = { n: ++thumbExportSeq, stateId, version: currentVersion, xml };
thumbExport = t;
setTimeout(() => {
if (thumbExport !== t) return; // a newer load takes its own
iframe.contentWindow.postMessage(JSON.stringify({ action: 'export', format: 'svg', thumbExport: t.n }), '*');
}, 500);
}
}
// Restore the user's real document after a page-targeted projection
// export by reloading the server state. The server also has any
// autosave that was still in flight when the projection started,
// which a copy taken at that moment would miss. A flag is used
// because a push finishing meanwhile may update currentVersion.
// projectionExportActive stays set until the poll loads the document:
// an edit on the projection before that must not be pushed.
function restoreFromProjection() {
if (!projectionExportActive) return;
forceReload = true;
poll();
}
function showNotice(text) {
const el = document.getElementById('notice');
el.textContent = text;
el.classList.add('open');
clearTimeout(noticeTimer);
noticeTimer = setTimeout(() => el.classList.remove('open'), 8000);
}
// source is 'sync' for replies to a server sync request, 'recover' for the
// tab's copy after the server recovered the session, else 'edit'. sid is the
// server state the push is based on.
async function pushState(xml, svg = '', baseVersion = currentVersion, source = 'edit', sid = stateId) {
if (!sessionId) return;
pushesInFlight.push(xml);
try {
const r = await fetch('/api/state', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, xml, svg, baseVersion, source, stateId: sid })
});
pushFailing = false;
if (r.ok) {
const d = await r.json();
// An answer about a state this tab has left since, or one that
// comes after a newer version was loaded or saved
if (sid !== stateId || d.version < currentVersion) return;
currentVersion = d.version;
lastXml = xml;
// The canvas changed while this edit was on its way, to
// something no pending autosave will send (an undo back to the
// previous version): send it now. A sync reply is draw.io's
// export of the canvas, in another format than its autosave.
if (latestXml && latestXml !== xml && pendingSvgExport !== latestXml && source === 'edit') {
pushState(latestXml);
}
}
// Over the server's size limit: the image is most of it, so try once
// without it
else if (r.status === 413) {
if (svg) pushState(xml, '', baseVersion, source, sid);
else showNotice('This diagram is too large to save to the MCP server (over 10 MB). Use Download to keep it.');
}
// 409: the AI wrote a newer version, or the server lost the state
// this push was based on; the next poll sorts it out
else if (r.status === 409) {
const d = await r.json().catch(() => ({}));
if (d.savedToHistory) {
showNotice(source === 'recover'
? 'The diagram was restored from its saved file. What this tab showed before is in History.'
: 'The AI changed the diagram while you were editing. Your last change was saved in History.');
}
poll();
}
} catch (e) {
console.error('Push failed:', e);
if (!pushFailing) {
pushFailing = true;
showNotice("Can't reach the MCP server. Your changes are only in this tab for now; use Download to keep a copy.");
}
} finally {
pushesInFlight.splice(pushesInFlight.indexOf(xml), 1);
}
}
// The server made a new state for this session: it expired, or the MCP
// process restarted. Decide whose diagram wins.
function recoverState(s) {
stateId = s.stateId;
// The old state's pending work is gone with it
const projectionShown = projectionExportActive;
projectionExportActive = false;
forceReload = false;
pendingMcpExport = null;
pendingSyncExport = false;
const mine = latestXml;
currentVersion = s.version;
if (s.blank || s.xml === lastXml) {
// The server knows nothing, or exactly what this tab last saved:
// the canvas can only be newer, so it wins (edits made while the
// server was down are saved now)
if (projectionShown && mine) {
iframe.contentWindow.postMessage(JSON.stringify({ action: 'load', xml: mine, autosave: 1 }), '*');
expectLoad();
}
if (mine && mine !== s.xml) pushState(mine, '', s.version);
} else {
// The server has a diagram this tab never showed (an AI write it
// missed, a saved file): show that, and keep this tab's copy in
// History unless it is the same
loadDiagram(s.xml, true);
expectLoad();
if (mine && mine !== s.xml) pushState(mine, '', s.version, 'recover');
}
}
// Until draw.io reports the load (its messages come in order), an autosave
// is from the canvas being replaced; in case no report comes, not for long
function expectLoad() {
awaitingLoad = true;
setTimeout(() => { awaitingLoad = false; }, 5000);
}
let pendingSyncExport = false;
let pendingSyncBase = 0; // version the pending sync export was taken at
let pendingSyncStateId = null; // and the state it belonged to
let syncExportSeq = 0; // number of the latest sync export
async function poll() {
if (!sessionId) return;
const seq = ++pollSeq;
try {
const r = await fetch('/api/state?sessionId=' + encodeURIComponent(sessionId));
if (!r.ok) return;
const s = await r.json();
// An older answer than one already handled (the interval, the 409
// handler and the projection restore each poll): it could name a
// state that is gone
if (seq < lastHandledPoll) return;
lastHandledPoll = seq;
if (stateId === null) stateId = s.stateId;
else if (s.stateId && s.stateId !== stateId) recoverState(s);
// Load new diagram from server (before export, so we export latest).
// While a page-targeted projection is on screen, only the restore
// (forceReload) replaces it, so a new version doesn't fight the
// projection; currentVersion stays unadvanced until then, so the
// bump is applied with the real document.
// The tab's own push still on its way is not loaded back: the
// canvas may have moved on since (an undo), and its answer follows
const ownPush = pushesInFlight.includes(s.xml);
if ((forceReload || (s.version > currentVersion && !projectionExportActive && !ownPush)) && s.xml) {
forceReload = false;
projectionExportActive = false;
currentVersion = s.version;
loadDiagram(s.xml, true);
}
// Handle sync request - server needs fresh state. After the load
// above, so draw.io exports what it just loaded; never while a
// one-page projection is on screen, which would be sent as the
// whole document. Reset after a while in case draw.io never
// answers, so later syncs still run.
if (s.syncRequested && !pendingSyncExport && isReady && !projectionExportActive) {
pendingSyncExport = true;
pendingSyncBase = currentVersion;
pendingSyncStateId = stateId;
// draw.io echoes the request in msg.message, so the reply can
// be matched to this request
const seq = ++syncExportSeq;
iframe.contentWindow.postMessage(JSON.stringify({ action: 'export', format: 'xml', syncExport: seq }), '*');
setTimeout(() => { if (seq === syncExportSeq) pendingSyncExport = false; }, 5000);
}
// Handle export request from MCP server (png/svg).
//
// Plain export: capture whatever tab is currently displayed.
//
// Page-targeted export: the server sends a single-page <mxfile>
// projection in s.exportXml. We load it into the iframe, let
// draw.io render it, export, then reload the user's real
// document — all browser-side. The canonical session state is
// never mutated, so there is no server-side restore race and no
// dependence on poll timing. autosave is suppressed while the
// projection is showing (see projectionExportActive guard).
if (s.exportFormat && !pendingMcpExport && isReady) {
pendingMcpExport = s.exportFormat;
const seq = ++mcpExportSeq;
mcpExportId = s.exportId;
const extra = s.exportOptions || {};
const fireExport = () => {
// mcpExport carries this export's number and is echoed
// back in msg.message (see the handler). PNG: width
// caps the size, pageId picks a page; without one
// draw.io would use the first page.
const exportOpts = pendingMcpExport === 'png'
? { action: 'export', format: 'png', scale: 2, currentPage: !extra.pageId, ...extra, mcpExport: seq }
: { action: 'export', format: pendingMcpExport, mcpExport: seq };
iframe.contentWindow.postMessage(JSON.stringify(exportOpts), '*');
};
if (s.exportXml) {
projectionExportActive = true;
// Load the projection without touching lastXml/server state.
iframe.contentWindow.postMessage(JSON.stringify({ action: 'load', xml: s.exportXml, autosave: 0 }), '*');
// Let draw.io render the loaded page before exporting
// (same proven settle delay as the AI-preview path).
setTimeout(fireExport, 600);
} else {
fireExport();
}
// Timeout: reset if draw.io never responds, and restore the
// real document if a projection was left showing. Only for
// this export: a later one may be running by then.
setTimeout(() => {
if (pendingMcpExport && seq === mcpExportSeq) {
pendingMcpExport = null;
restoreFromProjection();
}
}, 10000);
}
} catch {}
}
if (sessionId) { poll(); setInterval(poll, 2000); }
// Save modal
const saveBtn = document.getElementById('save-btn');
const saveModal = document.getElementById('save-modal');
const saveFormat = document.getElementById('save-format');
const saveFilename = document.getElementById('save-filename');
const saveExt = document.getElementById('save-ext');
const saveCancelBtn = document.getElementById('save-cancel-btn');
const saveConfirmBtn = document.getElementById('save-confirm-btn');
let pendingDownload = null;
const extMap = { drawio: '.drawio', png: '.png', svg: '.svg', xmlsvg: '.drawio.svg' };
saveBtn.onclick = () => {
if (!sessionId || !isReady) return;
// Local date as YYYY-MM-DD, like the web app's default name
saveFilename.value = 'diagram-' + new Date().toLocaleDateString('sv-SE');
saveModal.classList.add('open');
saveFilename.focus();
saveFilename.select();
};
saveFilename.onkeydown = (e) => {
if (e.key === 'Enter' && !e.isComposing && !saveConfirmBtn.disabled) saveConfirmBtn.onclick();
};
document.addEventListener('keydown', (e) => {
if (e.key !== 'Escape') return;
if (saveModal.classList.contains('open')) saveCancelBtn.onclick();
if (historyModal.classList.contains('open')) cancelBtn.onclick();
});
saveFormat.onchange = () => {
saveExt.textContent = extMap[saveFormat.value] || '.drawio';
};
saveCancelBtn.onclick = () => { saveModal.classList.remove('open'); };
saveModal.onclick = (e) => { if (e.target === saveModal) saveCancelBtn.onclick(); };
saveConfirmBtn.onclick = () => {
const format = saveFormat.value;
const filename = (saveFilename.value.trim() || 'diagram') + extMap[format];
saveConfirmBtn.disabled = true;
saveConfirmBtn.textContent = 'Exporting...';
if (format === 'drawio') {
// Use the XML directly instead of requesting export (avoids race with SVG exports).
// session.xml is canonically <mxfile> after the multi-page refactor,
// so no wrapper injection is needed. The legacy fallback below
// remains only for documents that somehow slipped past
// normalisation (e.g. an older session loaded from external state).
// The canvas as it is, also edits not saved to the server yet
let xmlData = latestXml || lastXml || '';
if (xmlData && !xmlData.includes('<mxfile')) {
xmlData = '<mxfile host="mcp"><diagram name="Page-1">' + xmlData + '</diagram></mxfile>';
}
const blob = new Blob([xmlData], { type: 'application/xml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = filename;
document.body.appendChild(a); a.click(); document.body.removeChild(a);
URL.revokeObjectURL(url);
saveModal.classList.remove('open');
saveConfirmBtn.disabled = false;
saveConfirmBtn.textContent = 'Save';
} else if (format === 'png') {
pendingDownload = { format: 'png', filename };
iframe.contentWindow.postMessage(JSON.stringify({ action: 'export', format: 'png', scale: 2, currentPage: true, dlExport: true }), '*');
setTimeout(() => { saveConfirmBtn.disabled = false; saveConfirmBtn.textContent = 'Save'; pendingDownload = null; }, 5000);
} else {
// svg, or xmlsvg: an SVG with the diagram embedded, which draw.io can open again
pendingDownload = { format, filename };
iframe.contentWindow.postMessage(JSON.stringify({ action: 'export', format, dlExport: true }), '*');
setTimeout(() => { saveConfirmBtn.disabled = false; saveConfirmBtn.textContent = 'Save'; pendingDownload = null; }, 5000);
}
};
// History UI
const historyBtn = document.getElementById('history-btn');
const historyModal = document.getElementById('history-modal');
const historyGrid = document.getElementById('history-grid');
const historyEmpty = document.getElementById('history-empty');
const restoreBtn = document.getElementById('restore-btn');
const cancelBtn = document.getElementById('cancel-btn');
let historyData = [], selectedId = null;
historyBtn.onclick = async () => {
if (!sessionId) return;
try {
const r = await fetch('/api/history?sessionId=' + encodeURIComponent(sessionId));
if (r.ok) {
const d = await r.json();
historyData = d.entries || [];
renderHistory();
}
} catch {}
historyModal.classList.add('open');
};
cancelBtn.onclick = () => { historyModal.classList.remove('open'); selectedId = null; restoreBtn.disabled = true; };
historyModal.onclick = (e) => { if (e.target === historyModal) cancelBtn.onclick(); };
function renderHistory() {
if (historyData.length === 0) {
historyGrid.style.display = 'none';
historyEmpty.style.display = 'block';
return;
}
historyGrid.style.display = 'grid';
historyEmpty.style.display = 'none';
// Built element by element: a stored image is never read as HTML, and
// only an SVG data URL is shown as one
historyGrid.replaceChildren(...historyData.map((e) => {
const item = document.createElement('div');
item.className = 'history-item';
item.dataset.id = String(e.id);
const thumb = document.createElement('div');
thumb.className = 'thumb';
if (typeof e.svg === 'string' && e.svg.startsWith('data:image/svg+xml;base64,')) {
const img = document.createElement('img');
img.src = e.svg;
thumb.appendChild(img);
} else {
thumb.textContent = '#' + e.index;
}
const label = document.createElement('div');
label.className = 'label';
label.textContent = '#' + e.index;
item.append(thumb, label);
return item;
}));
historyGrid.querySelectorAll('.history-item').forEach(item => {
item.onclick = () => {
const id = parseInt(item.dataset.id);
if (selectedId === id) { selectedId = null; restoreBtn.disabled = true; }
else { selectedId = id; restoreBtn.disabled = false; }
historyGrid.querySelectorAll('.history-item').forEach(el => el.classList.toggle('selected', parseInt(el.dataset.id) === selectedId));
};
});
}
restoreBtn.onclick = async () => {
if (selectedId === null) return;
restoreBtn.disabled = true;
restoreBtn.textContent = 'Restoring...';
try {
const r = await fetch('/api/restore', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, id: selectedId })
});
if (r.ok) { cancelBtn.onclick(); await poll(); }
else { showNotice('Restore failed. Please try again.'); }
} catch { showNotice('Restore failed. Please try again.'); }
restoreBtn.textContent = 'Restore';
};
+73
View File
@@ -0,0 +1,73 @@
/**
* Shape and icon library docs (docs/shape-libraries/*.md), the same files
* the web app's get_shape_library tool reads (app/api/chat/route.ts).
*/
import { readFile } from "node:fs/promises"
import { dirname, join, resolve } from "node:path"
import { fileURLToPath } from "node:url"
export const SHAPE_LIBRARY_GROUPS: Record<string, string[]> = {
Cloud: [
"aws4",
"azure2",
"gcp2",
"alibaba_cloud",
"openstack",
"salesforce",
],
Networking: ["cisco19", "network", "kubernetes", "vvd", "rack"],
Business: ["bpmn", "lean_mapping"],
General: ["flowchart", "basic", "arrows2", "infographic", "sitemap"],
"UI/Mockups": ["android", "material_design"],
Enterprise: ["citrix", "sap", "mscae", "atlassian"],
Engineering: ["fluidpower", "electrical", "pid", "cabinets", "floorplan"],
Icons: ["webicons"],
}
/** The libraries by group, one "- Group: a, b" line each, for tool descriptions */
export const SHAPE_LIBRARY_LIST = Object.entries(SHAPE_LIBRARY_GROUPS)
.map(([group, names]) => `- ${group}: ${names.join(", ")}`)
.join("\n")
const LIBRARIES = new Set(Object.values(SHAPE_LIBRARY_GROUPS).flat())
/**
* The build copies the docs to dist/shape-libraries; running from src (tsx)
* reads them from the repository instead. The web app passes its own folder.
*/
function libraryDirs(dir?: string): string[] {
if (dir) return [dir]
const here = dirname(fileURLToPath(import.meta.url))
return [
join(here, "shape-libraries"),
resolve(here, "../../../docs/shape-libraries"),
]
}
export async function getShapeLibrary(
name: string,
dir?: string,
): Promise<{ ok: true; text: string } | { ok: false; error: string }> {
const library = name.trim().toLowerCase()
if (!LIBRARIES.has(library)) {
return {
ok: false,
error: `Library "${name}" not found. Available: ${Array.from(LIBRARIES).join(", ")}`,
}
}
for (const folder of libraryDirs(dir)) {
try {
return {
ok: true,
text: await readFile(join(folder, `${library}.md`), "utf-8"),
}
} catch {
// Try the next location
}
}
return {
ok: false,
error: `Library "${library}" is missing from this installation.`,
}
}
+27
View File
@@ -0,0 +1,27 @@
/**
* The attributes of one tag as written: name="value" or name='value'
* pairs. A quoted value is read whole, so text inside it such as
* value="Use parent='1'" is never taken for an attribute.
*/
export interface TagAttribute {
name: string
value: string
// The attribute's text in the tag, with the whitespace before it
start: number
end: number
}
export function readAttributes(tag: string): TagAttribute[] {
const attributes: TagAttribute[] = []
for (const m of tag.matchAll(
/\s*([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,
)) {
attributes.push({
name: m[1],
value: m[2] ?? m[3],
start: m.index,
end: m.index + m[0].length,
})
}
return attributes
}
+43
View File
@@ -0,0 +1,43 @@
/**
* XML examples shared by the MCP drawing guide and the web app's system
* prompt and tool descriptions, so both teach the model the same thing.
*/
export const SWIMLANE_EXAMPLE = `<mxCell id="lane1" value="Frontend" style="swimlane;" vertex="1" parent="1">
<mxGeometry x="40" y="40" width="200" height="200" as="geometry"/>
</mxCell>
<mxCell id="step1" value="Step 1" style="rounded=1;" vertex="1" parent="lane1">
<mxGeometry x="20" y="60" width="160" height="40" as="geometry"/>
</mxCell>
<mxCell id="lane2" value="Backend" style="swimlane;" vertex="1" parent="1">
<mxGeometry x="280" y="40" width="200" height="200" as="geometry"/>
</mxCell>
<mxCell id="step2" value="Step 2" style="rounded=1;" vertex="1" parent="lane2">
<mxGeometry x="20" y="60" width="160" height="40" as="geometry"/>
</mxCell>
<mxCell id="edge1" style="edgeStyle=orthogonalEdgeStyle;endArrow=classic;" edge="1" parent="1" source="step1" target="step2">
<mxGeometry relative="1" as="geometry"/>
</mxCell>`
export const TWO_EDGES_EXAMPLE = `<mxCell id="e1" value="A to B" style="edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.3;entryX=0;entryY=0.3;endArrow=classic;" edge="1" parent="1" source="a" target="b">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="e2" value="B to A" style="edgeStyle=orthogonalEdgeStyle;exitX=0;exitY=0.7;entryX=1;entryY=0.7;endArrow=classic;" edge="1" parent="1" source="b" target="a">
<mxGeometry relative="1" as="geometry"/>
</mxCell>`
export const WAYPOINT_EXAMPLE = `<mxCell id="hotfix_to_main" style="edgeStyle=orthogonalEdgeStyle;exitX=0.5;exitY=0;entryX=1;entryY=0.5;endArrow=classic;" edge="1" parent="1" source="hotfix" target="main">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="750" y="80"/>
<mxPoint x="750" y="150"/>
</Array>
</mxGeometry>
</mxCell>`
/** Indent every line, for an indented code block in Markdown */
export const indent = (text: string, prefix = " ") =>
text
.split("\n")
.map((line) => prefix + line)
.join("\n")
+21
View File
@@ -0,0 +1,21 @@
/**
* Strict XML syntax check, used in Node and in the web app's browser code.
* saxes reports syntax errors the way draw.io's DOMParser will, including
* an attribute prefix such as xlink: that was never declared.
*/
import { SaxesParser } from "saxes"
/**
* Returns the first XML syntax error as "line:column: message", or null if
* the XML is well-formed. Surrounding whitespace is ignored because every
* caller trims before the XML reaches the browser.
*/
export function getXmlSyntaxError(xml: string): string | null {
let error: string | null = null
const parser = new SaxesParser({ xmlns: true })
parser.on("error", (err) => {
error ??= err.message
})
parser.write(xml.trim()).close()
return error
}
+325 -213
View File
@@ -3,6 +3,9 @@
* Copied from lib/utils.ts to avoid cross-package imports
*/
import { readAttributes } from "./xml-attributes.ts"
import { getXmlSyntaxError } from "./xml-syntax.ts"
// ============================================================================
// Constants
// ============================================================================
@@ -10,9 +13,6 @@
/** Maximum XML size to process (1MB) - larger XMLs may cause performance issues */
const MAX_XML_SIZE = 1_000_000
/** Maximum iterations for aggressive cell dropping to prevent infinite loops */
const MAX_DROP_ITERATIONS = 10
/** Structural attributes that should not be duplicated in draw.io */
const STRUCTURAL_ATTRS = [
"edge",
@@ -26,6 +26,23 @@ const STRUCTURAL_ATTRS = [
/** Valid XML entity names */
const VALID_ENTITIES = new Set(["lt", "gt", "amp", "quot", "apos"])
/** Element names draw.io understands (case-sensitive) */
const VALID_DRAWIO_TAGS = new Set([
"mxfile",
"diagram",
"mxGraphModel",
"root",
"mxCell",
"mxGeometry",
"mxPoint",
"Array",
"Object",
"mxRectangle",
// Wrappers draw.io writes for cells with links, tooltips or data
"UserObject",
"object",
])
// ============================================================================
// XML Parsing Helpers
// ============================================================================
@@ -91,6 +108,48 @@ function parseXmlTags(xml: string): ParsedTag[] {
return tags
}
/**
* Returns a function telling whether a position lies inside a quoted
* attribute value. Positions must be queried in increasing order.
*/
function createQuoteTracker(str: string): (pos: number) => boolean {
let i = 0
let inQuote = false
let quoteChar = ""
return (pos: number) => {
for (; i < pos && i < str.length; i++) {
const c = str[i]
if (inQuote) {
if (c === quoteChar) inQuote = false
} else if (c === '"' || c === "'") {
// Only quotes that follow "=" open an attribute value
let j = i - 1
while (j >= 0 && /\s/.test(str[j])) j--
if (j >= 0 && str[j] === "=") {
inQuote = true
quoteChar = c
}
}
}
return inQuote
}
}
/** Rewrite every opening tag with fn, leaving text and closing tags as is. */
function replaceInOpeningTags(
xml: string,
fn: (tag: string) => string,
): string {
let out = ""
let last = 0
for (const { tag, isClosing, startIndex, endIndex } of parseXmlTags(xml)) {
if (isClosing) continue
out += xml.slice(last, startIndex) + fn(tag)
last = endIndex + 1
}
return out + xml.slice(last)
}
// ============================================================================
// Validation Helper Functions
// ============================================================================
@@ -98,16 +157,10 @@ function parseXmlTags(xml: string): ParsedTag[] {
/** Check for duplicate structural attributes in a tag */
function checkDuplicateAttributes(xml: string): string | null {
const structuralSet = new Set(STRUCTURAL_ATTRS)
const tagPattern = /<[^>]+>/g
let tagMatch
while ((tagMatch = tagPattern.exec(xml)) !== null) {
const tag = tagMatch[0]
const attrPattern = /\s([a-zA-Z_:][a-zA-Z0-9_:.-]*)\s*=/g
for (const [tag] of xml.matchAll(/<[^>]+>/g)) {
const attributes = new Map<string, number>()
let attrMatch
while ((attrMatch = attrPattern.exec(tag)) !== null) {
const attrName = attrMatch[1]
attributes.set(attrName, (attributes.get(attrName) || 0) + 1)
for (const { name } of readAttributes(tag)) {
attributes.set(name, (attributes.get(name) || 0) + 1)
}
const duplicates = Array.from(attributes.entries())
.filter(([name, count]) => count > 1 && structuralSet.has(name))
@@ -128,8 +181,7 @@ function checkDuplicateAttributes(xml: string): string | null {
* scope the cell-ID uniqueness check per <diagram>, and additionally check
* that the <diagram> ids themselves are unique.
*
* The legacy regex-based check is kept as a fallback for non-mxfile inputs
* and for XML that won't DOM-parse.
* The legacy regex-based check is kept as a fallback for non-mxfile inputs.
*/
function checkDuplicateIds(xml: string): string | null {
// The DOM-aware path only matters for <mxfile> wrappers; for legacy
@@ -142,51 +194,57 @@ function checkDuplicateIds(xml: string): string | null {
if (mightBeMxFile)
try {
const doc = new DOMParser().parseFromString(xml, "text/xml")
if (!doc.querySelector("parsererror")) {
const rootEl = doc.documentElement
if (rootEl && rootEl.tagName === "mxfile") {
const diagrams = doc.querySelectorAll("diagram")
const rootEl = doc.documentElement
if (rootEl && rootEl.tagName === "mxfile") {
const diagrams = doc.querySelectorAll("diagram")
// 1) <diagram> ids must be unique across the file.
const diagramIds = new Map<string, number>()
diagrams.forEach((d) => {
const id = d.getAttribute("id")
if (id)
diagramIds.set(id, (diagramIds.get(id) || 0) + 1)
})
const dupDiagrams = Array.from(diagramIds.entries())
.filter(([, c]) => c > 1)
.map(([id]) => `'${id}'`)
if (dupDiagrams.length > 0) {
return `Invalid XML: Found duplicate <diagram> id(s): ${dupDiagrams.slice(0, 3).join(", ")}. Each page must have a unique id.`
}
// 2) Within each page, mxCell ids must be unique.
for (let i = 0; i < diagrams.length; i++) {
const diagram = diagrams[i]
const pageId =
diagram.getAttribute("id") || `(index ${i})`
const cells = diagram.querySelectorAll("mxCell")
const cellIds = new Map<string, number>()
cells.forEach((c) => {
const id = c.getAttribute("id")
if (id) cellIds.set(id, (cellIds.get(id) || 0) + 1)
})
const dups = Array.from(cellIds.entries())
.filter(([, c]) => c > 1)
.map(([id, count]) => `'${id}' (${count}x)`)
if (dups.length > 0) {
return `Invalid XML: Found duplicate cell ID(s) in page "${pageId}": ${dups.slice(0, 3).join(", ")}. All mxCell ids must be unique within a page.`
}
}
return null
// 1) <diagram> ids must be unique across the file.
const diagramIds = new Map<string, number>()
diagrams.forEach((d) => {
const id = d.getAttribute("id")
if (id) diagramIds.set(id, (diagramIds.get(id) || 0) + 1)
})
const dupDiagrams = Array.from(diagramIds.entries())
.filter(([, c]) => c > 1)
.map(([id]) => `'${id}'`)
if (dupDiagrams.length > 0) {
return `Invalid XML: Found duplicate <diagram> id(s): ${dupDiagrams.slice(0, 3).join(", ")}. Each page must have a unique id.`
}
// 2) Within each page, cell ids must be unique. A cell with
// a link or custom data is a UserObject/object holding the
// id, around an mxCell whose own id does not count.
for (let i = 0; i < diagrams.length; i++) {
const diagram = diagrams[i]
const pageId = diagram.getAttribute("id") || `(index ${i})`
const cells = diagram.querySelectorAll(
"mxCell, UserObject, object",
)
const cellIds = new Map<string, number>()
cells.forEach((c) => {
const wrapped =
c.tagName === "mxCell" &&
/^(UserObject|object)$/.test(
c.parentElement?.tagName ?? "",
)
const id = c.getAttribute("id")
if (id && !wrapped)
cellIds.set(id, (cellIds.get(id) || 0) + 1)
})
const dups = Array.from(cellIds.entries())
.filter(([, c]) => c > 1)
.map(([id, count]) => `'${id}' (${count}x)`)
if (dups.length > 0) {
return `Invalid XML: Found duplicate cell ID(s) in page "${pageId}": ${dups.slice(0, 3).join(", ")}. All mxCell ids must be unique within a page.`
}
}
return null
}
} catch {
// fall through to regex
}
// Legacy regex-based check for bare <mxGraphModel> and parse-error cases.
// Legacy regex-based check for bare <mxGraphModel> inputs.
const idPattern = /\bid\s*=\s*["']([^"']+)["']/gi
const ids = new Map<string, number>()
let idMatch
@@ -297,6 +355,38 @@ function checkNestedMxCells(xml: string): string | null {
return null
}
/** Check for element names draw.io does not know (e.g. a lowercase <mxcell>) */
function checkUnknownElements(xml: string): string | null {
const tags = parseXmlTags(xml.replace(/<!--[\s\S]*?-->/g, ""))
for (const { tagName } of tags) {
if (!VALID_DRAWIO_TAGS.has(tagName)) {
return `Invalid XML: Unknown element <${tagName}>. draw.io only understands ${Array.from(VALID_DRAWIO_TAGS).join(", ")} (names are case-sensitive).`
}
}
return null
}
/**
* Find <mxPoint> elements without an "as" attribute outside <Array
* as="points">. draw.io rejects them with "Could not add object mxPoint".
*/
function findOrphanMxPoints(
xml: string,
): Array<{ start: number; end: number }> {
const arrays: Array<[number, number]> = []
// (?<!\/) skips an empty <Array/>, which has no points inside
for (const m of xml.matchAll(/<Array\b[^>]*(?<!\/)>[\s\S]*?<\/Array>/g)) {
arrays.push([m.index, m.index + m[0].length])
}
const orphans: Array<{ start: number; end: number }> = []
for (const m of xml.matchAll(/<mxPoint\b[^>]*?(?:\/>|>\s*<\/mxPoint>)/g)) {
if (/\sas\s*=/.test(m[0])) continue
if (arrays.some(([s, e]) => m.index > s && m.index < e)) continue
orphans.push({ start: m.index, end: m.index + m[0].length })
}
return orphans
}
// ============================================================================
// Main Validation Function
// ============================================================================
@@ -305,9 +395,35 @@ function checkNestedMxCells(xml: string): string | null {
* Validates draw.io XML structure for common issues
* Uses DOM parsing + additional regex checks for high accuracy
* @param xml - The XML string to validate
* @param opts.strict - Also reject unknown element names and orphan
* <mxPoint>s. Used for XML the model wrote, not for files or browser state.
* @returns null if valid, error message string if invalid
*/
export function validateMxCellStructure(xml: string): string | null {
/** The first non-blank text under el, skipping a page's compressed data */
function findTextBetweenTags(el: Element | null): string | null {
if (!el) return null
// A <diagram> with only text holds the page compressed
const compressed = el.tagName === "diagram" && el.children.length === 0
for (const node of Array.from(el.childNodes)) {
if (node.nodeType === 1) {
const text = findTextBetweenTags(node as Element)
if (text) return text
} else if (
// Text, or a CDATA section (draw.io reads it as text too)
(node.nodeType === 3 || node.nodeType === 4) &&
!compressed
) {
const text = node.textContent?.trim()
if (text) return text.slice(0, 40)
}
}
return null
}
export function validateMxCellStructure(
xml: string,
opts: { strict?: boolean } = {},
): string | null {
// Size check for performance
if (xml.length > MAX_XML_SIZE) {
console.warn(
@@ -315,14 +431,11 @@ export function validateMxCellStructure(xml: string): string | null {
)
}
// 0. First use DOM parser to catch syntax errors (most accurate)
// 0. DOM-based checks. Syntax errors are caught by the strict check at
// the end: linkedom's DOMParser never reports them.
try {
const parser = new DOMParser()
const doc = parser.parseFromString(xml, "text/xml")
const parseError = doc.querySelector("parsererror")
if (parseError) {
return `Invalid XML: The XML contains syntax errors (likely unescaped special characters like <, >, & in attribute values). Please escape special characters: use &lt; for <, &gt; for >, &amp; for &, &quot; for ". Regenerate the diagram with properly escaped values.`
}
// DOM-based checks for nested mxCell
const allCells = doc.querySelectorAll("mxCell")
@@ -332,6 +445,15 @@ export function validateMxCellStructure(xml: string): string | null {
return `Invalid XML: Found nested mxCell (id="${id}"). Cells should be siblings, not nested inside other mxCell elements.`
}
}
// draw.io reads any text inside a page as compressed page data and
// then fails to open the page
if (!doc.querySelector("parsererror")) {
const text = findTextBetweenTags(doc.documentElement)
if (text) {
return `Invalid XML: Found text "${text}" between tags. Labels belong in the value attribute; remove any other text between tags.`
}
}
} catch (error) {
console.warn(
"[validateMxCellStructure] DOMParser threw unexpected error, falling back to regex validation:",
@@ -404,6 +526,24 @@ export function validateMxCellStructure(xml: string): string | null {
return nestedCellError
}
if (opts.strict) {
const unknownError = checkUnknownElements(xml)
if (unknownError) {
return unknownError
}
if (findOrphanMxPoints(xml).length > 0) {
return 'Invalid XML: Found <mxPoint> without an "as" attribute outside <Array as="points">. Put waypoints inside <Array as="points"> or remove the point.'
}
}
// 11. Strict XML syntax check, run last so the checks above can give
// more specific messages. Catches what they miss, e.g. duplicate or
// unquoted attributes, which make draw.io refuse to load the diagram.
const syntaxError = getXmlSyntaxError(xml)
if (syntaxError) {
return `Invalid XML: syntax error at ${syntaxError} Escape special characters in attribute values (&lt; for <, &amp; for &, &quot; for "), quote every attribute value, and do not repeat an attribute.`
}
return null
}
@@ -427,6 +567,15 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
fixes.push("Fixed JSON-escaped XML")
}
// 0b. Literal \n, \t or \r between tags, from escaping the XML twice
const unescaped = fixed.replace(/>(?:\s|\\[nrt])+</g, (gap) =>
gap.replace(/\\n/g, "\n").replace(/\\t/g, "\t").replace(/\\r/g, ""),
)
if (unescaped !== fixed) {
fixed = unescaped
fixes.push("Replaced literal \\n between tags with line breaks")
}
// 1. Remove CDATA wrapper
if (/^\s*<!\[CDATA\[/.test(fixed)) {
fixed = fixed.replace(/^\s*<!\[CDATA\[/, "").replace(/\]\]>\s*$/, "")
@@ -442,27 +591,23 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
// 3. Fix duplicate attributes
let dupAttrFixed = false
const structural = new Set(STRUCTURAL_ATTRS)
fixed = fixed.replace(/<[^>]+>/g, (tag) => {
let newTag = tag
for (const attr of STRUCTURAL_ATTRS) {
const attrRegex = new RegExp(
`\\s${attr}\\s*=\\s*["'][^"']*["']`,
"gi",
)
const matches = tag.match(attrRegex)
if (matches && matches.length > 1) {
let firstKept = false
newTag = newTag.replace(attrRegex, (m) => {
if (!firstKept) {
firstKept = true
return m
}
dupAttrFixed = true
return ""
})
// Keep the first of each, drop the later ones
const seen = new Set<string>()
let newTag = ""
let last = 0
for (const attr of readAttributes(tag)) {
if (!structural.has(attr.name)) continue
if (!seen.has(attr.name)) {
seen.add(attr.name)
continue
}
newTag += tag.slice(last, attr.start)
last = attr.end
dupAttrFixed = true
}
return newTag
return newTag + tag.slice(last)
})
if (dupAttrFixed) {
fixes.push("Removed duplicate structural attributes")
@@ -494,13 +639,21 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
}
}
// 6. Fix malformed attribute quotes
const malformedQuotePattern = /(\s[a-zA-Z][a-zA-Z0-9_:-]*)=&quot;/
if (malformedQuotePattern.test(fixed)) {
fixed = fixed.replace(
/(\s[a-zA-Z][a-zA-Z0-9_:-]*)=&quot;([^&]*?)&quot;/g,
'$1="$2"',
)
// 6. Fix malformed attribute quotes (name=&quot;value&quot;). Quoted
// values are matched first and kept, so &quot; inside a rich-text
// label like value="&lt;font style=&quot;...&quot;&gt;" is left alone.
let quotesFixed = false
fixed = replaceInOpeningTags(fixed, (tag) =>
tag.replace(
/("[^"]*"|'[^']*')|(\s[a-zA-Z][a-zA-Z0-9_:-]*)=&quot;([^&]*?)&quot;/g,
(match, quoted, name, value) => {
if (quoted) return match
quotesFixed = true
return `${name}="${value}"`
},
),
)
if (quotesFixed) {
fixes.push("Fixed malformed attribute quotes")
}
@@ -511,10 +664,21 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
fixes.push("Fixed malformed closing tags")
}
// 8. Fix missing space between attributes
const missingSpacePattern = /("[^"]*")([a-zA-Z][a-zA-Z0-9_:-]*=)/g
if (missingSpacePattern.test(fixed)) {
fixed = fixed.replace(/("[^"]*")([a-zA-Z][a-zA-Z0-9_:-]*=)/g, "$1 $2")
// 8. Fix missing space between attributes (id="2"vertex="1"). Every
// quoted value is consumed whole, so quotes always pair up within one
// attribute.
let spaceAdded = false
fixed = replaceInOpeningTags(fixed, (tag) =>
tag.replace(
/("[^"]*"|'[^']*')([a-zA-Z_:])?/g,
(match, quoted, next) => {
if (!next) return match
spaceAdded = true
return `${quoted} ${next}`
},
),
)
if (spaceAdded) {
fixes.push("Added missing space between attributes")
}
@@ -596,62 +760,67 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
fixes.push("Fixed <Cell> tags to <mxCell>")
}
// 15. Fix common closing tag typos (MUST run before foreign tag removal)
const tagTypos = [
{ wrong: /<\/mxElement>/gi, right: "</mxCell>", name: "</mxElement>" },
{ wrong: /<\/mxcell>/g, right: "</mxCell>", name: "</mxcell>" },
{
wrong: /<\/mxgeometry>/g,
right: "</mxGeometry>",
name: "</mxgeometry>",
},
{ wrong: /<\/mxpoint>/g, right: "</mxPoint>", name: "</mxpoint>" },
{
wrong: /<\/mxgraphmodel>/gi,
right: "</mxGraphModel>",
name: "</mxgraphmodel>",
},
]
for (const { wrong, right, name } of tagTypos) {
const before = fixed
fixed = fixed.replace(wrong, right)
if (fixed !== before) {
fixes.push(`Fixed typo ${name} to ${right}`)
// 15. Fix closing tag typos and wrong tag case, e.g. <mxcell> (MUST run
// before foreign tag removal, which would otherwise delete them)
const before15 = fixed
fixed = fixed.replace(/<\/mxElement>/gi, "</mxCell>")
if (fixed !== before15) {
fixes.push("Fixed typo </mxElement> to </mxCell>")
}
for (const name of ["mxCell", "mxGeometry", "mxPoint", "mxGraphModel"]) {
let changed = false
fixed = fixed.replace(
new RegExp(`<(/?)${name}(?=[\\s/>])`, "gi"),
(match, slash) => {
const right = `<${slash}${name}`
if (match !== right) changed = true
return right
},
)
if (changed) {
fixes.push(`Fixed tag case of <${name}>`)
}
}
// 16. Remove non-draw.io tags (after typo fixes so lowercase variants are fixed first)
const validDrawioTags = new Set([
"mxfile",
"diagram",
"mxGraphModel",
"root",
"mxCell",
"mxGeometry",
"mxPoint",
"Array",
"Object",
"mxRectangle",
])
// 16. Remove non-draw.io tags (after the case fixes above). Removes only
// the exact tag occurrences and skips quoted attribute values, so a stray
// <mxGraph/> never takes <mxGraphModel> with it and <b> inside
// value="..." stays.
const isInsideQuotesFor16 = createQuoteTracker(fixed)
const foreignTagPattern = /<\/?([a-zA-Z][a-zA-Z0-9_]*)[^>]*>/g
let foreignMatch
const foreignTags = new Set<string>()
const foreignTagPositions: Array<{ start: number; end: number }> = []
while ((foreignMatch = foreignTagPattern.exec(fixed)) !== null) {
const tagName = foreignMatch[1]
if (!validDrawioTags.has(tagName)) {
foreignTags.add(tagName)
}
if (VALID_DRAWIO_TAGS.has(tagName)) continue
if (isInsideQuotesFor16(foreignMatch.index)) continue
foreignTags.add(tagName)
foreignTagPositions.push({
start: foreignMatch.index,
end: foreignMatch.index + foreignMatch[0].length,
})
}
if (foreignTags.size > 0) {
for (const tag of foreignTags) {
fixed = fixed.replace(new RegExp(`<${tag}[^>]*>`, "gi"), "")
fixed = fixed.replace(new RegExp(`</${tag}>`, "gi"), "")
if (foreignTagPositions.length > 0) {
// Remove from the end so earlier positions stay valid
for (const { start, end } of foreignTagPositions.reverse()) {
fixed = fixed.slice(0, start) + fixed.slice(end)
}
fixes.push(
`Removed foreign tags: ${Array.from(foreignTags).join(", ")}`,
)
}
// 16b. Remove orphan <mxPoint>s (no "as" attribute, not inside
// <Array as="points">), which draw.io refuses to load
const orphanPoints = findOrphanMxPoints(fixed)
if (orphanPoints.length > 0) {
for (const { start, end } of orphanPoints.reverse()) {
fixed = fixed.slice(0, start) + fixed.slice(end)
}
fixes.push(`Removed ${orphanPoints.length} orphan <mxPoint>(s)`)
}
// 17. Fix unclosed tags
const tagStack: string[] = []
const parsedTags = parseXmlTags(fixed)
@@ -689,19 +858,23 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
}
}
// 18. Remove extra closing tags
// 18. Remove extra closing tags. Counts only draw.io tags outside quoted
// attribute values (value="<b>Title</b>" holds HTML, not elements).
const tagCounts = new Map<
string,
{ opens: number; closes: number; selfClosing: number }
>()
const fullTagPattern = /<(\/?[a-zA-Z][a-zA-Z0-9]*)[^>]*>/g
const isInsideQuotesFor18 = createQuoteTracker(fixed)
let tagCountMatch
while ((tagCountMatch = fullTagPattern.exec(fixed)) !== null) {
if (isInsideQuotesFor18(tagCountMatch.index)) continue
const fullMatch = tagCountMatch[0]
const tagPart = tagCountMatch[1]
const isClosing = tagPart.startsWith("/")
const isSelfClosing = fullMatch.endsWith("/>")
const tagName = isClosing ? tagPart.slice(1) : tagPart
if (!VALID_DRAWIO_TAGS.has(tagName)) continue
let counts = tagCounts.get(tagName)
if (!counts) {
@@ -796,8 +969,10 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
fixes.push(`Flattened ${nestedFixed} duplicate-ID nested mxCell(s)`)
}
// 21. Fix true nested mxCell (different IDs)
const lines2 = fixed.split("\n")
// 21. Fix true nested mxCell (different IDs). Runs only when the nesting
// check finds real nesting, because this line-based rewrite can break
// valid cells written over several lines.
const lines2 = checkNestedMxCells(fixed) ? fixed.split("\n") : []
newLines = []
let trueNestedFixed = 0
let cellDepth = 0
@@ -807,7 +982,11 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
const line = lines2[i]
const trimmed = line.trim()
const isOpenCell = /<mxCell\s/.test(trimmed) && !trimmed.endsWith("/>")
// A line holding a whole cell (<mxCell ...>...</mxCell>) opens nothing
const isOpenCell =
/<mxCell\s/.test(trimmed) &&
!trimmed.endsWith("/>") &&
!trimmed.endsWith("</mxCell>")
const isCloseCell = trimmed === "</mxCell>"
if (isOpenCell) {
@@ -860,9 +1039,11 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
if (duplicateIds.length > 0) {
const idCounters = new Map<string, number>()
// Rebuild from the captured parts so only the value changes (an id
// like "d" or "i" also occurs in the attribute name itself)
fixed = fixed.replace(
/\bid\s*=\s*["']([^"']+)["']/gi,
(match, id) => {
/(\bid\s*=\s*["'])([^"']+)(["'])/gi,
(match, before, id, after) => {
if (!duplicateIds.includes(id)) return match
const count = idCounters.get(id) || 0
@@ -870,8 +1051,7 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
if (count === 0) return match
const newId = `${id}_dup${count}`
return match.replace(id, newId)
return `${before}${id}_dup${count}${after}`
},
)
fixes.push(`Renamed ${duplicateIds.length} duplicate ID(s)`)
@@ -892,49 +1072,6 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
fixes.push(`Generated ${emptyIdCount} missing ID(s)`)
}
// 24. Aggressive: drop broken mxCell elements
if (typeof DOMParser !== "undefined") {
let droppedCells = 0
let maxIterations = MAX_DROP_ITERATIONS
while (maxIterations-- > 0) {
const parser = new DOMParser()
const doc = parser.parseFromString(fixed, "text/xml")
const parseError = doc.querySelector("parsererror")
if (!parseError) break
const errText = parseError.textContent || ""
const match = errText.match(/(\d+):\d+:/)
if (!match) break
const errLine = parseInt(match[1], 10) - 1
const lines = fixed.split("\n")
let cellStart = errLine
let cellEnd = errLine
while (cellStart > 0 && !lines[cellStart].includes("<mxCell")) {
cellStart--
}
while (cellEnd < lines.length - 1) {
if (
lines[cellEnd].includes("</mxCell>") ||
lines[cellEnd].trim().endsWith("/>")
) {
break
}
cellEnd++
}
lines.splice(cellStart, cellEnd - cellStart + 1)
fixed = lines.join("\n")
droppedCells++
}
if (droppedCells > 0) {
fixes.push(`Dropped ${droppedCells} unfixable mxCell element(s)`)
}
}
return { fixed, fixes }
}
@@ -943,18 +1080,23 @@ export function autoFixXml(xml: string): { fixed: string; fixes: string[] } {
// ============================================================================
/**
* Validates XML and attempts to fix if invalid
* Validates XML and attempts to fix if invalid. By default runs the strict
* checks (unknown elements, orphan mxPoints), meant for XML the model wrote.
* Pass strict: false for a diagram that also holds the user's own content.
* @param xml - The XML string to validate and potentially fix
* @returns Object with validation result, fixed XML if applicable, and fixes applied
*/
export function validateAndFixXml(xml: string): {
export function validateAndFixXml(
xml: string,
{ strict = true }: { strict?: boolean } = {},
): {
valid: boolean
error: string | null
fixed: string | null
fixes: string[]
} {
// First validation attempt
let error = validateMxCellStructure(xml)
let error = validateMxCellStructure(xml, { strict })
if (!error) {
return { valid: true, error: null, fixed: null, fixes: [] }
@@ -964,7 +1106,7 @@ export function validateAndFixXml(xml: string): {
const { fixed, fixes } = autoFixXml(xml)
// Validate the fixed version
error = validateMxCellStructure(fixed)
error = validateMxCellStructure(fixed, { strict })
if (!error) {
return { valid: true, error: null, fixed, fixes }
@@ -978,33 +1120,3 @@ export function validateAndFixXml(xml: string): {
fixes,
}
}
/**
* Check if mxCell XML output is complete (not truncated).
* Uses a robust approach that handles any LLM provider's wrapper tags
* by finding the last valid mxCell ending and checking if suffix is just closing tags.
* @param xml - The XML string to check (can be undefined/null)
* @returns true if XML appears complete, false if truncated or empty
*/
export function isMxCellXmlComplete(xml: string | undefined | null): boolean {
const trimmed = xml?.trim() || ""
if (!trimmed) return false
// Find position of last complete mxCell ending (either /> or </mxCell>)
const lastSelfClose = trimmed.lastIndexOf("/>")
const lastMxCellClose = trimmed.lastIndexOf("</mxCell>")
const lastValidEnd = Math.max(lastSelfClose, lastMxCellClose)
// No valid ending found at all
if (lastValidEnd === -1) return false
// Check what comes after the last valid ending
// For />: add 2 chars, for </mxCell>: add 9 chars
const endOffset = lastMxCellClose > lastSelfClose ? 9 : 2
const suffix = trimmed.slice(lastValidEnd + endOffset)
// If suffix is empty or only contains closing tags (any provider's wrapper) or whitespace, it's complete
// This regex matches any sequence of closing XML tags like </foo>, </bar>, </|DSML|xyz>
return /^(\s*<\/[^>]+>)*\s*$/.test(suffix)
}