Compare commits

..

1 Commits

Author SHA1 Message Date
dayuan.jiang
95c8c8d01f fix(electron): override draw.io iframe beforeunload to allow window close (fixes #815)
The draw.io iframe registers a window.onbeforeunload handler that returns
a non-empty string whenever its internal editor.modified flag is true.
After the user edits text in a shape, that flag is set and never cleared.

Per Electron BrowserWindow docs, returning a non-void value from any
beforeunload handler in the page tree silently cancels the window close
without showing a dialog. This is what caused the X button (and Cmd+Q)
to do nothing for users who had typed in a shape.

Calling event.preventDefault() in will-prevent-unload tells Electron to
ignore the iframe's beforeunload return value and proceed with the close.
The host app already persists diagrams via autosave + visibilitychange,
so the prompt was unnecessary.

Verified by reproducing the bug, applying the fix, and re-testing.
2026-05-20 23:28:48 +09:00
6 changed files with 1206 additions and 1611 deletions

View File

@@ -12,6 +12,7 @@ import {
import { useDiagram } from "@/contexts/diagram-context" import { useDiagram } from "@/contexts/diagram-context"
import { type DrawioTheme, isDrawioTheme } from "@/lib/drawio-themes" import { type DrawioTheme, isDrawioTheme } from "@/lib/drawio-themes"
import { i18n, type Locale } from "@/lib/i18n/config" import { i18n, type Locale } from "@/lib/i18n/config"
import { isIndexedDBUsable } from "@/lib/session-storage"
export default function Home() { export default function Home() {
const { const {
@@ -32,6 +33,8 @@ export default function Home() {
const [isLoaded, setIsLoaded] = useState(false) const [isLoaded, setIsLoaded] = useState(false)
const [isDrawioReady, setIsDrawioReady] = useState(false) const [isDrawioReady, setIsDrawioReady] = useState(false)
const [isElectron, setIsElectron] = useState(false) const [isElectron, setIsElectron] = useState(false)
const [canPersist, setCanPersist] = useState(false)
const [canPersistChecked, setCanPersistChecked] = useState(false)
const [drawioBaseUrl, setDrawioBaseUrl] = useState( const [drawioBaseUrl, setDrawioBaseUrl] = useState(
process.env.NEXT_PUBLIC_DRAWIO_BASE_URL || "https://embed.diagrams.net", process.env.NEXT_PUBLIC_DRAWIO_BASE_URL || "https://embed.diagrams.net",
) )
@@ -82,6 +85,11 @@ export default function Home() {
setDrawioBaseUrl(`${window.location.origin}/drawio/index.html`) setDrawioBaseUrl(`${window.location.origin}/drawio/index.html`)
} }
void (async () => {
const usable = await isIndexedDBUsable()
setCanPersist(usable)
setCanPersistChecked(true)
})()
setIsLoaded(true) setIsLoaded(true)
}, [pathname, router]) }, [pathname, router])
@@ -90,6 +98,13 @@ export default function Home() {
onDrawioLoad() onDrawioLoad()
}, [onDrawioLoad]) }, [onDrawioLoad])
const handleDrawioAutoSave = useCallback(
(data: { xml?: string }) => {
handleDiagramAutoSave(data)
},
[handleDiagramAutoSave],
)
const handleDarkModeChange = () => { const handleDarkModeChange = () => {
const newValue = !darkMode const newValue = !darkMode
setDarkMode(newValue) setDarkMode(newValue)
@@ -172,7 +187,7 @@ export default function Home() {
}`} }`}
> >
<div className="h-full rounded-xl overflow-hidden shadow-soft-lg border border-border/30 relative"> <div className="h-full rounded-xl overflow-hidden shadow-soft-lg border border-border/30 relative">
{isLoaded && ( {isLoaded && canPersistChecked && (
<div <div
className={`h-full w-full ${isDrawioReady ? "" : "invisible absolute inset-0"}`} className={`h-full w-full ${isDrawioReady ? "" : "invisible absolute inset-0"}`}
> >
@@ -180,14 +195,24 @@ export default function Home() {
key={`${drawioUi}-${darkMode}-${currentLang}-${isElectron}`} key={`${drawioUi}-${darkMode}-${currentLang}-${isElectron}`}
ref={drawioRef} ref={drawioRef}
autosave autosave
onAutoSave={handleDiagramAutoSave} onAutoSave={handleDrawioAutoSave}
onExport={handleDiagramExport} onExport={handleDiagramExport}
onLoad={handleDrawioLoad} onLoad={handleDrawioLoad}
baseUrl={drawioBaseUrl} baseUrl={drawioBaseUrl}
configuration={
canPersist
? { confirmExit: false }
: undefined
}
urlParameters={{ urlParameters={{
ui: drawioUi, ui: drawioUi,
spin: false, spin: false,
libraries: false, libraries: false,
// Disable modified tracking only when persistence is available
...(canPersist && {
modified: false,
keepmodified: false,
}),
saveAndExit: false, saveAndExit: false,
noSaveBtn: true, noSaveBtn: true,
noExitBtn: true, noExitBtn: true,

View File

@@ -58,6 +58,33 @@ interface ChatSessionDB extends DBSchema {
// Database singleton // Database singleton
let dbPromise: Promise<IDBPDatabase<ChatSessionDB>> | null = null let dbPromise: Promise<IDBPDatabase<ChatSessionDB>> | null = null
const resetDBPromise = () => {
dbPromise = null
}
const isClosingError = (error: unknown): boolean => {
return (
error instanceof DOMException &&
error.name === "InvalidStateError" &&
/closing/i.test(error.message)
)
}
const withDB = async <T>(
action: (db: IDBPDatabase<ChatSessionDB>) => Promise<T>,
): Promise<T> => {
try {
const db = await getDB()
return await action(db)
} catch (error) {
if (isClosingError(error)) {
resetDBPromise()
const db = await getDB()
return await action(db)
}
throw error
}
}
async function getDB(): Promise<IDBPDatabase<ChatSessionDB>> { async function getDB(): Promise<IDBPDatabase<ChatSessionDB>> {
if (!dbPromise) { if (!dbPromise) {
@@ -88,7 +115,23 @@ async function getDB(): Promise<IDBPDatabase<ChatSessionDB>> {
} }
} }
}, },
terminated() {
resetDBPromise()
},
}) })
dbPromise
.then((db) => {
db.onversionchange = () => {
db.close()
resetDBPromise()
}
db.onclose = () => {
resetDBPromise()
}
})
.catch(() => {
resetDBPromise()
})
} }
return dbPromise return dbPromise
} }
@@ -103,31 +146,46 @@ export function isIndexedDBAvailable(): boolean {
} }
} }
// Check if IndexedDB is actually usable (not just present).
// Note: Do NOT close the db here - getDB() returns a shared singleton connection
// that other code depends on.
export async function isIndexedDBUsable(): Promise<boolean> {
if (!isIndexedDBAvailable()) return false
try {
await getDB()
return true
} catch {
return false
}
}
// CRUD Operations // CRUD Operations
export async function getAllSessionMetadata(): Promise<SessionMetadata[]> { export async function getAllSessionMetadata(): Promise<SessionMetadata[]> {
if (!isIndexedDBAvailable()) return [] if (!isIndexedDBAvailable()) return []
try { try {
const db = await getDB() return await withDB(async (db) => {
const tx = db.transaction(STORE_NAME, "readonly") const tx = db.transaction(STORE_NAME, "readonly")
const index = tx.store.index("by-updated") const index = tx.store.index("by-updated")
const metadata: SessionMetadata[] = [] const metadata: SessionMetadata[] = []
// Use cursor to read only metadata fields (avoids loading full messages/XML) // Use cursor to read only metadata fields (avoids loading full messages/XML)
let cursor = await index.openCursor(null, "prev") // newest first let cursor = await index.openCursor(null, "prev") // newest first
while (cursor) { while (cursor) {
const s = cursor.value const s = cursor.value
metadata.push({ metadata.push({
id: s.id, id: s.id,
title: s.title, title: s.title,
createdAt: s.createdAt, createdAt: s.createdAt,
updatedAt: s.updatedAt, updatedAt: s.updatedAt,
messageCount: s.messages.length, messageCount: s.messages.length,
hasDiagram: !!s.diagramXml && s.diagramXml.trim().length > 0, hasDiagram:
thumbnailDataUrl: s.thumbnailDataUrl, !!s.diagramXml && s.diagramXml.trim().length > 0,
}) thumbnailDataUrl: s.thumbnailDataUrl,
cursor = await cursor.continue() })
} cursor = await cursor.continue()
return metadata }
return metadata
})
} catch (error) { } catch (error) {
console.error("Failed to get session metadata:", error) console.error("Failed to get session metadata:", error)
return [] return []
@@ -137,8 +195,9 @@ export async function getAllSessionMetadata(): Promise<SessionMetadata[]> {
export async function getSession(id: string): Promise<ChatSession | null> { export async function getSession(id: string): Promise<ChatSession | null> {
if (!isIndexedDBAvailable()) return null if (!isIndexedDBAvailable()) return null
try { try {
const db = await getDB() return await withDB(async (db) => {
return (await db.get(STORE_NAME, id)) || null return (await db.get(STORE_NAME, id)) || null
})
} catch (error) { } catch (error) {
console.error("Failed to get session:", error) console.error("Failed to get session:", error)
return null return null
@@ -148,8 +207,9 @@ export async function getSession(id: string): Promise<ChatSession | null> {
export async function saveSession(session: ChatSession): Promise<boolean> { export async function saveSession(session: ChatSession): Promise<boolean> {
if (!isIndexedDBAvailable()) return false if (!isIndexedDBAvailable()) return false
try { try {
const db = await getDB() await withDB(async (db) => {
await db.put(STORE_NAME, session) await db.put(STORE_NAME, session)
})
return true return true
} catch (error) { } catch (error) {
// Handle quota exceeded // Handle quota exceeded
@@ -161,8 +221,9 @@ export async function saveSession(session: ChatSession): Promise<boolean> {
await deleteOldestSession() await deleteOldestSession()
// Retry once // Retry once
try { try {
const db = await getDB() await withDB(async (db) => {
await db.put(STORE_NAME, session) await db.put(STORE_NAME, session)
})
return true return true
} catch (retryError) { } catch (retryError) {
console.error( console.error(
@@ -181,8 +242,9 @@ export async function saveSession(session: ChatSession): Promise<boolean> {
export async function deleteSession(id: string): Promise<void> { export async function deleteSession(id: string): Promise<void> {
if (!isIndexedDBAvailable()) return if (!isIndexedDBAvailable()) return
try { try {
const db = await getDB() await withDB(async (db) => {
await db.delete(STORE_NAME, id) await db.delete(STORE_NAME, id)
})
} catch (error) { } catch (error) {
console.error("Failed to delete session:", error) console.error("Failed to delete session:", error)
} }
@@ -191,8 +253,9 @@ export async function deleteSession(id: string): Promise<void> {
export async function getSessionCount(): Promise<number> { export async function getSessionCount(): Promise<number> {
if (!isIndexedDBAvailable()) return 0 if (!isIndexedDBAvailable()) return 0
try { try {
const db = await getDB() return await withDB(async (db) => {
return await db.count(STORE_NAME) return await db.count(STORE_NAME)
})
} catch (error) { } catch (error) {
console.error("Failed to get session count:", error) console.error("Failed to get session count:", error)
return 0 return 0
@@ -202,14 +265,15 @@ export async function getSessionCount(): Promise<number> {
export async function deleteOldestSession(): Promise<void> { export async function deleteOldestSession(): Promise<void> {
if (!isIndexedDBAvailable()) return if (!isIndexedDBAvailable()) return
try { try {
const db = await getDB() await withDB(async (db) => {
const tx = db.transaction(STORE_NAME, "readwrite") const tx = db.transaction(STORE_NAME, "readwrite")
const index = tx.store.index("by-updated") const index = tx.store.index("by-updated")
const cursor = await index.openCursor() const cursor = await index.openCursor()
if (cursor) { if (cursor) {
await cursor.delete() await cursor.delete()
} }
await tx.done await tx.done
})
} catch (error) { } catch (error) {
console.error("Failed to delete oldest session:", error) console.error("Failed to delete oldest session:", error)
} }

View File

@@ -57,6 +57,33 @@ export function generateDefaultTitle(prompt: string): string {
// Database singleton // Database singleton
let dbPromise: Promise<IDBPDatabase<TemplateDB>> | null = null let dbPromise: Promise<IDBPDatabase<TemplateDB>> | null = null
const resetDBPromise = () => {
dbPromise = null
}
const isClosingError = (error: unknown): boolean => {
return (
error instanceof DOMException &&
error.name === "InvalidStateError" &&
/closing/i.test(error.message)
)
}
const withDB = async <T>(
action: (db: IDBPDatabase<TemplateDB>) => Promise<T>,
): Promise<T> => {
try {
const db = await getDB()
return await action(db)
} catch (error) {
if (isClosingError(error)) {
resetDBPromise()
const db = await getDB()
return await action(db)
}
throw error
}
}
async function getDB(): Promise<IDBPDatabase<TemplateDB>> { async function getDB(): Promise<IDBPDatabase<TemplateDB>> {
if (!dbPromise) { if (!dbPromise) {
@@ -74,7 +101,23 @@ async function getDB(): Promise<IDBPDatabase<TemplateDB>> {
} }
} }
}, },
terminated() {
resetDBPromise()
},
}) })
dbPromise
.then((db) => {
db.onversionchange = () => {
db.close()
resetDBPromise()
}
db.onclose = () => {
resetDBPromise()
}
})
.catch(() => {
resetDBPromise()
})
} }
return dbPromise return dbPromise
} }
@@ -94,9 +137,10 @@ export function isIndexedDBAvailable(): boolean {
export async function getAllTemplates(): Promise<Template[]> { export async function getAllTemplates(): Promise<Template[]> {
if (!isIndexedDBAvailable()) return [] if (!isIndexedDBAvailable()) return []
try { try {
const db = await getDB() return await withDB(async (db) => {
const templates = await db.getAll(STORE_NAME) const templates = await db.getAll(STORE_NAME)
return sortTemplates(templates) return sortTemplates(templates)
})
} catch (error) { } catch (error) {
console.error("Failed to get templates:", error) console.error("Failed to get templates:", error)
return [] return []
@@ -106,8 +150,9 @@ export async function getAllTemplates(): Promise<Template[]> {
export async function getTemplate(id: string): Promise<Template | null> { export async function getTemplate(id: string): Promise<Template | null> {
if (!isIndexedDBAvailable()) return null if (!isIndexedDBAvailable()) return null
try { try {
const db = await getDB() return await withDB(async (db) => {
return (await db.get(STORE_NAME, id)) || null return (await db.get(STORE_NAME, id)) || null
})
} catch (error) { } catch (error) {
console.error("Failed to get template:", error) console.error("Failed to get template:", error)
return null return null
@@ -137,8 +182,9 @@ export async function createTemplate(
} }
try { try {
const db = await getDB() await withDB(async (db) => {
await db.put(STORE_NAME, template) await db.put(STORE_NAME, template)
})
return template return template
} catch (error) { } catch (error) {
console.error("Failed to create template:", error) console.error("Failed to create template:", error)
@@ -152,19 +198,20 @@ export async function updateTemplate(
): Promise<Template | null> { ): Promise<Template | null> {
if (!isIndexedDBAvailable()) return null if (!isIndexedDBAvailable()) return null
try { try {
const db = await getDB() return await withDB(async (db) => {
const existing = await db.get(STORE_NAME, id) const existing = await db.get(STORE_NAME, id)
if (!existing) return null if (!existing) return null
const updated: Template = { const updated: Template = {
...existing, ...existing,
...updates, ...updates,
id: existing.id, id: existing.id,
createdAt: existing.createdAt, createdAt: existing.createdAt,
updatedAt: Date.now(), updatedAt: Date.now(),
} }
await db.put(STORE_NAME, updated) await db.put(STORE_NAME, updated)
return updated return updated
})
} catch (error) { } catch (error) {
console.error("Failed to update template:", error) console.error("Failed to update template:", error)
return null return null
@@ -174,8 +221,9 @@ export async function updateTemplate(
export async function deleteTemplate(id: string): Promise<boolean> { export async function deleteTemplate(id: string): Promise<boolean> {
if (!isIndexedDBAvailable()) return false if (!isIndexedDBAvailable()) return false
try { try {
const db = await getDB() await withDB(async (db) => {
await db.delete(STORE_NAME, id) await db.delete(STORE_NAME, id)
})
return true return true
} catch (error) { } catch (error) {
console.error("Failed to delete template:", error) console.error("Failed to delete template:", error)
@@ -189,24 +237,25 @@ export async function duplicateTemplate(
): Promise<Template | null> { ): Promise<Template | null> {
if (!isIndexedDBAvailable()) return null if (!isIndexedDBAvailable()) return null
try { try {
const db = await getDB() return await withDB(async (db) => {
const existing = await db.get(STORE_NAME, id) const existing = await db.get(STORE_NAME, id)
if (!existing) return null if (!existing) return null
const now = Date.now() const now = Date.now()
const duplicate: Template = { const duplicate: Template = {
...existing, ...existing,
id: nanoid(), id: nanoid(),
title: `${existing.title} ${copySuffix}`, title: `${existing.title} ${copySuffix}`,
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,
clickCount: 0, clickCount: 0,
runCount: 0, runCount: 0,
lastUsedAt: 0, lastUsedAt: 0,
pinned: false, pinned: false,
} }
await db.put(STORE_NAME, duplicate) await db.put(STORE_NAME, duplicate)
return duplicate return duplicate
})
} catch (error) { } catch (error) {
console.error("Failed to duplicate template:", error) console.error("Failed to duplicate template:", error)
return null return null
@@ -218,12 +267,13 @@ export async function duplicateTemplate(
export async function incrementClickCount(id: string): Promise<void> { export async function incrementClickCount(id: string): Promise<void> {
if (!isIndexedDBAvailable()) return if (!isIndexedDBAvailable()) return
try { try {
const db = await getDB() await withDB(async (db) => {
const template = await db.get(STORE_NAME, id) const template = await db.get(STORE_NAME, id)
if (!template) return if (!template) return
template.clickCount += 1 template.clickCount += 1
template.updatedAt = Date.now() template.updatedAt = Date.now()
await db.put(STORE_NAME, template) await db.put(STORE_NAME, template)
})
} catch (error) { } catch (error) {
console.error("Failed to increment click count:", error) console.error("Failed to increment click count:", error)
} }
@@ -232,14 +282,15 @@ export async function incrementClickCount(id: string): Promise<void> {
export async function incrementRunCount(id: string): Promise<void> { export async function incrementRunCount(id: string): Promise<void> {
if (!isIndexedDBAvailable()) return if (!isIndexedDBAvailable()) return
try { try {
const db = await getDB() await withDB(async (db) => {
const template = await db.get(STORE_NAME, id) const template = await db.get(STORE_NAME, id)
if (!template) return if (!template) return
const now = Date.now() const now = Date.now()
template.runCount += 1 template.runCount += 1
template.lastUsedAt = now template.lastUsedAt = now
template.updatedAt = now template.updatedAt = now
await db.put(STORE_NAME, template) await db.put(STORE_NAME, template)
})
} catch (error) { } catch (error) {
console.error("Failed to increment run count:", error) console.error("Failed to increment run count:", error)
} }
@@ -372,8 +423,9 @@ export async function importTemplates(
pinned: typeof t.pinned === "boolean" ? t.pinned : false, pinned: typeof t.pinned === "boolean" ? t.pinned : false,
} }
try { try {
const db = await getDB() await withDB(async (db) => {
await db.put(STORE_NAME, newTemplate) await db.put(STORE_NAME, newTemplate)
})
existingKeys.add(key) existingKeys.add(key)
imported++ imported++
} catch (error) { } catch (error) {

2464
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "next-ai-draw-io", "name": "next-ai-draw-io",
"version": "0.4.16", "version": "0.4.15",
"license": "Apache-2.0", "license": "Apache-2.0",
"private": true, "private": true,
"main": "dist-electron/main/index.js", "main": "dist-electron/main/index.js",
@@ -49,9 +49,9 @@
"@langfuse/tracing": "^4.4.9", "@langfuse/tracing": "^4.4.9",
"@next/third-parties": "^16.0.6", "@next/third-parties": "^16.0.6",
"@opennextjs/cloudflare": "^1.17.1", "@opennextjs/cloudflare": "^1.17.1",
"@openrouter/ai-sdk-provider": "^2.0.0", "@openrouter/ai-sdk-provider": "^1.5.4",
"@opentelemetry/api": "^1.9.0", "@opentelemetry/api": "^1.9.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.216.0", "@opentelemetry/exporter-trace-otlp-http": "^0.214.0",
"@opentelemetry/sdk-trace-node": "^2.2.0", "@opentelemetry/sdk-trace-node": "^2.2.0",
"@radix-ui/react-alert-dialog": "^1.1.15", "@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-collapsible": "^1.1.12", "@radix-ui/react-collapsible": "^1.1.12",
@@ -77,7 +77,7 @@
"nanoid": "^5.0.0", "nanoid": "^5.0.0",
"negotiator": "^1.0.0", "negotiator": "^1.0.0",
"next": "^16.0.7", "next": "^16.0.7",
"ollama-ai-provider-v2": "^3.0.0", "ollama-ai-provider-v2": "^2.0.0",
"pako": "^2.1.0", "pako": "^2.1.0",
"prism-react-renderer": "^2.4.1", "prism-react-renderer": "^2.4.1",
"react": "^19.1.2", "react": "^19.1.2",
@@ -108,7 +108,7 @@
}, },
"devDependencies": { "devDependencies": {
"@anthropic-ai/tokenizer": "^0.0.4", "@anthropic-ai/tokenizer": "^0.0.4",
"@biomejs/biome": "2.4.13", "@biomejs/biome": "2.4.10",
"@playwright/test": "^1.57.0", "@playwright/test": "^1.57.0",
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@tailwindcss/typography": "^0.5.19", "@tailwindcss/typography": "^0.5.19",
@@ -127,7 +127,7 @@
"cross-env": "^10.1.0", "cross-env": "^10.1.0",
"electron": "^39.2.7", "electron": "^39.2.7",
"electron-builder": "^26.0.12", "electron-builder": "^26.0.12",
"esbuild": "^0.28.0", "esbuild": "^0.27.2",
"eslint": "9.39.4", "eslint": "9.39.4",
"eslint-config-next": "16.1.6", "eslint-config-next": "16.1.6",
"husky": "^9.1.7", "husky": "^9.1.7",

View File

@@ -521,9 +521,9 @@
} }
}, },
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "24.12.2", "version": "24.12.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.0.tgz",
"integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==", "integrity": "sha512-GYDxsZi3ChgmckRT9HPU0WEhKLP08ev/Yfcq2AstjrDASOYCSXeyjDsHg4v5t4jOj7cyDX3vmprafKlWIG9MXQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -2062,9 +2062,9 @@
} }
}, },
"node_modules/zod": { "node_modules/zod": {
"version": "4.4.1", "version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.4.1.tgz", "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-a6ENMBBGZBsnlSebQ/eKCguSBeGKSf4O7BPnqVPmYGtpBYI7VSqoVqw+QcB7kPRjbqPwhYTpFbVj/RqNz/CT0Q==", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT", "license": "MIT",
"funding": { "funding": {
"url": "https://github.com/sponsors/colinhacks" "url": "https://github.com/sponsors/colinhacks"