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.
This commit is contained in:
dayuan.jiang
2026-10-05 18:57:02 +09:00
parent c75f74a5a0
commit c0fa997186
67 changed files with 3152 additions and 531 deletions
+86 -1
View File
@@ -1,4 +1,10 @@
import { expect, getIframe, test } from "./lib/fixtures"
import {
expect,
getChatInput,
getIframe,
sendMessage,
test,
} from "./lib/fixtures"
test.describe("Chat Panel", () => {
test.beforeEach(async ({ page }) => {
@@ -20,3 +26,82 @@ test.describe("Chat Panel", () => {
expect(src).toBeTruthy()
})
})
test.describe("Crossing the mobile breakpoint", () => {
test.beforeEach(async ({ page }) => {
// A text answer that arrives in parts over a few seconds
await page.addInitScript(() => {
const realFetch = window.fetch
window.fetch = async (input, init) => {
const url = input instanceof Request ? input.url : String(input)
if (!url.endsWith("/api/chat")) return realFetch(input, init)
const events = [
{ type: "start" },
{ type: "text-start", id: "t" },
{ type: "text-delta", id: "t", delta: "Once upon" },
{ type: "text-delta", id: "t", delta: " a time." },
{ type: "text-end", id: "t" },
{ type: "finish" },
]
const body = new ReadableStream({
async start(controller) {
for (const event of events) {
controller.enqueue(
new TextEncoder().encode(
`data: ${JSON.stringify(event)}\n\n`,
),
)
await new Promise((r) => setTimeout(r, 1500))
}
controller.enqueue(
new TextEncoder().encode("data: [DONE]\n\n"),
)
controller.close()
},
})
return new Response(body, {
headers: { "content-type": "text/event-stream" },
})
}
})
await page.setViewportSize({ width: 1280, height: 800 })
await page.goto("/", { waitUntil: "networkidle" })
await getIframe(page).waitFor({ state: "visible", timeout: 30000 })
})
test("keeps the chat and its streaming answer", async ({ page }) => {
const chat = page.locator('[data-panel-id="chat-panel"]')
await sendMessage(page, "Tell me a story")
await expect(page.getByText("Once upon")).toBeVisible({
timeout: 10000,
})
await page.setViewportSize({ width: 600, height: 900 })
await expect(page.getByText("Tell me a story")).toBeVisible()
// Half the height on mobile
await expect
.poll(async () => (await chat.boundingBox())?.height ?? 0)
.toBeCloseTo(450, -1)
await page.setViewportSize({ width: 1280, height: 800 })
// A third of the width on desktop
await expect
.poll(async () => (await chat.boundingBox())?.width ?? 0)
.toBeCloseTo(1280 / 3, -1)
await expect(page.getByText("Once upon a time.")).toBeVisible({
timeout: 10000,
})
await expect(page.getByText("Tell me a story")).toBeVisible()
})
test("opens a chat collapsed on desktop", async ({ page }) => {
await page.locator("button:has(svg.lucide-panel-right-close)").click()
await expect(getChatInput(page)).toBeHidden()
await page.setViewportSize({ width: 600, height: 900 })
await expect(getChatInput(page)).toBeVisible()
await page.setViewportSize({ width: 1280, height: 800 })
await expect(getChatInput(page)).toBeVisible()
})
})
+50
View File
@@ -409,6 +409,14 @@ const drawReply = (id: string, xml: string) => {
const call = toolCallEvents(id, "display_diagram", { xml })
return `${sse([{ type: "start" }, call.start, ...call.deltas, call.done, { type: "finish" }])}data: [DONE]\n\n`
}
const textReply = (text: string) =>
`${sse([
{ type: "start" },
{ type: "text-start", id: "t" },
{ type: "text-delta", id: "t", delta: text },
{ type: "text-end", id: "t" },
{ type: "finish" },
])}data: [DONE]\n\n`
// SSE comments keep a stream open without sending anything
const KEEP_OPEN = Array(20).fill(":\n\n")
@@ -685,3 +693,45 @@ test("stopping during the screenshot check starts no new request", async ({
await p.waitForTimeout(5000)
expect(chatRequests).toBe(1)
})
test("stopping during the screenshot check lets the next message go at once", async ({
page: p,
}) => {
// The check was still running when the user stopped; it held up the
// chat until it ended, and its call never got a result
await p.addInitScript(() => {
localStorage.setItem("next-ai-draw-io-vlm-validation-enabled", "true")
})
const bodies: Array<{ messages: any[] }> = []
await p.route("**/api/chat", async (route) => {
bodies.push(route.request().postDataJSON())
const n = bodies.length
await route.fulfill({
status: 200,
contentType: "text/event-stream",
body:
n === 1
? drawReply("d1", cell("a", "Alpha", 40))
: textReply("Second answer"),
})
})
let checking = false
await p.route("**/api/validate-diagram", async (route) => {
checking = true
// Much longer than this test waits for the second answer
await new Promise((r) => setTimeout(r, 30000))
await route.fulfill({ status: 200, body: "{}" }).catch(() => {})
})
await p.goto("/", { waitUntil: "networkidle" })
await getIframe(p).waitFor({ state: "visible", timeout: 30000 })
await sendMessage(p, "Draw a box")
await expect.poll(() => checking, { timeout: 15000 }).toBe(true)
await p.getByRole("button", { name: "Stop generation" }).click()
await sendMessage(p, "Thanks")
await expect(p.getByText("Second answer")).toBeVisible({ timeout: 8000 })
// The drawing call had its result when the next message was sent
const draw = bodies[1].messages
.flatMap((m: any) => m.parts ?? [])
.find((part: any) => part.type === "tool-display_diagram")
expect(draw?.state).toBe("output-available")
})
+86
View File
@@ -86,6 +86,40 @@ test.describe("History and Session Restore", () => {
).toBeVisible()
})
test("new chat can go on without saving when storage is full", async ({
page,
}) => {
// Old chats can only be deleted from the empty chat's list, so the
// user must be able to get there
await page.route("**/api/chat", async (route) => {
await route.fulfill({
status: 200,
contentType: "text/event-stream",
body: createMockSSEResponse(
SINGLE_BOX_XML,
"Created your test diagram.",
),
})
})
await page.goto("/", { waitUntil: "networkidle" })
await getIframe(page).waitFor({ state: "visible", timeout: 30000 })
await sendMessage(page, "Create a test diagram")
await waitForText(page, "Created your test diagram.")
await page.evaluate(() => {
IDBObjectStore.prototype.put = () => {
throw new DOMException("Storage is full", "QuotaExceededError")
}
})
await page.locator('[data-testid="new-chat-button"]').click()
await page
.getByRole("button", { name: "Continue without saving" })
.click({ timeout: 5000 })
await expect(
page.locator('text="Created your test diagram."'),
).toHaveCount(0, { timeout: 5000 })
await expect(page.getByText("Paper to Diagram")).toBeVisible()
})
// A diagram drawn by hand, without chat messages: loaded into draw.io
// directly, then moved with an arrow key, which draw.io reports as an
// edit like any manual change
@@ -338,3 +372,55 @@ test.describe("History and Session Restore", () => {
})
})
})
/** Number of chats stored in this origin's IndexedDB */
const countSessions = (page: Page) =>
page.evaluate(
() =>
new Promise<number>((resolve, reject) => {
const open = indexedDB.open("next-ai-drawio")
open.onerror = () => reject(open.error)
open.onsuccess = () => {
const db = open.result
if (!db.objectStoreNames.contains("sessions")) {
db.close()
return resolve(0)
}
const count = db
.transaction("sessions", "readonly")
.objectStore("sessions")
.count()
count.onsuccess = () => {
db.close()
resolve(count.result)
}
}
}),
)
test("new chat right after an answer saves that chat once", async ({
page,
}) => {
test.setTimeout(180_000)
await page.route("**/api/chat", async (route) => {
await route.fulfill({
status: 200,
contentType: "text/event-stream",
body: createMockSSEResponse(SINGLE_BOX_XML, "Drew the box."),
})
})
await page.goto("/", { waitUntil: "networkidle" })
await getIframe(page).waitFor({ state: "visible", timeout: 30000 })
const newChat = page.locator('[data-testid="new-chat-button"]')
// The auto-save runs a second after the answer; New Chat around then
// waits for its thumbnail while the auto-save starts
for (let run = 1; run <= 10; run++) {
await sendMessage(page, `Draw box ${run}`)
await waitForText(page, "Drew the box.")
await page.waitForTimeout(500 + run * 100)
await newChat.click()
await expect(page.getByText("Drew the box.")).toHaveCount(0)
await page.waitForTimeout(2500)
expect(await countSessions(page), `run ${run}`).toBe(run)
}
})
+29
View File
@@ -302,6 +302,35 @@ test("an older test does not end a newer one's spinners", async ({ page }) => {
await expect(dialog.locator('[title="1.0 s"]')).toHaveCount(1)
})
test("an older test touches nothing, also when the key came back", async ({
page,
}) => {
const releases: Array<() => void> = []
await page.route("**/api/validate-model", async (route) => {
const n = releases.length
await new Promise<void>((r) => releases.push(r))
await route.fulfill({
status: 200,
// The older test's result would say 9.0 s
json: { valid: true, responseTime: n === 0 ? 9000 : 1000 },
})
})
const dialog = await openQwenSettings(page, TWO_PROVIDERS)
await dialog.getByRole("button", { name: "Test", exact: true }).click()
await expect.poll(() => releases.length).toBe(1)
// The key changes and comes back, and the user tests again
await dialog.locator("#api-key").fill("other-key")
await dialog.locator("#api-key").fill("test-key")
await dialog.getByRole("button", { name: "Test", exact: true }).click()
await expect.poll(() => releases.length).toBe(2)
releases[0]()
await page.waitForTimeout(500)
await expect(dialog.locator(".animate-spin").first()).toBeVisible()
await expect(dialog.locator('[title="9.0 s"]')).toHaveCount(0)
releases[1]()
await expect(dialog.locator('[title="1.0 s"]')).toHaveCount(1)
})
test("no spinner stays after another tab's change while elsewhere", async ({
page,
}) => {