Skip to content

AI-native design editor. Open-source Figma alternative.

fix: protect unsaved documents and defer credential access (#713)

Danila Poyarkov9d2b97e67963
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f17804a71..9acbe801b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,8 +2,14 @@
## Unreleased
+### Changed
+
+- Export diagnostics from Settings only. AI requests and tool activity now carry conversation and request identifiers, while chat no longer offers a separate diagnostic log or includes transcript content.
+
### Fixed
+- Mark unsaved documents and ask whether to save before closing a tab, the desktop window, or the application, rather than relying on recovery alone.
+- Defer AI provider connections and system credential reads until you send a message or use a connected feature, so opening documents and browsing chat history no longer trigger unexpected credential prompts.
- Point Homebrew installation instructions to the official `openpencil` cask and document separate CLI installation.
## 0.15.0 — 2026-09-16
diff --git a/bun.lock b/bun.lock
index 88044f094..3a3e5071d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -449,6 +449,13 @@
"valibot": "^1.4.2",
},
},
+ "tools/tauri-menu": {
+ "name": "@open-pencil/tauri-menu-tools",
+ "devDependencies": {
+ "@open-pencil/package-artifacts": "workspace:*",
+ "@open-pencil/vue": "workspace:*",
+ },
+ },
"tools/visual-oracles": {
"name": "@open-pencil/visual-oracle-tools",
"dependencies": {
@@ -1336,6 +1343,8 @@
"@open-pencil/scene-graph": ["@open-pencil/scene-graph@workspace:packages/scene-graph"],
+ "@open-pencil/tauri-menu-tools": ["@open-pencil/tauri-menu-tools@workspace:tools/tauri-menu"],
+
"@open-pencil/visual-oracle-tools": ["@open-pencil/visual-oracle-tools@workspace:tools/visual-oracles"],
"@open-pencil/vue": ["@open-pencil/vue@workspace:packages/vue"],
diff --git a/desktop/capabilities/default.json b/desktop/capabilities/default.json
index 109b7eeef..78e1f27cb 100644
--- a/desktop/capabilities/default.json
+++ b/desktop/capabilities/default.json
@@ -5,6 +5,7 @@
"windows": ["main"],
"permissions": [
"core:default",
+ "core:window:allow-destroy",
"opener:default",
"dialog:default",
"dialog:allow-save",
diff --git a/desktop/generated/app-menu.json b/desktop/generated/app-menu.json
new file mode 100644
index 000000000..d5e6179e7
--- /dev/null
+++ b/desktop/generated/app-menu.json
@@ -0,0 +1,12 @@
+{
+ "about": {
+ "label": "About OpenPencil"
+ },
+ "check-updates": {
+ "label": "Check for Updates…"
+ },
+ "quit": {
+ "label": "Quit OpenPencil",
+ "accelerator": "CmdOrCtrl+Q"
+ }
+}
diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs
index e65b2304a..cd94fbd9f 100644
--- a/desktop/src/lib.rs
+++ b/desktop/src/lib.rs
@@ -174,6 +174,13 @@ pub fn run() {
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(|_app, event| match event {
+ tauri::RunEvent::ExitRequested {
+ api, code: None, ..
+ } if !_app.webview_windows().is_empty() => {
+ api.prevent_exit();
+ // The frontend asks about unsaved documents and exits when they agree.
+ let _ = _app.emit("menu-event", "quit");
+ }
#[cfg(target_os = "macos")]
tauri::RunEvent::Opened { urls } => {
let paths = urls
diff --git a/desktop/src/menu.rs b/desktop/src/menu.rs
index c79b56e7d..7c4d3f426 100644
--- a/desktop/src/menu.rs
+++ b/desktop/src/menu.rs
@@ -26,6 +26,31 @@ struct MenuEntry {
sub: Vec<MenuEntry>,
}
+#[cfg(target_os = "macos")]
+#[derive(Deserialize)]
+struct AppMenuItem {
+ label: String,
+ accelerator: Option<String>,
+}
+
+/// Generated from `APP_MENU_APP_ITEMS`; placement stays here because the
+/// OS-predefined items sit between these entries.
+#[cfg(target_os = "macos")]
+#[derive(Deserialize)]
+struct AppMenuFile {
+ about: AppMenuItem,
+ #[serde(rename = "check-updates")]
+ check_updates: AppMenuItem,
+ quit: AppMenuItem,
+}
+
+#[cfg(target_os = "macos")]
+fn app_menu_file() -> tauri::Result<AppMenuFile> {
+ Ok(serde_json::from_str(include_str!(
+ "../generated/app-menu.json"
+ ))?)
+}
+
fn build_submenu<R: tauri::Runtime>(
app: &tauri::AppHandle<R>,
label: &str,
@@ -208,26 +233,34 @@ pub fn install_app_menu<R: tauri::Runtime>(
recent_files: &[String],
) -> tauri::Result<()> {
#[cfg(target_os = "macos")]
- let app_menu = SubmenuBuilder::new(app, "OpenPencil")
- .item(&PredefinedMenuItem::about(
- app,
- Some("About OpenPencil"),
- None,
- )?)
- .item(
- &MenuItemBuilder::new("Check for Updates…")
- .id("check-updates")
- .build(app)?,
- )
- .separator()
- .item(&PredefinedMenuItem::services(app, None)?)
- .separator()
- .item(&PredefinedMenuItem::hide(app, None)?)
- .item(&PredefinedMenuItem::hide_others(app, None)?)
- .item(&PredefinedMenuItem::show_all(app, None)?)
- .separator()
- .item(&PredefinedMenuItem::quit(app, None)?)
- .build()?;
+ let app_menu = {
+ let items = app_menu_file()?;
+ let mut check_updates =
+ MenuItemBuilder::new(&items.check_updates.label).id("check-updates");
+ if let Some(accelerator) = &items.check_updates.accelerator {
+ check_updates = check_updates.accelerator(accelerator);
+ }
+ let mut quit = MenuItemBuilder::new(&items.quit.label).id("quit");
+ if let Some(accelerator) = &items.quit.accelerator {
+ quit = quit.accelerator(accelerator);
+ }
+ SubmenuBuilder::new(app, tauri::Manager::package_info(app).name.clone())
+ .item(&PredefinedMenuItem::about(
+ app,
+ Some(&items.about.label),
+ None,
+ )?)
+ .item(&check_updates.build(app)?)
+ .separator()
+ .item(&PredefinedMenuItem::services(app, None)?)
+ .separator()
+ .item(&PredefinedMenuItem::hide(app, None)?)
+ .item(&PredefinedMenuItem::hide_others(app, None)?)
+ .item(&PredefinedMenuItem::show_all(app, None)?)
+ .separator()
+ .item(&quit.build(app)?)
+ .build()?
+ };
let schema_menus = build_schema_menus(app, recent_files)?;
let mut builder = MenuBuilder::new(app);
diff --git a/package.json b/package.json
index 007477bc2..c6b14f6a9 100644
--- a/package.json
+++ b/package.json
@@ -22,6 +22,7 @@
"tools/authoring-reference",
"tools/package-quality",
"tools/release-packages",
+ "tools/tauri-menu",
"tools/visual-oracles"
],
"type": "module",
diff --git a/packages/core/src/tools/stock-photo/providers.ts b/packages/core/src/tools/stock-photo/providers.ts
index 6e2c2f3b9..742ce62e2 100644
--- a/packages/core/src/tools/stock-photo/providers.ts
+++ b/packages/core/src/tools/stock-photo/providers.ts
@@ -64,9 +64,15 @@ function pickPexelsSize(src: PexelsPhoto['src'], targetDim: number): string {
return src.original
}
-let pexelsAPIKey: string | null = null
+type CredentialSource = string | null | (() => Promise<string | null>)
-export function setPexelsAPIKey(key: string | null): void {
+async function resolveCredential(source: CredentialSource): Promise<string | null> {
+ return typeof source === 'function' ? source() : source
+}
+
+let pexelsAPIKey: CredentialSource = null
+
+export function setPexelsAPIKey(key: CredentialSource): void {
pexelsAPIKey = key
if (key) {
registerStockPhotoProvider(pexelsProvider)
@@ -77,11 +83,12 @@ export function setPexelsAPIKey(key: string | null): void {
const pexelsProvider: StockPhotoProvider = {
name: 'pexels',
async search(query, { perPage, orientation, targetDim }) {
- if (!pexelsAPIKey) throw new Error('Pexels API key not configured')
+ const key = await resolveCredential(pexelsAPIKey)
+ if (!key) throw new Error('Pexels API key not configured')
const response = await ofetch.raw<{ photos: PexelsPhoto[] }>(
'https://api.pexels.com/v1/search',
{
- headers: { Authorization: pexelsAPIKey },
+ headers: { Authorization: key },
ignoreResponseError: true,
query: { query, per_page: perPage, orientation },
retry: 0
@@ -99,9 +106,9 @@ const pexelsProvider: StockPhotoProvider = {
}
}
-let unsplashAccessKey: string | null = null
+let unsplashAccessKey: CredentialSource = null
-export function setUnsplashAccessKey(key: string | null): void {
+export function setUnsplashAccessKey(key: CredentialSource): void {
unsplashAccessKey = key
if (key) {
registerStockPhotoProvider(unsplashProvider)
@@ -127,13 +134,14 @@ function pickUnsplashSize(urls: UnsplashPhoto['urls'], targetDim: number): strin
const unsplashProvider: StockPhotoProvider = {
name: 'unsplash',
async search(query, { perPage, orientation }) {
- if (!unsplashAccessKey) throw new Error('Unsplash access key not configured')
+ const key = await resolveCredential(unsplashAccessKey)
+ if (!key) throw new Error('Unsplash access key not configured')
const orient = orientation === 'square' ? 'squarish' : orientation
const response = await ofetch.raw<{ results: UnsplashPhoto[] }>(
'https://api.unsplash.com/search/photos',
{
headers: {
- Authorization: `Client-ID ${unsplashAccessKey}`,
+ Authorization: `Client-ID ${key}`,
'Accept-Version': 'v1'
},
ignoreResponseError: true,
diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.json
index f0d420b32..36b2435fa 100644
--- a/packages/vue/src/i18n/locales/de/ai.json
+++ b/packages/vue/src/i18n/locales/de/ai.json
@@ -137,11 +137,7 @@
"allDocuments": "Alle Dokumente",
"noChatsFound": "Keine Unterhaltungen gefunden.",
"chatActions": "Unterhaltungsaktionen",
- "copyDiagnosticLog": "Diagnoseprotokoll kopieren",
- "diagnosticCopied": "Diagnoseprotokoll kopiert.",
- "diagnosticCopyFailed": "Das Diagnoseprotokoll konnte nicht kopiert werden. Prüfe die Berechtigungen für die Zwischenablage und versuche es erneut.",
"continueChat": "Fortfahren",
- "copyACPLog": "ACP-Protokoll kopieren",
"chatSettings": "Chat",
"reasoningDisplay": "Anzeige der Überlegungen",
"reasoningCollapsed": "Standardmäßig eingeklappt",
diff --git a/packages/vue/src/i18n/locales/de/files.json b/packages/vue/src/i18n/locales/de/files.json
index 9d0ea9ec5..0b5a37dec 100644
--- a/packages/vue/src/i18n/locales/de/files.json
+++ b/packages/vue/src/i18n/locales/de/files.json
@@ -1,4 +1,8 @@
{
+ "unsavedChanges": "Ungespeicherte Änderungen",
+ "saveBeforeClosing": "Änderungen an „{name}“ speichern?",
+ "saveBeforeClosingDescription": "Wenn du ohne Speichern schließt, werden deine Änderungen verworfen.",
+ "discard": "Nicht speichern",
"importLabel": "Importieren",
"importHTMLCSS": "HTML/CSS importieren",
"importHTMLCSSDescription": "HTML sowie optionales CSS oder kompiliertes Tailwind-CSS einfügen.",
diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.json
index ccb906d30..4021e316d 100644
--- a/packages/vue/src/i18n/locales/es/ai.json
+++ b/packages/vue/src/i18n/locales/es/ai.json
@@ -137,11 +137,7 @@
"allDocuments": "Todos los documentos",
"noChatsFound": "No se encontraron conversaciones.",
"chatActions": "Acciones de la conversación",
- "copyDiagnosticLog": "Copiar registro de diagnóstico",
- "diagnosticCopied": "Registro de diagnóstico copiado.",
- "diagnosticCopyFailed": "No se pudo copiar el registro de diagnóstico. Comprueba los permisos del portapapeles e inténtalo de nuevo.",
"continueChat": "Continuar",
- "copyACPLog": "Copiar registro ACP",
"chatSettings": "Chat",
"reasoningDisplay": "Visualización del razonamiento",
"reasoningCollapsed": "Contraído por defecto",
diff --git a/packages/vue/src/i18n/locales/es/files.json b/packages/vue/src/i18n/locales/es/files.json
index 718c79d27..839b1f366 100644
--- a/packages/vue/src/i18n/locales/es/files.json
+++ b/packages/vue/src/i18n/locales/es/files.json
@@ -1,4 +1,8 @@
{
+ "unsavedChanges": "Cambios sin guardar",
+ "saveBeforeClosing": "¿Guardar los cambios de «{name}»?",
+ "saveBeforeClosingDescription": "Si cierras sin guardar, se perderán los cambios.",
+ "discard": "No guardar",
"importLabel": "Importar",
"importHTMLCSS": "Importar HTML/CSS",
"importHTMLCSSDescription": "Pega HTML y, opcionalmente, CSS o CSS de Tailwind compilado.",
diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.json
index e300292a4..79b7029f4 100644
--- a/packages/vue/src/i18n/locales/fr/ai.json
+++ b/packages/vue/src/i18n/locales/fr/ai.json
@@ -137,11 +137,7 @@
"allDocuments": "Tous les documents",
"noChatsFound": "Aucune discussion trouvée.",
"chatActions": "Actions de la discussion",
- "copyDiagnosticLog": "Copier le journal de diagnostic",
- "diagnosticCopied": "Journal de diagnostic copié.",
- "diagnosticCopyFailed": "Impossible de copier le journal de diagnostic. Vérifiez les autorisations du presse-papiers et réessayez.",
"continueChat": "Continuer",
- "copyACPLog": "Copier le journal ACP",
"chatSettings": "Discussion",
"reasoningDisplay": "Affichage du raisonnement",
"reasoningCollapsed": "Replié par défaut",
diff --git a/packages/vue/src/i18n/locales/fr/files.json b/packages/vue/src/i18n/locales/fr/files.json
index 890c34656..1b9bd6e1a 100644
--- a/packages/vue/src/i18n/locales/fr/files.json
+++ b/packages/vue/src/i18n/locales/fr/files.json
@@ -1,4 +1,8 @@
{
+ "unsavedChanges": "Modifications non enregistrées",
+ "saveBeforeClosing": "Enregistrer les modifications de « {name} » ?",
+ "saveBeforeClosingDescription": "Si vous fermez sans enregistrer, vos modifications seront perdues.",
+ "discard": "Ne pas enregistrer",
"importLabel": "Importer",
"importHTMLCSS": "Importer du HTML/CSS",
"importHTMLCSSDescription": "Collez du HTML avec, si besoin, du CSS ou du CSS Tailwind compilé.",
diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.json
index 640744aca..09d652e00 100644
--- a/packages/vue/src/i18n/locales/it/ai.json
+++ b/packages/vue/src/i18n/locales/it/ai.json
@@ -137,11 +137,7 @@
"allDocuments": "Tutti i documenti",
"noChatsFound": "Nessuna conversazione trovata.",
"chatActions": "Azioni della conversazione",
- "copyDiagnosticLog": "Copia registro diagnostico",
- "diagnosticCopied": "Registro diagnostico copiato.",
- "diagnosticCopyFailed": "Impossibile copiare il registro diagnostico. Controlla i permessi degli appunti e riprova.",
"continueChat": "Continua",
- "copyACPLog": "Copia registro ACP",
"chatSettings": "Chat",
"reasoningDisplay": "Visualizzazione del ragionamento",
"reasoningCollapsed": "Compresso per impostazione predefinita",
diff --git a/packages/vue/src/i18n/locales/it/files.json b/packages/vue/src/i18n/locales/it/files.json
index da3d42f8b..d92ab1a78 100644
--- a/packages/vue/src/i18n/locales/it/files.json
+++ b/packages/vue/src/i18n/locales/it/files.json
@@ -1,4 +1,8 @@
{
+ "unsavedChanges": "Modifiche non salvate",
+ "saveBeforeClosing": "Salvare le modifiche a «{name}»?",
+ "saveBeforeClosingDescription": "Se chiudi senza salvare, le modifiche andranno perse.",
+ "discard": "Non salvare",
"importLabel": "Importa",
"importHTMLCSS": "Importa HTML/CSS",
"importHTMLCSSDescription": "Incolla HTML con CSS facoltativo o CSS Tailwind compilato.",
diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.json
index 6f70b23b5..d328684d2 100644
--- a/packages/vue/src/i18n/locales/ja/ai.json
+++ b/packages/vue/src/i18n/locales/ja/ai.json
@@ -137,11 +137,7 @@
"allDocuments": "すべてのドキュメント",
"noChatsFound": "会話が見つかりません。",
"chatActions": "会話の操作",
- "copyDiagnosticLog": "診断ログをコピー",
- "diagnosticCopied": "診断ログをコピーしました。",
- "diagnosticCopyFailed": "診断ログをコピーできませんでした。クリップボードの権限を確認して、もう一度お試しください。",
"continueChat": "続ける",
- "copyACPLog": "ACPログをコピー",
"chatSettings": "チャット",
"reasoningDisplay": "推論の表示",
"reasoningCollapsed": "既定で折りたたむ",
diff --git a/packages/vue/src/i18n/locales/ja/files.json b/packages/vue/src/i18n/locales/ja/files.json
index 67ab6e830..b5f8251bc 100644
--- a/packages/vue/src/i18n/locales/ja/files.json
+++ b/packages/vue/src/i18n/locales/ja/files.json
@@ -1,4 +1,8 @@
{
+ "unsavedChanges": "未保存の変更",
+ "saveBeforeClosing": "「{name}」の変更を保存しますか?",
+ "saveBeforeClosingDescription": "保存せずに閉じると、変更は失われます。",
+ "discard": "保存しない",
"importLabel": "インポート",
"importHTMLCSS": "HTML/CSSをインポート",
"importHTMLCSSDescription": "HTMLと、必要に応じてCSSまたはコンパイル済みTailwind CSSを貼り付けます。",
diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.json
index 5b04b2fa0..fd071dcb2 100644
--- a/packages/vue/src/i18n/locales/pl/ai.json
+++ b/packages/vue/src/i18n/locales/pl/ai.json
@@ -137,11 +137,7 @@
"allDocuments": "Wszystkie dokumenty",
"noChatsFound": "Nie znaleziono rozmów.",
"chatActions": "Działania rozmowy",
- "copyDiagnosticLog": "Kopiuj dziennik diagnostyczny",
- "diagnosticCopied": "Skopiowano dziennik diagnostyczny.",
- "diagnosticCopyFailed": "Nie udało się skopiować dziennika diagnostycznego. Sprawdź uprawnienia schowka i spróbuj ponownie.",
"continueChat": "Kontynuuj",
- "copyACPLog": "Kopiuj dziennik ACP",
"chatSettings": "Czat",
"reasoningDisplay": "Wyświetlanie rozumowania",
"reasoningCollapsed": "Domyślnie zwinięte",
diff --git a/packages/vue/src/i18n/locales/pl/files.json b/packages/vue/src/i18n/locales/pl/files.json
index cddc7992c..a38360bb5 100644
--- a/packages/vue/src/i18n/locales/pl/files.json
+++ b/packages/vue/src/i18n/locales/pl/files.json
@@ -1,4 +1,8 @@
{
+ "unsavedChanges": "Niezapisane zmiany",
+ "saveBeforeClosing": "Zapisać zmiany w „{name}”?",
+ "saveBeforeClosingDescription": "Jeśli zamkniesz dokument bez zapisywania, zmiany zostaną utracone.",
+ "discard": "Nie zapisuj",
"importLabel": "Importuj",
"importHTMLCSS": "Importuj HTML/CSS",
"importHTMLCSSDescription": "Wklej HTML oraz opcjonalnie CSS lub skompilowany CSS Tailwind.",
diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.json
index fe94798ad..3f26aa69c 100644
--- a/packages/vue/src/i18n/locales/ru/ai.json
+++ b/packages/vue/src/i18n/locales/ru/ai.json
@@ -137,11 +137,7 @@
"allDocuments": "Все документы",
"noChatsFound": "Чаты не найдены.",
"chatActions": "Действия с чатом",
- "copyDiagnosticLog": "Копировать диагностический журнал",
- "diagnosticCopied": "Диагностический журнал скопирован.",
- "diagnosticCopyFailed": "Не удалось скопировать диагностический журнал. Проверьте разрешения буфера обмена и повторите попытку.",
"continueChat": "Продолжить",
- "copyACPLog": "Копировать журнал ACP",
"chatSettings": "Чат",
"reasoningDisplay": "Отображение рассуждений",
"reasoningCollapsed": "Свёрнуто по умолчанию",
diff --git a/packages/vue/src/i18n/locales/ru/files.json b/packages/vue/src/i18n/locales/ru/files.json
index de2f58199..032d55612 100644
--- a/packages/vue/src/i18n/locales/ru/files.json
+++ b/packages/vue/src/i18n/locales/ru/files.json
@@ -1,4 +1,8 @@
{
+ "unsavedChanges": "Несохранённые изменения",
+ "saveBeforeClosing": "Сохранить изменения в «{name}»?",
+ "saveBeforeClosingDescription": "Если закрыть документ без сохранения, изменения будут потеряны.",
+ "discard": "Не сохранять",
"importLabel": "Импорт",
"importHTMLCSS": "Импорт HTML/CSS",
"importHTMLCSSDescription": "Вставьте HTML и, при необходимости, CSS или скомпилированный Tailwind CSS.",
diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.json
index b4b056a37..fb1305481 100644
--- a/packages/vue/src/i18n/locales/zh-cn/ai.json
+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json
@@ -137,11 +137,7 @@
"allDocuments": "所有文档",
"noChatsFound": "未找到对话。",
"chatActions": "对话操作",
- "copyDiagnosticLog": "复制诊断日志",
- "diagnosticCopied": "诊断日志已复制。",
- "diagnosticCopyFailed": "无法复制诊断日志。请检查剪贴板权限并重试。",
"continueChat": "继续",
- "copyACPLog": "复制 ACP 日志",
"chatSettings": "聊天",
"reasoningDisplay": "推理显示",
"reasoningCollapsed": "默认折叠",
diff --git a/packages/vue/src/i18n/locales/zh-cn/files.json b/packages/vue/src/i18n/locales/zh-cn/files.json
index 594739383..6a8b816b6 100644
--- a/packages/vue/src/i18n/locales/zh-cn/files.json
+++ b/packages/vue/src/i18n/locales/zh-cn/files.json
@@ -1,4 +1,8 @@
{
+ "unsavedChanges": "未保存的更改",
+ "saveBeforeClosing": "保存对“{name}”的更改吗?",
+ "saveBeforeClosingDescription": "如果不保存就关闭,更改将丢失。",
+ "discard": "不保存",
"importLabel": "导入",
"importHTMLCSS": "导入 HTML/CSS",
"importHTMLCSSDescription": "粘贴 HTML,并可选择添加 CSS 或编译后的 Tailwind CSS。",
diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.ts
index 14fddb2c9..0505fd91b 100644
--- a/packages/vue/src/i18n/messages/ai.ts
+++ b/packages/vue/src/i18n/messages/ai.ts
@@ -10,11 +10,6 @@ export const aiMessageDefaults = {
reasoningWhileThinking: 'Expand while thinking',
reasoningExpanded: 'Expanded by default',
continueChat: 'Continue',
- copyACPLog: 'Copy ACP log',
- diagnosticCopied: 'Diagnostic log copied.',
- diagnosticCopyFailed:
- 'Could not copy the diagnostic log. Check clipboard permissions and try again.',
- copyDiagnosticLog: 'Copy diagnostic log',
searchChats: 'Search conversations…',
chatScope: 'Conversation scope',
thisDocument: 'This document',
diff --git a/packages/vue/src/i18n/messages/files.ts b/packages/vue/src/i18n/messages/files.ts
index f4b9483cf..f75c8b4ec 100644
--- a/packages/vue/src/i18n/messages/files.ts
+++ b/packages/vue/src/i18n/messages/files.ts
@@ -12,6 +12,10 @@ export const filesMessageDefaults = {
importToCanvas: 'Import to canvas',
newTab: 'New tab',
closeTab: params('Close {name}'),
+ unsavedChanges: 'Unsaved changes',
+ saveBeforeClosing: params('Save changes to “{name}”?'),
+ saveBeforeClosingDescription: 'Your changes will be discarded if you close without saving.',
+ discard: 'Don’t Save',
clipboardImageUnavailableWeb:
'Pasted design includes 1 image that cannot be loaded in the web app. Use the desktop app to include it.',
clipboardImagesUnavailableWeb: params(
diff --git a/src/App.vue b/src/App.vue
index ed2b83d21..eb7f3a815 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -7,6 +7,7 @@ import { computed, onMounted } from 'vue'
import { provideEditor, useI18n } from '@open-pencil/vue'
+import { useDocumentCloseProtection } from '@/app/document/close/use'
import { useEditorStore } from '@/app/editor/active-store'
import { animationsEnabled } from '@/app/shell/motion'
import { useAppTheme } from '@/app/shell/theme'
@@ -14,6 +15,7 @@ import { toast } from '@/app/shell/ui'
import { scheduleStartupUpdateCheck } from '@/app/shell/updater'
import { kickSyncEngine } from '@/app/storage/sync'
import { prepareForReload } from '@/app/tabs'
+import UnsavedChangesDialog from '@/components/document/UnsavedChangesDialog.vue'
import PublishLibraryDialog from '@/components/libraries/PublishLibraryDialog.vue'
import LibraryUpdateReviewDialog from '@/components/libraries/review/LibraryUpdateReviewDialog.vue'
import RecoveryDialog from '@/components/recovery/RecoveryDialog.vue'
@@ -34,6 +36,7 @@ useHead({
provideEditor(store)
useAppTheme()
+useDocumentCloseProtection()
useEventListener(window, 'pagehide', () => {
void prepareForReload()
})
@@ -53,6 +56,7 @@ onMounted(() => {
</AppShell>
<SettingsDialog />
<RecoveryDialog />
+ <UnsavedChangesDialog />
<PublishLibraryDialog />
<LibraryUpdateReviewDialog />
<AppToast />
diff --git a/src/app/ai/acp/transport.ts b/src/app/ai/acp/transport.ts
index a8fb713d2..6520f2c2b 100644
--- a/src/app/ai/acp/transport.ts
+++ b/src/app/ai/acp/transport.ts
@@ -19,12 +19,6 @@ import { spawnACPProcess } from './process'
type TauriChild = Awaited<ReturnType<typeof spawnACPProcess>>['child']
-interface ACPDebugEntry {
- ts: number
- type: string
- data: unknown
-}
-
interface ACPSession {
connection: ClientSideConnection
sessionId: string
@@ -33,34 +27,6 @@ interface ACPSession {
dead: boolean
}
-const MAX_LOG_AGE_MS = 5 * 60 * 1000
-const IS_DEV = import.meta.env.DEV
-
-const acpDebugLog: ACPDebugEntry[] = []
-
-function pruneOldEntries() {
- const cutoff = Date.now() - MAX_LOG_AGE_MS
- while (acpDebugLog.length > 0 && acpDebugLog[0].ts < cutoff) {
- acpDebugLog.shift()
- }
-}
-
-export function getACPDebugText(): string {
- pruneOldEntries()
- return acpDebugLog
- .map((e) => `[${new Date(e.ts).toISOString()}] ${e.type}\n${JSON.stringify(e.data, null, 2)}`)
- .join('\n\n---\n\n')
-}
-
-export function clearACPDebugLog() {
- acpDebugLog.length = 0
-}
-
-export function hasACPDebugEntries(): boolean {
- pruneOldEntries()
- return acpDebugLog.length > 0
-}
-
function isMissingCommandError(message: string): boolean {
const normalized = message.toLowerCase()
return normalized.includes('enoent') || normalized.includes('program not found')
@@ -170,13 +136,6 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
session.onUpdate = (params) => {
if (closed) return
- if (IS_DEV) {
- acpDebugLog.push({
- ts: Date.now(),
- type: params.update.sessionUpdate,
- data: params.update
- })
- }
const result = mapUpdate(params.update, textId, textStarted)
for (const chunk of result.chunks) {
controller.enqueue(chunk)
diff --git a/src/app/ai/chat/storage.ts b/src/app/ai/chat/storage.ts
index 6b673bc3d..d3921b1c9 100644
--- a/src/app/ai/chat/storage.ts
+++ b/src/app/ai/chat/storage.ts
@@ -18,7 +18,10 @@ import {
refreshMediaCredentials,
credentialPersistenceRevision
} from '@/app/settings/credentials/media'
-import { initializeCredentialMigration } from '@/app/settings/credentials/migration'
+import {
+ hasLegacyCredential,
+ initializeCredentialMigration
+} from '@/app/settings/credentials/migration'
import type { CredentialRef, CredentialStatus } from '@/app/settings/credentials/types'
export const providerID = designProviderID
@@ -46,7 +49,8 @@ export const isConfigured = computed(() => {
})
async function refreshStatus(reference: CredentialRef): Promise<CredentialStatus> {
- return appCredentialServices.manager.status(reference)
+ const status = await appCredentialServices.manager.status(reference)
+ return status === 'missing' && hasLegacyCredential(reference) ? 'configured' : status
}
function designCredentialReference(): CredentialRef | null {
@@ -60,13 +64,15 @@ export async function refreshAIProviderStatus(): Promise<void> {
apiKeyStatus.value = reference ? await refreshStatus(reference) : 'missing'
}
-export const credentialsReady = initializeCredentialMigration().then(async () => {
- await Promise.all([refreshAIProviderStatus(), refreshMediaCredentials()])
- return undefined
-})
+// Startup checks metadata only. Secret migration/resolution belongs to explicit provider use.
+export const credentialsReady = Promise.all([
+ refreshAIProviderStatus(),
+ refreshMediaCredentials()
+]).then(() => undefined)
export async function resolveAPIKey(): Promise<string | null> {
await credentialsReady
+ await initializeCredentialMigration()
const reference = designCredentialReference()
return reference ? appCredentialServices.resolver.resolve(reference) : null
}
@@ -74,6 +80,8 @@ export async function resolveAPIKey(): Promise<string | null> {
export async function setAPIKey(key: string): Promise<void> {
const reference = designCredentialReference()
if (!reference) return
+ // Migrate first so clearing also removes a value that only exists in legacy storage.
+ await initializeCredentialMigration()
const value = key.trim()
if (value) await appCredentialServices.manager.set(reference, value)
else await appCredentialServices.manager.clear(reference)
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index 3a178beb2..8ae29ddb2 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -18,6 +18,7 @@ import {
recordChatFailed,
recordModelStepCompleted
} from '@/app/diagnostics/events'
+import type { AIDiagnosticContext } from '@/app/diagnostics/events/ai'
import type { getActiveEditorStore } from '@/app/editor/active-store'
import { resumableTransport } from './history/continuation'
@@ -41,6 +42,7 @@ export type ToolLoopTransportOptions = {
maxOutputTokens: number
reasoningEffort: string
onError?: (error: unknown) => void
+ diagnosticContext?: AIDiagnosticContext
}
const ANTHROPIC_CACHE_CONTROL = {
@@ -80,9 +82,10 @@ export function createToolLoopTransport({
effectiveModelID,
maxOutputTokens,
reasoningEffort,
- onError
+ onError,
+ diagnosticContext = {}
}: ToolLoopTransportOptions) {
- const tools = createAITools(store)
+ const tools = createAITools(store, diagnosticContext)
const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)
? ANTHROPIC_CACHE_CONTROL
: undefined
@@ -108,14 +111,17 @@ export function createToolLoopTransport({
},
onStepFinish: ({ usage }) => {
recordStep(store)
- recordModelStepCompleted({
- provider: providerID,
- model: effectiveModelID,
- inputTokens: usage.inputTokens ?? null,
- outputTokens: usage.outputTokens ?? null,
- cacheReadTokens: usage.inputTokenDetails.cacheReadTokens ?? null,
- cacheWriteTokens: usage.inputTokenDetails.cacheWriteTokens ?? null
- })
+ recordModelStepCompleted(
+ {
+ provider: providerID,
+ model: effectiveModelID,
+ inputTokens: usage.inputTokens ?? null,
+ outputTokens: usage.outputTokens ?? null,
+ cacheReadTokens: usage.inputTokenDetails.cacheReadTokens ?? null,
+ cacheWriteTokens: usage.inputTokenDetails.cacheWriteTokens ?? null
+ },
+ diagnosticContext
+ )
}
})
@@ -152,19 +158,22 @@ export function createChatSessionManager({
activeProviderError ??= error
}
- function handleChatFinish({
- finishReason,
- isAbort,
- isDisconnect,
- isError
- }: {
- finishReason?: FinishReason
- isAbort: boolean
- isDisconnect: boolean
- isError: boolean
- }): void {
+ function handleChatFinish(
+ context: AIDiagnosticContext,
+ {
+ finishReason,
+ isAbort,
+ isDisconnect,
+ isError
+ }: {
+ finishReason?: FinishReason
+ isAbort: boolean
+ isDisconnect: boolean
+ isError: boolean
+ }
+ ): void {
if (!isAbort && !isDisconnect && !isError) {
- recordChatCompleted({ finishReason: finishReason ?? null })
+ recordChatCompleted({ finishReason: finishReason ?? null }, context)
}
}
@@ -226,7 +235,7 @@ export function createChatSessionManager({
return transport as ChatTransport<UIMessage>
}
- async function createTransport(store: EditorStore) {
+ async function createTransport(store: EditorStore, diagnosticContext: AIDiagnosticContext) {
if (overrideTransport) return overrideTransport()
await destroyAgentTransports()
@@ -246,7 +255,8 @@ export function createChatSessionManager({
}),
maxOutputTokens: runtime.role.profile.maxOutputTokens,
reasoningEffort: runtime.role.profile.reasoningEffort ?? '',
- onError: captureProviderError
+ onError: captureProviderError,
+ diagnosticContext
})
}
@@ -264,22 +274,32 @@ export function createChatSessionManager({
if (!chat || transportDirty || currentChatStore !== store) {
const messages = initialMessages ?? currentChatMessages.get(store)
+ const diagnosticContext: AIDiagnosticContext = { sessionId, runId: crypto.randomUUID() }
let transport: ChatTransport<UIMessage>
if (isACPProvider.value) transport = await createActiveACPTransport()
else if (isHarnessProvider.value) transport = await createActiveHarnessTransport(sessionId)
- else transport = await createTransport(store)
+ else transport = await createTransport(store, diagnosticContext)
chat = new Chat<UIMessage>({
- transport,
+ transport: {
+ sendMessages: (options) => {
+ diagnosticContext.runId = crypto.randomUUID()
+ return transport.sendMessages(options)
+ },
+ reconnectToStream: (options) => transport.reconnectToStream(options)
+ },
messages,
onError: (error) => {
const reportedError = activeProviderError ?? error
activeProviderError = null
failure.value = classifyAIChatError(reportedError)
- recordChatFailed({
- errorName: reportedError instanceof Error ? reportedError.name : 'unknown'
- })
+ recordChatFailed(
+ {
+ errorName: reportedError instanceof Error ? reportedError.name : 'unknown'
+ },
+ diagnosticContext
+ )
},
- onFinish: handleChatFinish
+ onFinish: (event) => handleChatFinish(diagnosticContext, event)
})
currentChatStore = store
transportDirty = false
diff --git a/src/app/ai/debug/index.ts b/src/app/ai/debug/index.ts
deleted file mode 100644
index 87a038665..000000000
--- a/src/app/ai/debug/index.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-import type { UIMessage } from 'ai'
-
-import { buildDebugLog } from '@open-pencil/core/tools'
-import type { ToolDebugLog, ToolLogEntry } from '@open-pencil/core/tools'
-import type { JSONObject } from '@open-pencil/scene-graph/primitives'
-
-import type { AIChatFailure } from '@/app/ai/chat/failure'
-import { getToolLogEntries } from '@/app/ai/tools'
-import { diagnostics } from '@/app/diagnostics'
-
-const MAX_FAILURE_DETAIL_LENGTH = 240
-const SENSITIVE_DETAIL_PATTERN =
- /(api[-_ ]?key|authorization|token|secret|password)(\s*[:=]\s*|\s+)([^\s,;]+)/gi
-
-export function safeFailureDetail(detail: string): string {
- const redacted = detail.replace(SENSITIVE_DETAIL_PATTERN, '$1$2[redacted]')
- return redacted.length <= MAX_FAILURE_DETAIL_LENGTH
- ? redacted
- : `${redacted.slice(0, MAX_FAILURE_DETAIL_LENGTH)}…`
-}
-
-export function formatTokenUsage(): string {
- const events = diagnostics.recent().filter((event) => event.name === 'model.step.completed')
- if (events.length === 0) return ' (no usage data — provider may not report it)'
-
- let totalInput = 0
- let totalOutput = 0
- let totalCacheRead = 0
- let totalCacheWrite = 0
- const lines = events.map((event, index) => {
- const input = event.attributes.inputTokens
- const output = event.attributes.outputTokens
- const cacheRead = event.attributes.cacheReadTokens
- const cacheWrite = event.attributes.cacheWriteTokens
- if (typeof input === 'number') totalInput += input
- if (typeof output === 'number') totalOutput += output
- if (typeof cacheRead === 'number') totalCacheRead += cacheRead
- if (typeof cacheWrite === 'number') totalCacheWrite += cacheWrite
- return ` Step ${events.length - index}: in=${input ?? 'not reported'} out=${output ?? 'not reported'} cache_read=${cacheRead ?? 'not reported'} cache_write=${cacheWrite ?? 'not reported'}`
- })
- const cacheHitRate = totalInput > 0 ? ((totalCacheRead / totalInput) * 100).toFixed(1) : '0.0'
- lines.unshift(
- `Total: in=${totalInput} out=${totalOutput} cache_read=${totalCacheRead} cache_write=${totalCacheWrite}`,
- `Cache hit rate: ${cacheHitRate}%`,
- `Steps: ${events.length}`
- )
- return lines.join('\n')
-}
-
-export function formatLogEntry(entry: ToolLogEntry, index: number): string {
- const time = new Date(entry.timestamp).toISOString().slice(11, 23)
- const lines = [` #${index + 1} [${time}] ${entry.tool} (${entry.durationMs}ms)`]
- lines.push(` args: ${JSON.stringify(entry.args)}`)
-
- if (entry.error) {
- lines.push(` ERROR: ${entry.error}`)
- } else {
- lines.push(` result: ${JSON.stringify(entry.result)}`)
- }
-
- if (entry.isDuplicate) {
- lines.push(` ⚠ DUPLICATE: same tool+args called earlier in session`)
- }
-
- if (entry.unchangedProps?.length) {
- lines.push(` ⚠ NO-OP PROPS: ${entry.unchangedProps.join(', ')}`)
- if (entry.nodeBefore) {
- for (const prop of entry.unchangedProps) {
- const val = entry.nodeBefore[prop]
- lines.push(` ${prop} stayed: ${JSON.stringify(val)}`)
- }
- }
- }
-
- if (entry.nodeBefore && entry.nodeAfter) {
- const changed = diffNodeSnapshots(entry.nodeBefore, entry.nodeAfter)
- if (changed.length > 0) {
- lines.push(
- ` changed: ${changed.map((c) => `${c.prop}: ${JSON.stringify(c.before)} → ${JSON.stringify(c.after)}`).join(', ')}`
- )
- }
- }
-
- return lines.join('\n')
-}
-
-function diffNodeSnapshots(
- before: Record<string, unknown>,
- after: Record<string, unknown>
-): Array<{ prop: string; before: unknown; after: unknown }> {
- const skip = new Set(['childIds', 'parentId', 'id'])
- const changed: Array<{ prop: string; before: unknown; after: unknown }> = []
- const allKeys = new Set([...Object.keys(before), ...Object.keys(after)])
- for (const key of allKeys) {
- if (skip.has(key)) continue
- const bStr = JSON.stringify(before[key])
- const aStr = JSON.stringify(after[key])
- if (bStr !== aStr) {
- changed.push({ prop: key, before: before[key], after: after[key] })
- }
- }
- return changed
-}
-
-export function formatDiagnostics(log: ToolDebugLog): string {
- const sections: string[] = []
-
- sections.push(`Total tool calls: ${log.entries.length}`)
- sections.push(`Total result payload: ${(log.totalResultBytes / 1024).toFixed(1)} KB`)
-
- const mutatingCalls = log.entries.filter((e) => e.mutates)
- const errorCalls = log.entries.filter((e) => e.error)
- sections.push(`Mutating calls: ${mutatingCalls.length}`)
- if (errorCalls.length > 0) {
- sections.push(`Errors: ${errorCalls.length}`)
- }
-
- if (log.duplicates.length > 0) {
- sections.push('')
- sections.push('⚠ DUPLICATE CALLS (potential loops):')
- for (const dup of log.duplicates) {
- sections.push(` ${dup.tool} ×${dup.count} — args: ${JSON.stringify(dup.args)}`)
- }
- }
-
- if (log.noopMutations.length > 0) {
- sections.push('')
- sections.push('⚠ NO-OP MUTATIONS (tool succeeded but node unchanged):')
- for (const entry of log.noopMutations) {
- sections.push(` ${entry.tool} on ${String(entry.args.id)}`)
- sections.push(` unchanged: ${entry.unchangedProps?.join(', ')}`)
- if (entry.nodeBefore && entry.unchangedProps) {
- for (const prop of entry.unchangedProps) {
- sections.push(` ${prop} = ${JSON.stringify(entry.nodeBefore[prop])}`)
- }
- }
- }
- }
-
- const largeResults = log.entries
- .map((e, i) => ({ index: i, tool: e.tool, size: JSON.stringify(e.result ?? '').length }))
- .filter((r) => r.size > 2048)
- .sort((a, b) => b.size - a.size)
- .slice(0, 5)
-
- if (largeResults.length > 0) {
- sections.push('')
- sections.push('⚠ LARGE RESULTS (potential token waste):')
- for (const r of largeResults) {
- sections.push(` #${r.index + 1} ${r.tool}: ${(r.size / 1024).toFixed(1)} KB`)
- }
- }
-
- return sections.join('\n')
-}
-
-function formatToolPart(part: Record<string, unknown>): string {
- const inv = part.toolInvocation as JSONObject | undefined
- if (inv) {
- const lines = [` [tool] ${String(inv.toolName)} (${String(inv.state)})`]
- if (inv.args) lines.push(` args: ${JSON.stringify(inv.args)}`)
- if (inv.result !== undefined) lines.push(` result: ${JSON.stringify(inv.result)}`)
- return lines.join('\n')
- }
-
- const name = (typeof part.type === 'string' ? part.type : 'unknown').replace(/^tool-/, '')
- const state = typeof part.state === 'string' ? part.state : '?'
- const lines = [` [tool] ${name} (${state})`]
- if (part.input) lines.push(` input: ${JSON.stringify(part.input)}`)
- if (part.output !== undefined) lines.push(` output: ${JSON.stringify(part.output)}`)
- if (part.errorText) lines.push(` error: ${part.errorText as string}`)
- return lines.join('\n')
-}
-
-function formatMessageStats(messages: UIMessage[]): string {
- let userMessages = 0
- let assistantMessages = 0
- let toolCalls = 0
- let totalTextLength = 0
-
- for (const msg of messages) {
- if (msg.role === 'user') userMessages++
- else if (msg.role === 'assistant') assistantMessages++
- for (const part of msg.parts) {
- const p = part as JSONObject
- if (p.type === 'text') {
- totalTextLength += typeof p.text === 'string' ? p.text.length : 0
- } else if (
- p.type === 'tool-invocation' ||
- p.type === 'dynamic-tool' ||
- p.toolInvocation ||
- (typeof p.type === 'string' && p.type.startsWith('tool-'))
- ) {
- toolCalls++
- totalTextLength += JSON.stringify(p).length
- }
- }
- }
-
- const lines = [
- `Messages: ${messages.length} (${userMessages} user, ${assistantMessages} assistant)`,
- `Tool invocations in messages: ${toolCalls}`,
- `Total text content: ${(totalTextLength / 1024).toFixed(1)} KB (~${Math.ceil(totalTextLength / 4)} tokens approx)`
- ]
- return lines.join('\n')
-}
-
-export function serializeChatLog(messages: UIMessage[], failure?: AIChatFailure | null): string {
- const sections: string[] = []
-
- const toolLog = getToolLogEntries()
- const debugLog = buildDebugLog(toolLog)
-
- sections.push('╔══════════════════════════════════════╗')
- sections.push('║ OPEN PENCIL AI DEBUG LOG ║')
- sections.push(`║ ${new Date().toISOString()} ║`)
- sections.push('╚══════════════════════════════════════╝')
- sections.push('')
-
- sections.push('=== TOKEN USAGE & CACHING ===')
- sections.push(formatTokenUsage())
- sections.push('')
-
- sections.push('=== DIAGNOSTICS ===')
- sections.push(formatDiagnostics(debugLog))
- sections.push('')
-
- sections.push('=== ERRORS ===')
- if (failure) {
- const detail = failure.detail ? `: ${safeFailureDetail(failure.detail)}` : ''
- sections.push(` ${failure.reason}${detail}`)
- } else {
- sections.push(' (none recorded)')
- }
- sections.push('')
-
- sections.push('=== MESSAGE STATS ===')
- sections.push(formatMessageStats(messages))
- sections.push('')
-
- sections.push('=== TOOL EXECUTION LOG ===')
- if (toolLog.length === 0) {
- sections.push(' (no tool calls recorded)')
- } else {
- for (let i = 0; i < toolLog.length; i++) {
- sections.push(formatLogEntry(toolLog[i], i))
- }
- }
- sections.push('')
-
- sections.push('=== CONVERSATION ===')
- for (const msg of messages) {
- const header = `--- ${msg.role.toUpperCase()} (${msg.id}) ---`
- const parts: string[] = []
-
- for (const part of msg.parts) {
- const p = part as JSONObject
- if (p.type === 'text') {
- parts.push(` ${p.text as string}`)
- } else if (p.type === 'reasoning') {
- let reasoning = ''
- if (typeof p.text === 'string') reasoning = p.text
- else if (typeof p.content === 'string') reasoning = p.content
- parts.push(` [reasoning] ${reasoning}`)
- } else if (
- p.type === 'tool-invocation' ||
- p.toolInvocation ||
- (typeof p.type === 'string' && p.type.startsWith('tool-'))
- ) {
- parts.push(formatToolPart(p))
- } else {
- parts.push(` [${typeof p.type === 'string' ? p.type : 'unknown'}] ${JSON.stringify(p)}`)
- }
- }
-
- sections.push(`${header}\n${parts.join('\n')}`)
- }
-
- return sections.join('\n\n')
-}
-
-export function copyChatLog(messages: UIMessage[], failure?: AIChatFailure | null): Promise<void> {
- const text = serializeChatLog(messages, failure)
- return navigator.clipboard.writeText(text)
-}
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.ts
index c16bf9a1a..0cca69030 100644
--- a/src/app/ai/tools/index.ts
+++ b/src/app/ai/tools/index.ts
@@ -7,11 +7,12 @@ import {
isAtomicTool,
toolsToAI
} from '@open-pencil/core/tools'
-import type { StepBudget, ToolLogEntry } from '@open-pencil/core/tools'
+import type { StepBudget } from '@open-pencil/core/tools'
import type { SceneNode } from '@open-pencil/scene-graph'
import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'
import { executeAtomicEditorTool } from '@/app/automation/execution/editor'
+import { recordToolCompleted, type AIDiagnosticContext } from '@/app/diagnostics/events/ai'
import { getActiveEditorStore } from '@/app/editor/active-store'
import type { EditorStore } from '@/app/editor/active-store'
import { ensureGraphFonts } from '@/app/editor/fonts'
@@ -20,7 +21,6 @@ import { useLibraryService } from '@/app/libraries'
export const MAX_AGENT_STEPS = 50
class RunState {
- toolLog: ToolLogEntry[] = []
currentSteps = 0
resetSteps(): void {
@@ -30,11 +30,6 @@ class RunState {
hitLimit(): boolean {
return this.currentSteps >= MAX_AGENT_STEPS
}
-
- clear(): void {
- this.toolLog = []
- this.currentSteps = 0
- }
}
const runStates = new WeakMap<EditorStore, RunState>()
@@ -48,10 +43,6 @@ function getRunState(store?: EditorStore): RunState {
return created
}
-export function getToolLogEntries(store?: EditorStore): ToolLogEntry[] {
- return getRunState(store).toolLog
-}
-
export function recordStep(store?: EditorStore): void {
getRunState(store).currentSteps++
}
@@ -64,11 +55,7 @@ export function didHitStepLimit(store?: EditorStore): boolean {
return getRunState(store).hitLimit()
}
-export function clearToolLogEntries(store?: EditorStore): void {
- getRunState(store).clear()
-}
-
-export function createAITools(store: EditorStore) {
+export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnosticContext) {
let beforeSnapshot: Map<string, SceneNode> | null = null
const runState = getRunState(store)
const libraryService = useLibraryService()
@@ -123,7 +110,15 @@ export function createAITools(store: EditorStore) {
}
},
onToolLog: (entry) => {
- runState.toolLog.push(entry)
+ recordToolCompleted(
+ {
+ tool: entry.tool,
+ durationMs: entry.durationMs,
+ mutates: entry.mutates,
+ failed: Boolean(entry.error)
+ },
+ diagnosticContext
+ )
},
getStepBudget: (): StepBudget => ({
current: runState.currentSteps,
diff --git a/src/app/diagnostics/events/ai.ts b/src/app/diagnostics/events/ai.ts
index 7212f5c38..c8d5343d5 100644
--- a/src/app/diagnostics/events/ai.ts
+++ b/src/app/diagnostics/events/ai.ts
@@ -15,11 +15,20 @@ const modelStepSchema = v.object({
const chatCompletedSchema = v.object({ finishReason: v.nullable(v.string()) })
const chatFailedSchema = v.object({ errorName: v.string() })
+const toolCompletedSchema = v.object({
+ tool: v.string(),
+ durationMs: v.number(),
+ mutates: v.boolean(),
+ failed: v.boolean()
+})
+
+export type AIDiagnosticContext = Pick<DiagnosticEvent, 'sessionId' | 'runId'>
function recordAIEvent(
- name: 'model.step.completed' | 'chat.completed' | 'chat.failed',
+ name: 'model.step.completed' | 'chat.completed' | 'chat.failed' | 'tool.completed',
attributes: Record<string, DiagnosticValue>,
- schema: v.GenericSchema
+ schema: v.GenericSchema,
+ context: AIDiagnosticContext = {}
): void {
const parsed = v.safeParse(schema, attributes)
if (!parsed.success) {
@@ -29,6 +38,7 @@ function recordAIEvent(
if (name === 'model.step.completed' && !isUsageEnabled()) return
const output = parsed.output as Record<string, DiagnosticValue>
recordDiagnostic({
+ ...context,
category: 'ai',
level: name === 'chat.failed' ? 'error' : 'info',
name,
@@ -36,14 +46,30 @@ function recordAIEvent(
} satisfies Omit<DiagnosticEvent, 'id' | 'timestamp'>)
}
-export function recordModelStepCompleted(input: v.InferOutput<typeof modelStepSchema>): void {
- recordAIEvent('model.step.completed', input, modelStepSchema)
+export function recordModelStepCompleted(
+ input: v.InferOutput<typeof modelStepSchema>,
+ context?: AIDiagnosticContext
+): void {
+ recordAIEvent('model.step.completed', input, modelStepSchema, context)
+}
+
+export function recordChatCompleted(
+ input: v.InferOutput<typeof chatCompletedSchema>,
+ context?: AIDiagnosticContext
+): void {
+ recordAIEvent('chat.completed', input, chatCompletedSchema, context)
}
-export function recordChatCompleted(input: v.InferOutput<typeof chatCompletedSchema>): void {
- recordAIEvent('chat.completed', input, chatCompletedSchema)
+export function recordChatFailed(
+ input: v.InferOutput<typeof chatFailedSchema>,
+ context?: AIDiagnosticContext
+): void {
+ recordAIEvent('chat.failed', input, chatFailedSchema, context)
}
-export function recordChatFailed(input: v.InferOutput<typeof chatFailedSchema>): void {
- recordAIEvent('chat.failed', input, chatFailedSchema)
+export function recordToolCompleted(
+ input: v.InferOutput<typeof toolCompletedSchema>,
+ context?: AIDiagnosticContext
+): void {
+ recordAIEvent('tool.completed', input, toolCompletedSchema, context)
}
diff --git a/src/app/document/close/all.ts b/src/app/document/close/all.ts
new file mode 100644
index 000000000..73eb8e627
--- /dev/null
+++ b/src/app/document/close/all.ts
@@ -0,0 +1,37 @@
+import type { ClosableDocument } from './controller'
+import { requestDocumentClose } from './prompt'
+
+interface OpenDocument extends ClosableDocument {
+ state: { documentName: string }
+ persistRecoveryNow(): Promise<void>
+ discardRecovery(): Promise<void>
+}
+
+export async function confirmAllDocuments(
+ getDocuments: () => OpenDocument[],
+ confirm: typeof requestDocumentClose = requestDocumentClose
+): Promise<boolean> {
+ const documents = getDocuments()
+ const discarded = new Set<OpenDocument>()
+ function canClose() {
+ const current = getDocuments()
+ return (
+ current.length === documents.length &&
+ current.every(
+ (document) =>
+ documents.includes(document) && (discarded.has(document) || !document.hasUnsavedChanges())
+ )
+ )
+ }
+ for (const document of documents) {
+ const choice = await confirm(document, document.state.documentName)
+ if (choice === 'cancel') return false
+ if (choice === 'discard') discarded.add(document)
+ }
+ if (!canClose()) return false
+ for (const document of documents) {
+ if (discarded.has(document)) await document.discardRecovery()
+ else await document.persistRecoveryNow()
+ }
+ return canClose()
+}
diff --git a/src/app/document/close/controller.ts b/src/app/document/close/controller.ts
new file mode 100644
index 000000000..d09da33c0
--- /dev/null
+++ b/src/app/document/close/controller.ts
@@ -0,0 +1,18 @@
+export type CloseChoice = 'save' | 'discard' | 'cancel'
+export type CloseResult = 'saved' | 'discard' | 'cancel'
+
+export interface ClosableDocument {
+ hasUnsavedChanges(): boolean
+ saveFigFile(): Promise<boolean>
+}
+
+export async function confirmDocumentClose(
+ document: ClosableDocument,
+ choose: () => Promise<CloseChoice>
+): Promise<CloseResult> {
+ if (!document.hasUnsavedChanges()) return 'saved'
+ const choice = await choose()
+ if (choice !== 'save') return choice
+ const saved = await document.saveFigFile()
+ return saved && !document.hasUnsavedChanges() ? 'saved' : 'cancel'
+}
diff --git a/src/app/document/close/exit.ts b/src/app/document/close/exit.ts
new file mode 100644
index 000000000..eb0c84ed6
--- /dev/null
+++ b/src/app/document/close/exit.ts
@@ -0,0 +1,41 @@
+import { prepareForClose } from '@/app/tabs'
+
+/** Shared approval so the window close handler and the Quit item cannot prompt twice. */
+export function createExitApproval(confirmDocuments: () => Promise<boolean>) {
+ let approved = false
+ let confirmation: Promise<boolean> | null = null
+
+ return {
+ isApproved: () => approved,
+ confirm: async (): Promise<boolean> => {
+ if (approved) return true
+ confirmation ??= confirmDocuments()
+ .then((agreed) => {
+ if (agreed) approved = true
+ return agreed
+ })
+ .finally(() => {
+ confirmation = null
+ })
+ return confirmation
+ }
+ }
+}
+
+const approval = createExitApproval(prepareForClose)
+
+/** True once every open document agreed to close, so later requests skip the prompt. */
+export function isExitApproved(): boolean {
+ return approval.isApproved()
+}
+
+export function confirmAppExit(): Promise<boolean> {
+ return approval.confirm()
+}
+
+/** Shared by the native Quit item and the platform exit request. */
+export async function requestAppExit(): Promise<void> {
+ if (!(await confirmAppExit())) return
+ const { exit } = await import('@tauri-apps/plugin-process')
+ await exit(0)
+}
diff --git a/src/app/document/close/native.ts b/src/app/document/close/native.ts
new file mode 100644
index 000000000..45f890159
--- /dev/null
+++ b/src/app/document/close/native.ts
@@ -0,0 +1,28 @@
+import { message } from '@tauri-apps/plugin-dialog'
+import type { MessageDialogOptions, MessageDialogResult } from '@tauri-apps/plugin-dialog'
+
+import { commonMessages, filesMessages } from '@open-pencil/vue'
+
+import type { CloseChoice } from './controller'
+
+export type NativeMessageDialog = (
+ message: string,
+ options?: MessageDialogOptions
+) => Promise<MessageDialogResult>
+
+/** Desktop uses the platform alert so the choice matches the rest of the operating system. */
+export async function chooseNativeDocumentClose(
+ documentName: string,
+ show: NativeMessageDialog = message
+): Promise<CloseChoice> {
+ const files = filesMessages.get()
+ const common = commonMessages.get()
+ const result = await show(files.saveBeforeClosingDescription, {
+ title: files.saveBeforeClosing({ name: documentName }),
+ kind: 'warning',
+ buttons: { yes: common.save, no: files.discard, cancel: common.cancel }
+ })
+ if (result === common.save) return 'save'
+ if (result === files.discard) return 'discard'
+ return 'cancel'
+}
diff --git a/src/app/document/close/prompt.ts b/src/app/document/close/prompt.ts
new file mode 100644
index 000000000..e8b965076
--- /dev/null
+++ b/src/app/document/close/prompt.ts
@@ -0,0 +1,36 @@
+import { shallowRef } from 'vue'
+
+import { IS_TAURI } from '@/constants'
+
+import { confirmDocumentClose, type ClosableDocument, type CloseChoice } from './controller'
+
+export const closePrompt = shallowRef<{ documentName: string } | null>(null)
+let resolvePrompt: ((choice: CloseChoice) => void) | null = null
+let pending = Promise.resolve()
+
+export function answerClosePrompt(choice: CloseChoice): void {
+ const resolve = resolvePrompt
+ resolvePrompt = null
+ closePrompt.value = null
+ resolve?.(choice)
+}
+
+export function requestDocumentClose(document: ClosableDocument, documentName: string) {
+ const result = pending.then(() =>
+ confirmDocumentClose(document, async () => {
+ if (IS_TAURI) {
+ const { chooseNativeDocumentClose } = await import('./native')
+ return chooseNativeDocumentClose(documentName)
+ }
+ return new Promise<CloseChoice>((resolve) => {
+ resolvePrompt = resolve
+ closePrompt.value = { documentName }
+ })
+ })
+ )
+ pending = result.then(
+ () => undefined,
+ () => undefined
+ )
+ return result
+}
diff --git a/src/app/document/close/use.ts b/src/app/document/close/use.ts
new file mode 100644
index 000000000..f97deed39
--- /dev/null
+++ b/src/app/document/close/use.ts
@@ -0,0 +1,63 @@
+import { useEventListener } from '@vueuse/core'
+import { onMounted, onScopeDispose } from 'vue'
+
+import { confirmAppExit, isExitApproved } from '@/app/document/close/exit'
+import { notificationMessages } from '@/app/i18n/notifications'
+import { toast } from '@/app/shell/ui'
+import { allTabs } from '@/app/tabs'
+import { IS_TAURI } from '@/constants'
+
+export function useDocumentCloseProtection() {
+ let closing = false
+ let disposed = false
+ const cleanup: Array<() => void> = []
+
+ useEventListener(window, 'beforeunload', (event) => {
+ if (isExitApproved() || !allTabs.value.some((tab) => tab.isDirty)) return
+ event.preventDefault()
+ event.returnValue = ''
+ })
+
+ async function requestClose(close: () => Promise<void>) {
+ if (closing) return
+ closing = true
+ try {
+ if (!(await confirmAppExit())) return
+ await close()
+ } catch (error) {
+ toast.error(
+ notificationMessages.get().operationFailed({
+ error: error instanceof Error ? error.message : String(error)
+ })
+ )
+ } finally {
+ closing = false
+ }
+ }
+
+ function registerCleanup(unsubscribe: () => void) {
+ if (disposed) unsubscribe()
+ else cleanup.push(unsubscribe)
+ }
+
+ onMounted(async () => {
+ if (!IS_TAURI) return
+ const { getCurrentWindow } = await import('@tauri-apps/api/window')
+ if (disposed) return
+ const window = getCurrentWindow()
+ await window
+ .onCloseRequested((event) => {
+ // Always intercept: Tauri destroys the window implicitly when a handler returns
+ // without preventing, which would bypass the prompt after approval.
+ event.preventDefault()
+ if (isExitApproved()) return
+ void requestClose(() => window.destroy())
+ })
+ .then(registerCleanup)
+ })
+
+ onScopeDispose(() => {
+ disposed = true
+ for (const unsubscribe of cleanup) unsubscribe()
+ })
+}
diff --git a/src/app/document/io/changes.ts b/src/app/document/io/changes.ts
new file mode 100644
index 000000000..1be80893b
--- /dev/null
+++ b/src/app/document/io/changes.ts
@@ -0,0 +1,33 @@
+import { computed, ref } from 'vue'
+
+import type { Editor } from '@open-pencil/core/editor'
+
+/** Content-only revisions: viewport repainting and recovery never mark a document saved. */
+export function createDocumentChanges(editor: Editor) {
+ const revision = ref(0)
+ const savedRevision = ref(0)
+ const dirty = computed(() => revision.value !== savedRevision.value)
+ const changed = () => {
+ revision.value++
+ }
+ const unsubscribers = [
+ editor.onEditorEvent('node:created', changed),
+ editor.onEditorEvent('node:updated', changed),
+ editor.onEditorEvent('node:deleted', changed),
+ editor.onEditorEvent('node:reparented', changed),
+ editor.onEditorEvent('node:reordered', changed),
+ editor.onEditorEvent('graph:replaced', changed),
+ editor.onEditorEvent('history:changed', changed)
+ ]
+ return {
+ hasUnsavedChanges: () => dirty.value,
+ capture: () => revision.value,
+ markSaved: (version = revision.value) => {
+ savedRevision.value = version
+ },
+ markChanged: changed,
+ dispose: () => {
+ for (const unsubscribe of unsubscribers) unsubscribe()
+ }
+ }
+}
diff --git a/src/app/document/io/create.ts b/src/app/document/io/create.ts
index fad2baf70..cf75a43bb 100644
--- a/src/app/document/io/create.ts
+++ b/src/app/document/io/create.ts
@@ -29,7 +29,10 @@ export function createDocumentIOActions(
state,
getFilePath: sourceState.getFilePath,
getFileHandle: sourceState.getFileHandle,
- setSavedVersion: sourceState.setSavedVersion,
+ setSavedVersion: (version) => {
+ sourceState.setSavedVersion(version)
+ sourceActions.markDocumentSaved()
+ },
preparationController
})
const { startWatchingFile, stopWatchingFile } = createFileWatcher({
@@ -86,6 +89,7 @@ export function createDocumentIOActions(
openFigFile,
openDOMFile,
importDOMText,
+ hasUnsavedChanges: sourceActions.hasUnsavedChanges,
saveFigFile: sourceActions.saveFigFile,
saveFigFileAs: sourceActions.saveFigFileAs
}
diff --git a/src/app/document/io/save.ts b/src/app/document/io/save.ts
index 3036e7af1..60be4128d 100644
--- a/src/app/document/io/save.ts
+++ b/src/app/document/io/save.ts
@@ -60,13 +60,15 @@ export function createSaveActions({
const { data, version } = await buildVersionedFigFile()
const wrote = await writeFile(data, version)
if (wrote && !storageBinding) setSourceIdentity({ handle: fileHandle, path: filePath })
- } else if (downloadName) {
+ return wrote
+ }
+ if (downloadName) {
const { data, version } = await buildVersionedFigFile()
downloadBlob(new Uint8Array(data), downloadName, 'application/octet-stream')
await onDownloadSuccess?.(version)
- } else {
- await saveFigFileAs()
+ return true
}
+ return saveFigFileAs()
}
async function saveFigFileAs() {
@@ -74,35 +76,38 @@ export function createSaveActions({
if (IS_TAURI) {
const path = await chooseTauriFigSavePath()
- if (!path) return
+ if (!path) return false
setStorageBinding(null)
setFilePath(path)
setFileHandle(null)
state.documentName = documentNameFromFigPath(path)
- if (await writeFile(data, version)) setSourceIdentity({ handle: null, path })
+ const wrote = await writeFile(data, version)
+ if (wrote) setSourceIdentity({ handle: null, path })
startWatchingFile()
- return
+ return wrote
}
if (window.showSaveFilePicker) {
const handle = await chooseBrowserFigSaveHandle()
- if (!handle) return
+ if (!handle) return false
setStorageBinding(null)
setFileHandle(handle)
setFilePath(null)
state.documentName = documentNameFromFigPath(handle.name)
- if (await writeFile(data, version)) setSourceIdentity({ handle, path: null })
+ const wrote = await writeFile(data, version)
+ if (wrote) setSourceIdentity({ handle, path: null })
startWatchingFile()
- return
+ return wrote
}
const filename = prompt(filesMessages.get().saveAsPrompt, getDownloadName() ?? 'Untitled.fig')
- if (!filename) return
+ if (!filename) return false
setStorageBinding(null)
setDownloadName(filename)
state.documentName = documentNameFromFigPath(filename)
downloadBlob(new Uint8Array(data), filename, 'application/octet-stream')
await onDownloadSuccess?.(version)
+ return true
}
return { saveFigFile, saveFigFileAs, writeFile }
diff --git a/src/app/document/io/source.ts b/src/app/document/io/source.ts
index 4eee6010b..0cf0dd115 100644
--- a/src/app/document/io/source.ts
+++ b/src/app/document/io/source.ts
@@ -2,6 +2,7 @@ import type { Editor, EditorState } from '@open-pencil/core/editor'
import { exportFigFile } from '@open-pencil/core/io/formats/fig'
import { createAutosave } from '@/app/document/autosave'
+import { createDocumentChanges } from '@/app/document/io/changes'
import {
documentNameFromFigPath,
downloadNameFromPath,
@@ -48,6 +49,15 @@ export function createDocumentSourceActions({
setLastWriteTime,
getRenderer
}: DocumentSourceOptions) {
+ const changes = createDocumentChanges(editor)
+
+ async function saveAndTrack(save: () => Promise<boolean>) {
+ const revision = changes.capture()
+ const saved = await save()
+ if (saved) changes.markSaved(revision)
+ return saved
+ }
+
function buildFigFile() {
const renderer = getRenderer()
return exportFigFile(editor.graph, renderer?.ck, renderer ?? undefined, state.currentPageId)
@@ -90,8 +100,9 @@ export function createDocumentSourceActions({
getSavedVersion,
hasWritableSource: () => !!getFileHandle() || !!getFilePath() || !!getStorageBinding(),
saveCurrentDocument: async (version) => {
+ const revision = changes.capture()
const data = await buildFigFile()
- await writeFile(data, version)
+ if (await writeFile(data, version)) changes.markSaved(revision)
}
})
@@ -109,6 +120,7 @@ export function createDocumentSourceActions({
setDownloadName(figDownloadName(fileName, sourceFormat))
setSourceIdentity({ handle: handle ?? null, path: path ?? null })
setSavedVersion(state.sceneVersion)
+ changes.markSaved()
void recovery.markProtectedVersion(state.sceneVersion)
if (isFig && (handle || path)) {
void startWatchingFile()
@@ -125,6 +137,7 @@ export function createDocumentSourceActions({
state.documentName = documentName
state.autosaveEnabled = true
setSavedVersion(state.sceneVersion)
+ changes.markSaved()
void recovery.markProtectedVersion(state.sceneVersion)
}
@@ -143,6 +156,7 @@ export function createDocumentSourceActions({
}
function disposeDocumentIO() {
+ changes.dispose()
stopWatchingFile()
autosave.disposeAutosave()
recovery.disposeRecovery()
@@ -154,12 +168,16 @@ export function createDocumentSourceActions({
setPlannedFilePath,
startWatchingCurrentFile,
disposeDocumentIO,
- saveFigFile,
- saveFigFileAs,
+ saveFigFile: () => saveAndTrack(saveFigFile),
+ saveFigFileAs: () => saveAndTrack(saveFigFileAs),
+ hasUnsavedChanges: changes.hasUnsavedChanges,
+ markDocumentSaved: changes.markSaved,
getStorageBinding,
getRecoveryId: () => recovery.getRecoveryId(),
- adoptRecoverySnapshot: (id: string, version: number) =>
- recovery.adoptRecoverySnapshot(id, version),
+ adoptRecoverySnapshot: (id: string, version: number) => {
+ changes.markChanged()
+ return recovery.adoptRecoverySnapshot(id, version)
+ },
persistRecoveryNow: () => recovery.persistNow(),
discardRecovery: () => recovery.discardRecovery()
}
diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.ts
index 4f5159111..4e898c58d 100644
--- a/src/app/editor/session/modules.ts
+++ b/src/app/editor/session/modules.ts
@@ -75,6 +75,7 @@ export function createEditorStoreModules(
importDOMText: documentIO.importDOMText,
setViewportSize: documentIO.setViewportSize,
fitCurrentPageToViewport: documentIO.fitCurrentPageToViewport,
+ hasUnsavedChanges: documentIO.hasUnsavedChanges,
saveFigFile: documentIO.saveFigFile,
saveFigFileAs: documentIO.saveFigFileAs,
getDocumentFilePath: documentIO.getDocumentFilePath,
diff --git a/src/app/settings/credentials/media.ts b/src/app/settings/credentials/media.ts
index 0799c10a0..d624d2dd0 100644
--- a/src/app/settings/credentials/media.ts
+++ b/src/app/settings/credentials/media.ts
@@ -3,12 +3,22 @@ import { ref } from 'vue'
import { setPexelsAPIKey, setUnsplashAccessKey } from '@open-pencil/core/tools'
import { appCredentialServices } from './app'
-import { initializeCredentialMigration, PEXELS_CREDENTIAL, UNSPLASH_CREDENTIAL } from './migration'
+import {
+ hasLegacyCredential,
+ initializeCredentialMigration,
+ PEXELS_CREDENTIAL,
+ UNSPLASH_CREDENTIAL
+} from './migration'
import { setAppCredentialPersistence } from './persistence'
import type { CredentialRef, CredentialStatus } from './types'
export const credentialPersistenceRevision = ref(0)
async function refreshStatus(reference: CredentialRef): Promise<CredentialStatus> {
- return appCredentialServices.manager.status(reference)
+ const status = await appCredentialServices.manager.status(reference)
+ return status === 'missing' && hasLegacyCredential(reference) ? 'configured' : status
+}
+async function resolveMediaCredential(reference: CredentialRef): Promise<string | null> {
+ await initializeCredentialMigration()
+ return appCredentialServices.resolver.resolve(reference)
}
export const pexelsKeyStatus = ref<CredentialStatus>('missing')
export const unsplashKeyStatus = ref<CredentialStatus>('missing')
@@ -20,29 +30,33 @@ export async function refreshMediaCredentials(): Promise<void> {
pexelsKeyStatus.value = pexelsStatus
unsplashKeyStatus.value = unsplashStatus
setPexelsAPIKey(
- pexelsStatus === 'configured'
- ? await appCredentialServices.resolver.resolve(PEXELS_CREDENTIAL)
- : null
+ pexelsStatus === 'configured' ? () => resolveMediaCredential(PEXELS_CREDENTIAL) : null
)
setUnsplashAccessKey(
- unsplashStatus === 'configured'
- ? await appCredentialServices.resolver.resolve(UNSPLASH_CREDENTIAL)
- : null
+ unsplashStatus === 'configured' ? () => resolveMediaCredential(UNSPLASH_CREDENTIAL) : null
)
}
-export async function setPexelsKey(key: string): Promise<void> {
+async function setMediaKey(reference: CredentialRef, key: string): Promise<CredentialStatus> {
+ // Migrate first so clearing also removes a value that only exists in legacy storage.
+ await initializeCredentialMigration()
const value = key.trim()
- if (value) await appCredentialServices.manager.set(PEXELS_CREDENTIAL, value)
- else await appCredentialServices.manager.clear(PEXELS_CREDENTIAL)
- pexelsKeyStatus.value = await refreshStatus(PEXELS_CREDENTIAL)
- setPexelsAPIKey(value || null)
+ if (value) await appCredentialServices.manager.set(reference, value)
+ else await appCredentialServices.manager.clear(reference)
+ return refreshStatus(reference)
+}
+export async function setPexelsKey(key: string): Promise<void> {
+ pexelsKeyStatus.value = await setMediaKey(PEXELS_CREDENTIAL, key)
+ setPexelsAPIKey(
+ pexelsKeyStatus.value === 'configured' ? () => resolveMediaCredential(PEXELS_CREDENTIAL) : null
+ )
}
export async function setUnsplashKey(key: string): Promise<void> {
- const value = key.trim()
- if (value) await appCredentialServices.manager.set(UNSPLASH_CREDENTIAL, value)
- else await appCredentialServices.manager.clear(UNSPLASH_CREDENTIAL)
- unsplashKeyStatus.value = await refreshStatus(UNSPLASH_CREDENTIAL)
- setUnsplashAccessKey(value || null)
+ unsplashKeyStatus.value = await setMediaKey(UNSPLASH_CREDENTIAL, key)
+ setUnsplashAccessKey(
+ unsplashKeyStatus.value === 'configured'
+ ? () => resolveMediaCredential(UNSPLASH_CREDENTIAL)
+ : null
+ )
}
export async function setRememberCredentials(remembered: boolean): Promise<void> {
await initializeCredentialMigration()
diff --git a/src/app/settings/credentials/migration.ts b/src/app/settings/credentials/migration.ts
index 635c3d236..0beb60342 100644
--- a/src/app/settings/credentials/migration.ts
+++ b/src/app/settings/credentials/migration.ts
@@ -1,7 +1,7 @@
import { AI_PROVIDERS, type AIProviderID } from '@open-pencil/core/constants'
import { appCredentialStore } from '@/app/settings/credentials/app'
-import { credentialRef } from '@/app/settings/credentials/reference'
+import { credentialKey, credentialRef } from '@/app/settings/credentials/reference'
import { browserCredentialStorage } from '@/app/settings/credentials/storage'
import type { CredentialRef, CredentialStore } from '@/app/settings/credentials/types'
@@ -48,6 +48,18 @@ function legacyCredentials(storage: Storage): LegacyCredential[] {
return credentials
}
+export function hasLegacyCredential(
+ reference: CredentialRef,
+ storage = browserCredentialStorage()
+): boolean {
+ if (!storage || storage.getItem(MIGRATION_VERSION_KEY) === MIGRATION_VERSION) return false
+ return legacyCredentials(storage).some(
+ (entry) =>
+ credentialKey(entry.reference) === credentialKey(reference) &&
+ Boolean(storage.getItem(entry.storageKey)?.trim())
+ )
+}
+
export async function migrateLegacyCredentials(
storage: Storage,
store: CredentialStore
@@ -70,8 +82,29 @@ export async function migrateLegacyCredentials(
return true
}
-export async function initializeCredentialMigration(): Promise<boolean> {
- const storage = browserCredentialStorage()
+const migrationsInFlight = new WeakMap<Storage, Promise<boolean>>()
+let migrationQueue: Promise<void> = Promise.resolve()
+
+/** Migrations share one destination store, so distinct sources must not interleave. */
+function enqueueMigration(storage: Storage): Promise<boolean> {
+ const migration = migrationQueue.then(() => migrateLegacyCredentials(storage, appCredentialStore))
+ migrationQueue = migration.then(
+ () => undefined,
+ () => undefined
+ )
+ return migration
+}
+
+export async function initializeCredentialMigration(
+ storage = browserCredentialStorage()
+): Promise<boolean> {
if (!storage) return true
- return migrateLegacyCredentials(storage, appCredentialStore)
+ let migration = migrationsInFlight.get(storage)
+ if (!migration) {
+ migration = enqueueMigration(storage).finally(() => {
+ migrationsInFlight.delete(storage)
+ })
+ migrationsInFlight.set(storage, migration)
+ }
+ return migration
}
diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.ts
index 9aaffe2b4..4522d57a7 100644
--- a/src/app/shell/menu/schema.ts
+++ b/src/app/shell/menu/schema.ts
@@ -409,3 +409,15 @@ export const APP_MENU_SCHEMA = [
]
}
] satisfies AppMenuGroupSchema[]
+
+/**
+ * Custom entries in the macOS application menu.
+ *
+ * Placement stays in Rust because the OS-predefined items (About, Services, Hide)
+ * sit between them. Only the labels and accelerators are shared here.
+ */
+export const APP_MENU_APP_ITEMS = [
+ { id: 'about', label: 'About OpenPencil' },
+ { id: 'check-updates', label: 'Check for Updates…' },
+ { id: 'quit', label: 'Quit OpenPencil', shortcut: 'MOD+Q' }
+] satisfies AppMenuActionItem[]
diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.ts
index 30f58d2b0..9743544e6 100644
--- a/src/app/shell/menu/shell.ts
+++ b/src/app/shell/menu/shell.ts
@@ -1,5 +1,6 @@
import { useI18n } from '@open-pencil/vue'
+import { requestAppExit } from '@/app/document/close/exit'
import { openSettingsDialog } from '@/app/settings/dialog'
import { setSnappingPreference } from '@/app/settings/preferences/apply'
import { syncNativeSnappingMenu } from '@/app/settings/preferences/native-menu'
@@ -20,8 +21,10 @@ function shellMenuIds(entries: readonly AppMenuEntry[]): string[] {
export const SHELL_MENU_IDS = new Set([
...APP_MENU_SCHEMA.flatMap((group) => shellMenuIds(group.items)),
- // The macOS application menu is native-only and is not part of the shared schema.
- 'check-updates'
+ // The macOS application menu is native-only; its custom entries come from
+ // APP_MENU_APP_ITEMS while the OS-predefined ones stay in Rust.
+ 'check-updates',
+ 'quit'
])
export function useShellMenu() {
@@ -53,7 +56,8 @@ export function useShellMenu() {
'theme-light': () => setTheme('light'),
'theme-dark': () => setTheme('dark'),
'theme-auto': () => setTheme('auto'),
- 'check-updates': () => void checkForAppUpdate({ messages: updates })
+ 'check-updates': () => void checkForAppUpdate({ messages: updates }),
+ quit: () => void requestAppExit()
}
useNativeMenuEvents((id) => actions[id]?.())
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index b6fe3ae92..2cc7cf854 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -10,6 +10,8 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { setOpenPencilStore } from '@/app/browser-bridge'
import { describeDiagnosticError, recordStorageFailure } from '@/app/diagnostics'
+import { confirmAllDocuments } from '@/app/document/close/all'
+import { requestDocumentClose } from '@/app/document/close/prompt'
import { readFigDocument } from '@/app/document/io/fig'
import { applyImportedDocument } from '@/app/document/io/imported-document'
import type { DocumentSourceIdentity } from '@/app/document/io/types'
@@ -64,6 +66,7 @@ export const allTabs = computed(() =>
id: t.id,
name: t.store.state.documentName,
isHome: t.kind === 'home',
+ isDirty: t.kind === 'document' && t.store.hasUnsavedChanges(),
isPreparing: t.store.state.preparation !== null,
preparationProgress: t.store.state.preparation?.progress ?? null,
isActive: t.id === activeTabId.value
@@ -154,11 +157,16 @@ export async function closeTab(tabId: string): Promise<void> {
const closingTab = tabsRef.value[idx]
if (closingTab.kind === 'home' && tabsRef.value.length === 1) return
+ const choice = await requestDocumentClose(closingTab.store, closingTab.store.state.documentName)
+ if (choice === 'cancel') return
+ if (choice === 'discard') await closingTab.store.discardRecovery()
+ else await closingTab.store.persistRecoveryNow()
+ if (!tabsRef.value.includes(closingTab)) return
+ if (choice !== 'discard' && closingTab.store.hasUnsavedChanges()) return
const wasActive = activeTabId.value === tabId
coverThumbnailListeners.get(closingTab.store)?.()
coverThumbnailListeners.delete(closingTab.store)
closingTab.store.preparationController.dispose()
- await closingTab.store.persistRecoveryNow()
closingTab.store.dispose()
tabsRef.value = tabsRef.value.filter((t) => t.id !== tabId)
@@ -539,6 +547,12 @@ export async function restoreRecoverySnapshot(id: string): Promise<void> {
}
}
+export function prepareForClose(): Promise<boolean> {
+ return confirmAllDocuments(() =>
+ tabsRef.value.filter((tab) => tab.kind === 'document').map((tab) => tab.store)
+ )
+}
+
export async function prepareForReload(): Promise<void> {
await Promise.all(tabsRef.value.map((tab) => tab.store.persistRecoveryNow()))
}
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index 8dc5920da..19cb502fa 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -1,19 +1,15 @@
<script setup lang="ts">
import type { Chat } from '@ai-sdk/vue'
-import { useClipboard } from '@vueuse/core'
import type { UIMessage } from 'ai'
-import { computed, markRaw, ref, shallowRef, watch } from 'vue'
+import { computed, shallowRef, watch } from 'vue'
import { useI18n } from '@open-pencil/vue'
-import { getACPDebugText, hasACPDebugEntries } from '@/app/ai/acp/transport'
import { chatDocumentId } from '@/app/ai/chat/history/document'
import { useChatSubmission } from '@/app/ai/chat/submission/use'
import { useAIChat } from '@/app/ai/chat/use'
-import { copyChatLog } from '@/app/ai/debug'
import { didHitStepLimit } from '@/app/ai/tools'
import { getActiveEditorStore } from '@/app/editor/active-store'
-import { useNotificationMessages } from '@/app/i18n/notifications'
import { openSettingsDialog } from '@/app/settings/dialog'
import { toast } from '@/app/shell/ui'
import { activeTab } from '@/app/tabs'
@@ -23,12 +19,8 @@ import ChatInput from '@/components/chat/ChatInput.vue'
import ChatTranscript from '@/components/chat/ChatTranscript.vue'
import ProviderSetup from '@/components/chat/ProviderSetup.vue'
-const IS_DEV = import.meta.env.DEV
-
const { isConfigured, ensureChat, history, chatFailure, clearChatFailure } = useAIChat()
-const { copy } = useClipboard()
const { ai } = useI18n()
-const notifications = useNotificationMessages()
const chat = shallowRef<Chat<UIMessage> | null>(null)
const submission = useChatSubmission({
@@ -47,19 +39,10 @@ const submission = useChatSubmission({
})
let viewGeneration = 0
-const initialGeneration = ++viewGeneration
-void ensureChat()
- .then((c) => {
- if (c && initialGeneration === viewGeneration) chat.value = markRaw(c)
- return undefined
- })
- .catch((error: unknown) => {
- toast.error(
- notifications.value.chatInitializationFailed({
- error: error instanceof Error ? error.message : String(error)
- })
- )
- })
+// Restoring local history must not open a provider connection or read credentials.
+void history.initialize().catch(() => {
+ toast.error(ai.value.chatHistoryFailed)
+})
const messages = computed(() => chat.value?.messages ?? history.messages.value)
const historyOptions = computed(() => {
@@ -82,8 +65,6 @@ async function historyAction(action: () => Promise<unknown>) {
await action()
if (generation !== viewGeneration) return
chat.value = null
- const next = await ensureChat()
- if (generation === viewGeneration) chat.value = next ? markRaw(next) : null
} catch {
toast.error(ai.value.chatHistoryFailed)
}
@@ -159,9 +140,6 @@ watch(
chat.value = null
try {
await history.initialize()
- if (generation !== viewGeneration) return
- const nextChat = await ensureChat()
- if (generation === viewGeneration) chat.value = nextChat ? markRaw(nextChat) : null
} catch {
if (generation === viewGeneration) toast.error(ai.value.chatHistoryFailed)
}
@@ -171,36 +149,12 @@ watch(
function handleStop() {
submission.stop()
}
-
-const diagnosticNotice = ref('')
-async function copyDiagnostics(operation: () => Promise<void>) {
- diagnosticNotice.value = ''
- try {
- await operation()
- diagnosticNotice.value = ai.value.diagnosticCopied
- } catch {
- diagnosticNotice.value = ai.value.diagnosticCopyFailed
- }
-}
-async function handleCopyDebug() {
- await copyDiagnostics(() => copyChatLog(messages.value, chatFailure.value))
-}
-
-async function handleCopyACPLog() {
- const text = getACPDebugText()
- if (!text) return
- await copyDiagnostics(() => copy(text))
-}
</script>
<template>
<div data-test-id="chat-panel" class="flex min-w-0 flex-1 flex-col overflow-hidden select-text">
<ChatHistory
:saved="history.conversations.value.some((row) => row.id === history.current.value?.id)"
- :debug="true"
- :acp-debug="IS_DEV && hasACPDebugEntries()"
- @copy-debug="handleCopyDebug"
- @copy-a-c-p-debug="handleCopyACPLog"
:conversations="historyOptions"
:selected-id="history.current.value?.id"
:disabled="history.busy.value"
@@ -209,9 +163,6 @@ async function handleCopyACPLog() {
@rename="renameConversation"
@delete="historyAction(() => history.remove($event))"
/>
- <p v-if="diagnosticNotice" role="status" class="px-3 py-2 text-xs text-muted">
- {{ diagnosticNotice }}
- </p>
<p v-if="history.storageError.value" role="alert" class="px-3 py-2 text-xs text-red-400">
{{ ai.chatStorageFailed }}
</p>
diff --git a/src/components/TabBar.vue b/src/components/TabBar.vue
index c39be4d20..09aa8b198 100644
--- a/src/components/TabBar.vue
+++ b/src/components/TabBar.vue
@@ -61,11 +61,15 @@ function onClose(e: MouseEvent, tabId: string) {
data-test-id="tabbar-tab"
:class="tabBarStyles({ active: tab.isActive }).trigger()"
:data-active="tab.isActive || undefined"
+ :data-dirty="tab.isDirty || undefined"
>
<icon-lucide-house v-if="tab.isHome" :class="baseStyles.icon()" />
<PreparationIndicator v-else-if="tab.isPreparing" :progress="tab.preparationProgress" />
<icon-lucide-file v-else :class="baseStyles.icon()" />
<span :class="baseStyles.label()">{{ tab.isHome ? files.newTab : tab.name }}</span>
+ <Tip v-if="tab.isDirty" :label="files.unsavedChanges">
+ <span role="img" :aria-label="files.unsavedChanges" :class="baseStyles.dirtyDot()" />
+ </Tip>
</TabsTrigger>
<Tip
v-if="!tab.isHome || tabs.length > 1"
diff --git a/src/components/chat/ChatHistory.vue b/src/components/chat/ChatHistory.vue
index e5a279232..660b40586 100644
--- a/src/components/chat/ChatHistory.vue
+++ b/src/components/chat/ChatHistory.vue
@@ -9,8 +9,7 @@ import {
DropdownMenuTrigger,
DropdownMenuPortal,
DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator
+ DropdownMenuItem
} from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, nextTick, ref, watch } from 'vue'
@@ -28,24 +27,18 @@ const {
conversations,
selectedId,
disabled = false,
- saved = false,
- debug = false,
- acpDebug = false
+ saved = false
} = defineProps<{
conversations: { id: string; title: string; documentName: string; available: boolean }[]
selectedId?: string
disabled?: boolean
saved?: boolean
- debug?: boolean
- acpDebug?: boolean
}>()
const emit = defineEmits<{
select: [id: string]
create: []
rename: [id: string, title: string]
delete: [id: string]
- copyDebug: []
- copyACPDebug: []
}>()
const { ai } = useI18n()
const triggerClass = tv(iconButtonTheme)({ size: 'sm' })
@@ -190,13 +183,6 @@ function closeMenu(event: Event) {
<DropdownMenuItem :class="item" @select="confirmDelete">{{
ai.deleteChat
}}</DropdownMenuItem>
- <DropdownMenuSeparator v-if="debug" class="my-1 border-t border-border" />
- <DropdownMenuItem v-if="debug" :class="item" @select="emit('copyDebug')">{{
- ai.copyDiagnosticLog
- }}</DropdownMenuItem>
- <DropdownMenuItem v-if="acpDebug" :class="item" @select="emit('copyACPDebug')">{{
- ai.copyACPLog
- }}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenuPortal>
</DropdownMenuRoot>
diff --git a/src/components/chat/ChatPlayground.stories.ts b/src/components/chat/ChatPlayground.stories.ts
index 4ed96e75a..71b79065d 100644
--- a/src/components/chat/ChatPlayground.stories.ts
+++ b/src/components/chat/ChatPlayground.stories.ts
@@ -53,7 +53,6 @@ const meta = {
</fieldset>
<section aria-label="Chat preview" :data-narrow="args.narrow" class="flex h-[620px] w-[420px] max-w-full flex-col overflow-hidden rounded-xl border border-border bg-panel data-[narrow=true]:w-[300px]">
<ChatHistory
- :debug="true"
:saved="hasSavedConversation"
:conversations="conversationOptions"
:selected-id="selectedId"
diff --git a/src/components/document/UnsavedChangesDialog.vue b/src/components/document/UnsavedChangesDialog.vue
new file mode 100644
index 000000000..22dcc4cc2
--- /dev/null
+++ b/src/components/document/UnsavedChangesDialog.vue
@@ -0,0 +1,64 @@
+<script setup lang="ts">
+import { useStore } from '@nanostores/vue'
+import { useFocus } from '@vueuse/core'
+import { useTemplateRef } from 'vue'
+
+import { commonMessages, filesMessages } from '@open-pencil/vue'
+
+import { answerClosePrompt, closePrompt } from '@/app/document/close/prompt'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppAlertDialogRoot from '@/components/ui/dialog/AppAlertDialogRoot.vue'
+import AppDialogFooter from '@/components/ui/dialog/AppDialogFooter.vue'
+import AppDialogHeader from '@/components/ui/dialog/AppDialogHeader.vue'
+import { documentCloseUI, documentCloseButtonUI } from '@/theme/document/close'
+
+const files = useStore(filesMessages)
+const common = useStore(commonMessages)
+const saveButton = useTemplateRef('saveButton')
+
+// The dialog mounts on open, so focusing the primary action when the target appears keeps
+// Return on Save while Escape still cancels.
+useFocus(saveButton, { initialValue: true, preventScroll: true })
+
+function updateOpen(open: boolean) {
+ if (!open) answerClosePrompt('cancel')
+}
+</script>
+
+<template>
+ <AppAlertDialogRoot :open="closePrompt !== null" @update:open="updateOpen">
+ <AppDialogHeader
+ :heading="files.saveBeforeClosing({ name: closePrompt?.documentName ?? '' })"
+ :description="files.saveBeforeClosingDescription"
+ :show-close="false"
+ :ui="documentCloseUI"
+ />
+ <AppDialogFooter :ui="documentCloseUI">
+ <AppButton
+ color="neutral"
+ variant="ghost"
+ class="mr-auto"
+ @click="answerClosePrompt('discard')"
+ >
+ {{ files.discard }}
+ </AppButton>
+ <AppButton
+ color="neutral"
+ variant="outline"
+ :ui="documentCloseButtonUI"
+ @click="answerClosePrompt('cancel')"
+ >
+ {{ common.cancel }}
+ </AppButton>
+ <AppButton
+ ref="saveButton"
+ color="primary"
+ variant="solid"
+ :ui="documentCloseButtonUI"
+ @click="answerClosePrompt('save')"
+ >
+ {{ common.save }}
+ </AppButton>
+ </AppDialogFooter>
+ </AppAlertDialogRoot>
+</template>
diff --git a/src/theme/document/close.ts b/src/theme/document/close.ts
new file mode 100644
index 000000000..7284e726a
--- /dev/null
+++ b/src/theme/document/close.ts
@@ -0,0 +1,10 @@
+import type { DialogUI } from '@/components/ui/dialog/ui'
+
+export const documentCloseUI = {
+ header: 'border-b-0 px-5 pt-5 pb-4',
+ title: 'mb-1 text-pretty break-words',
+ description: 'leading-relaxed',
+ footer: 'border-t-0 px-5 pt-0 pb-5'
+} satisfies DialogUI
+
+export const documentCloseButtonUI = { base: 'min-w-18 justify-center' }
diff --git a/src/theme/tab-bar.ts b/src/theme/tab-bar.ts
index d025205c3..9fe86664d 100644
--- a/src/theme/tab-bar.ts
+++ b/src/theme/tab-bar.ts
@@ -10,6 +10,7 @@ const tabBarTheme = {
close:
'flex size-6 shrink-0 cursor-pointer touch-manipulation items-center justify-center rounded transition-opacity group-hover/tab:opacity-100 hover:bg-hover focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-panel-focus sm:size-4',
closeIcon: 'size-3',
+ dirtyDot: 'size-1.5 shrink-0 rounded-full bg-accent',
newIcon: 'size-3.5'
},
variants: {
diff --git a/tests/e2e/app/unsaved-changes.spec.ts b/tests/e2e/app/unsaved-changes.spec.ts
new file mode 100644
index 000000000..56c623d80
--- /dev/null
+++ b/tests/e2e/app/unsaved-changes.spec.ts
@@ -0,0 +1,104 @@
+import { expect, test } from '#tests/e2e/fixtures'
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+test.beforeEach(async ({ page }) => {
+ await page.goto('/')
+ await new CanvasHelper(page).waitForInit()
+ await page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Editor unavailable')
+ store.createShape('RECTANGLE', 100, 100, 100, 100)
+ })
+ await expect(
+ page.getByRole('tab').filter({ has: page.getByRole('img', { name: 'Unsaved changes' }) })
+ ).toBeVisible()
+})
+
+test('Cancel retains the dirty document and recovery does not mark it saved', async ({ page }) => {
+ await page.evaluate(async () => {
+ await window.openPencil?.getStore?.().persistRecoveryNow()
+ })
+ await page.getByTestId('tabbar-close').click()
+ const dialog = page.getByRole('alertdialog', { name: /Save changes to/ })
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByRole('button', { name: 'Save', exact: true })).toBeFocused()
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(dialog).not.toBeVisible()
+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toBeVisible()
+ expect(await page.evaluate(() => window.openPencil?.getStore?.().hasUnsavedChanges())).toBe(true)
+})
+
+test('Don’t Save closes the document', async ({ page }) => {
+ await page.getByTestId('tabbar-close').click()
+ await page
+ .getByRole('alertdialog')
+ .getByRole('button', { name: 'Don’t Save', exact: true })
+ .click()
+ await expect(page.getByTestId('recent-files-home')).toBeVisible()
+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).not.toBeVisible()
+})
+
+test('cancelling the Save file picker keeps the dirty document open', async ({ page }) => {
+ const picker = await page.evaluateHandle(() => {
+ const original = window.showSaveFilePicker
+ const state = {
+ calls: 0,
+ restore: () => {
+ window.showSaveFilePicker = original
+ }
+ }
+ window.showSaveFilePicker = async () => {
+ state.calls++
+ throw new DOMException('Cancelled', 'AbortError')
+ }
+ return state
+ })
+ try {
+ await page.getByTestId('tabbar-close').click()
+ await page.getByRole('alertdialog').getByRole('button', { name: 'Save', exact: true }).click()
+ await expect.poll(() => picker.evaluate((state) => state.calls)).toBe(1)
+ await expect(page.getByRole('alertdialog')).not.toBeVisible()
+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toBeVisible()
+ } finally {
+ await picker.evaluate((handle) => handle.restore())
+ await picker.dispose()
+ }
+})
+
+test('Save downloads the document before closing when the file API is unavailable', async ({
+ page
+}) => {
+ const picker = await page.evaluateHandle(() => {
+ const original = window.showSaveFilePicker
+ window.showSaveFilePicker = undefined
+ return {
+ restore: () => {
+ window.showSaveFilePicker = original
+ }
+ }
+ })
+ try {
+ await page.getByTestId('tabbar-close').click()
+ page.once('dialog', (dialog) => dialog.accept('Saved-before-close.fig'))
+ const download = page.waitForEvent('download')
+ await page.getByRole('alertdialog').getByRole('button', { name: 'Save', exact: true }).click()
+ expect((await download).suggestedFilename()).toBe('Saved-before-close.fig')
+ await expect(page.getByTestId('recent-files-home')).toBeVisible()
+ } finally {
+ await picker.evaluate((handle) => handle.restore())
+ await picker.dispose()
+ }
+})
+
+test('browser reload warns about unsaved work', async ({ page }) => {
+ // Browsers require a trusted interaction before showing a beforeunload prompt.
+ await page.getByTestId('tabbar-close').click()
+ await page.getByRole('alertdialog').getByRole('button', { name: 'Cancel', exact: true }).click()
+ const dialogPromise = page.waitForEvent('dialog')
+ const reload = page.evaluate(() => window.location.reload())
+ const dialog = await dialogPromise
+ expect(dialog.type()).toBe('beforeunload')
+ await dialog.dismiss()
+ await reload
+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toBeVisible()
+})
diff --git a/tests/e2e/chat/diagnostics.spec.ts b/tests/e2e/chat/diagnostics.spec.ts
deleted file mode 100644
index 26262a543..000000000
--- a/tests/e2e/chat/diagnostics.spec.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { test, expect } from '#tests/helpers/chat/fixture'
-
-test('diagnostic menu copies the conversation to the clipboard', async ({
- configuredChat: chat,
- page,
- context
-}) => {
- await context.grantPermissions(['clipboard-read', 'clipboard-write'])
- await chat.submit('Clipboard regression conversation')
- await expect(chat.assistantMessage()).toBeVisible()
- await page.getByRole('button', { name: 'Conversation actions' }).click()
- await page.getByRole('menuitem', { name: 'Copy diagnostic log' }).click()
- await expect(page.getByRole('status')).toContainText('Diagnostic log copied.')
- const contents = await page.evaluate(() => navigator.clipboard.readText())
- expect(contents).toContain('OPEN PENCIL AI DEBUG LOG')
- expect(contents).toContain('Clipboard regression conversation')
-})
-
-test('clipboard rejection shows failure feedback rather than success', async ({
- configuredChat: chat,
- page
-}) => {
- await chat.submit('Clipboard failure conversation')
- await expect(chat.assistantMessage()).toBeVisible()
- await page.evaluate(() => {
- Object.defineProperty(navigator.clipboard, 'writeText', {
- configurable: true,
- value: async () => {
- throw new DOMException('Permission denied', 'NotAllowedError')
- }
- })
- })
- await page.getByRole('button', { name: 'Conversation actions' }).click()
- await page.getByRole('menuitem', { name: 'Copy diagnostic log' }).click()
- await expect(page.getByRole('status')).toContainText('Could not copy the diagnostic log.')
- await expect(page.getByText('Diagnostic log copied.', { exact: true })).toHaveCount(0)
-})
-
-test('mobile conversation menu stays attached to its trigger and inside the viewport', async ({
- configuredChat: chat,
- page
-}) => {
- await chat.submit('Mobile menu conversation')
- await expect(chat.assistantMessage()).toBeVisible()
- await page.setViewportSize({ width: 390, height: 844 })
- await page.getByTestId('mobile-ribbon-ai').click()
- const trigger = page.getByRole('button', { name: 'Conversation actions' })
- await expect(trigger).toBeVisible()
- const triggerBox = await trigger.boundingBox()
- await trigger.click()
- const menu = page.getByRole('menu')
- await expect(menu).toBeVisible()
- await expect
- .poll(async () => {
- const box = await menu.boundingBox()
- if (!box || !triggerBox) return false
- return (
- box.x >= 0 &&
- box.x + box.width <= 390 &&
- box.y >= 0 &&
- box.y + box.height <= 844 &&
- Math.abs(box.x + box.width - triggerBox.x - triggerBox.width) < 2
- )
- })
- .toBe(true)
-})
diff --git a/tests/e2e/chat/history.spec.ts b/tests/e2e/chat/history.spec.ts
index c02648ec2..906f9d8ef 100644
--- a/tests/e2e/chat/history.spec.ts
+++ b/tests/e2e/chat/history.spec.ts
@@ -29,7 +29,7 @@ test('multiple conversations preserve messages and manual titles', async ({
if (!triggerBox || !menuBox) throw new Error('Missing menu geometry')
expect(Math.abs(menuBox.x + menuBox.width - triggerBox.x - triggerBox.width)).toBeLessThan(2)
expect(Math.abs(menuBox.y - triggerBox.y - triggerBox.height - 6)).toBeLessThan(2)
- await expect(page.getByRole('menuitem', { name: 'Copy diagnostic log' })).toBeVisible()
+ await expect(page.getByRole('menuitem')).toHaveText(['Rename', 'Delete'])
await page.getByRole('menuitem', { name: 'Rename', exact: true }).click()
await page.getByRole('textbox', { name: 'Conversation title' }).fill('First design')
await page.getByRole('button', { name: 'Save', exact: true }).click()
diff --git a/tests/e2e/chat/lazy-connection.spec.ts b/tests/e2e/chat/lazy-connection.spec.ts
new file mode 100644
index 000000000..db60a1b27
--- /dev/null
+++ b/tests/e2e/chat/lazy-connection.spec.ts
@@ -0,0 +1,37 @@
+import { test, expect } from '#tests/helpers/chat/fixture'
+import { injectMockChatTransport } from '#tests/helpers/chat/transport'
+
+test('creating a new chat does not connect before an explicit submission', async ({
+ configuredChat: chat,
+ page
+}) => {
+ const probe = await page.evaluateHandle(() => {
+ const setTransport = window.openPencil?.setChatTransport
+ if (!setTransport) throw new Error('Transport override unavailable')
+ const state = { connections: 0 }
+ setTransport(() => {
+ state.connections++
+ return {
+ async sendMessages() {
+ throw new Error('Intentional test provider failure')
+ },
+ async reconnectToStream() {
+ return null
+ }
+ }
+ })
+ return state
+ })
+
+ try {
+ await page.getByRole('button', { name: 'New chat', exact: true }).click()
+ await expect(chat.input).toBeVisible()
+ await expect(page.getByRole('button', { name: 'New chat', exact: true })).toBeEnabled()
+ expect(await probe.evaluate((state) => state.connections)).toBe(0)
+ await chat.submit('Connect only for this request')
+ await expect.poll(() => probe.evaluate((state) => state.connections)).toBe(1)
+ } finally {
+ await injectMockChatTransport(page)
+ await probe.dispose()
+ }
+})
diff --git a/tests/e2e/chat/menu.spec.ts b/tests/e2e/chat/menu.spec.ts
new file mode 100644
index 000000000..b0427aacb
--- /dev/null
+++ b/tests/e2e/chat/menu.spec.ts
@@ -0,0 +1,31 @@
+import { test, expect } from '#tests/helpers/chat/fixture'
+
+test('mobile conversation menu stays attached to its trigger and inside the viewport', async ({
+ configuredChat: chat,
+ page
+}) => {
+ await chat.submit('Mobile menu conversation')
+ await expect(chat.assistantMessage()).toBeVisible()
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.getByTestId('mobile-ribbon-ai').click()
+ const trigger = page.getByRole('button', { name: 'Conversation actions' })
+ await expect(trigger).toBeVisible()
+ const triggerBox = await trigger.boundingBox()
+ await trigger.click()
+ const menu = page.getByRole('menu')
+ await expect(menu).toBeVisible()
+ await expect(page.getByRole('menuitem')).toHaveText(['Rename', 'Delete'])
+ await expect
+ .poll(async () => {
+ const box = await menu.boundingBox()
+ if (!box || !triggerBox) return false
+ return (
+ box.x >= 0 &&
+ box.x + box.width <= 390 &&
+ box.y >= 0 &&
+ box.y + box.height <= 844 &&
+ Math.abs(box.x + box.width - triggerBox.x - triggerBox.width) < 2
+ )
+ })
+ .toBe(true)
+})
diff --git a/tests/e2e/recovery.spec.ts b/tests/e2e/recovery.spec.ts
index 7a5a0bf8e..f339fbfe5 100644
--- a/tests/e2e/recovery.spec.ts
+++ b/tests/e2e/recovery.spec.ts
@@ -1,7 +1,10 @@
import { expect, test } from '#tests/e2e/fixtures'
import { CanvasHelper } from '#tests/helpers/canvas'
-test('keeps an unsaved document recoverable after its tab closes', async ({ browser, baseURL }) => {
+test('keeps recovery independent from cancelling an unsaved-document close', async ({
+ browser,
+ baseURL
+}) => {
const context = await browser.newContext({ baseURL })
const page = await context.newPage()
await page.goto('/')
@@ -14,12 +17,15 @@ test('keeps an unsaved document recoverable after its tab closes', async ({ brow
const id = store.createShape('RECTANGLE', 120, 120, 240, 140)
await store.persistRecoveryNow()
store.updateNode(id, { name: 'Retained recovery rectangle' })
+ await store.persistRecoveryNow()
})
await page.keyboard.press('ControlOrMeta+t')
await expect(page.getByTestId('tabbar-tab')).toHaveCount(2)
await page.locator('[data-slot="tab-item"]').first().getByTestId('tabbar-close').click()
- await expect(page.getByTestId('tabbar-tab')).toHaveCount(1)
+ await expect(page.getByRole('alertdialog', { name: /Save changes to/ })).toBeVisible()
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(page.getByTestId('tabbar-tab')).toHaveCount(2)
await expect(page.getByTestId('recent-files-home')).toBeVisible()
await expect
.poll(() =>
@@ -39,6 +45,7 @@ test('keeps an unsaved document recoverable after its tab closes', async ({ brow
)
.toBe(1)
+ page.once('dialog', (dialog) => dialog.accept())
await page.reload()
await expect(page.getByRole('alertdialog', { name: 'Recover unsaved work' })).toBeVisible()
await page.getByRole('button', { name: 'Restore' }).click()
diff --git a/tests/e2e/settings/diagnostics.spec.ts b/tests/e2e/settings/diagnostics.spec.ts
new file mode 100644
index 000000000..59dd3c0fd
--- /dev/null
+++ b/tests/e2e/settings/diagnostics.spec.ts
@@ -0,0 +1,31 @@
+import type { DiagnosticEvent } from '@/app/diagnostics/types'
+
+import { test, expect } from '#tests/helpers/chat/fixture'
+
+test('Settings exports correlated chat telemetry without conversation content', async ({
+ configuredChat: chat,
+ page,
+ context
+}) => {
+ await context.grantPermissions(['clipboard-read', 'clipboard-write'])
+ await chat.submit('Private conversation content must not enter diagnostics')
+ await expect(chat.assistantMessage()).toBeVisible()
+ await expect(chat.input).toBeEnabled()
+ await chat.submit('A second request in the same conversation')
+ await expect(page.getByTestId('chat-message-assistant')).toHaveCount(2)
+ await page.getByTestId('app-settings-trigger').click()
+ await page.getByTestId('settings-section-diagnostics').click()
+ await page.getByRole('button', { name: 'Copy diagnostics', exact: true }).click()
+ await expect(page.getByText('Diagnostics copied to clipboard.', { exact: true })).toBeVisible()
+ const text = await page.evaluate(() => navigator.clipboard.readText())
+ const events: DiagnosticEvent[] = JSON.parse(text)
+ const completed = events.filter((event) => event.name === 'chat.completed')
+ expect(completed).toHaveLength(2)
+ expect(completed[0].sessionId).toEqual(expect.any(String))
+ expect(completed[1].sessionId).toBe(completed[0].sessionId)
+ expect(completed[0].runId).toEqual(expect.any(String))
+ expect(completed[1].runId).toEqual(expect.any(String))
+ expect(completed[1].runId).not.toBe(completed[0].runId)
+ expect(text).not.toContain('Private conversation content')
+ expect(text).not.toContain('A second request')
+})
diff --git a/tests/engine/app/ai/debug-log.test.ts b/tests/engine/app/ai/debug-log.test.ts
deleted file mode 100644
index 73dec8ee7..000000000
--- a/tests/engine/app/ai/debug-log.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import type { UIMessage } from 'ai'
-
-import { safeFailureDetail, serializeChatLog } from '@/app/ai/debug'
-import { setActiveEditorStore } from '@/app/editor/active-store'
-import { createEditorStore } from '@/app/editor/session'
-
-const messages: UIMessage[] = [
- { id: 'user-1', role: 'user', parts: [{ type: 'text', text: 'Create a card' }] }
-]
-
-describe('AI debug log', () => {
- setActiveEditorStore(createEditorStore())
-
- test('records request-level failures', () => {
- const log = serializeChatLog(messages, {
- reason: 'insufficient-credit',
- detail: '402 Payment Required'
- })
-
- expect(log).toContain('=== ERRORS ===')
- expect(log).toContain('insufficient-credit: 402 Payment Required')
- })
-
- test('redacts and bounds request failure details', () => {
- const secret = `Authorization: Bearer-secret ${'x'.repeat(300)}`
- const detail = safeFailureDetail(secret)
- expect(detail).not.toContain('Bearer-secret')
- expect(detail).toContain('[redacted]')
- expect(detail.length).toBeLessThanOrEqual(241)
- })
-
- test('reports when no request failure was recorded', () => {
- expect(serializeChatLog(messages)).toContain('=== ERRORS ===\n\n (none recorded)')
- })
-})
diff --git a/tests/engine/app/diagnostics/recorder.test.ts b/tests/engine/app/diagnostics/recorder.test.ts
index 3c1b8db09..d52148a25 100644
--- a/tests/engine/app/diagnostics/recorder.test.ts
+++ b/tests/engine/app/diagnostics/recorder.test.ts
@@ -1,9 +1,8 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { diagnostics, recordChatCompleted } from '@/app/diagnostics'
-import { isDiagnosticsEnabled } from '@/app/diagnostics/settings'
-
-void isDiagnosticsEnabled
+import { recordModelStepCompleted, recordToolCompleted } from '@/app/diagnostics/events/ai'
+import { useDiagnosticsSettings } from '@/app/diagnostics/settings'
describe('diagnostics recorder', () => {
beforeEach(async () => {
@@ -19,6 +18,56 @@ describe('diagnostics recorder', () => {
expect(await diagnostics.export()).toContain('chat.completed')
})
+ test('exports correlated AI metadata without transcript or tool payloads', async () => {
+ const context = { sessionId: 'conversation-one', runId: 'request-one' }
+ const tool = {
+ tool: 'create_node',
+ durationMs: 5,
+ mutates: true,
+ failed: false,
+ input: 'private tool input',
+ output: 'private tool output'
+ }
+ recordToolCompleted(tool, context)
+ recordModelStepCompleted(
+ {
+ provider: 'openrouter',
+ model: 'test',
+ inputTokens: 10,
+ outputTokens: 2,
+ cacheReadTokens: null,
+ cacheWriteTokens: null
+ },
+ context
+ )
+ recordChatCompleted({ finishReason: 'stop' }, context)
+ const events = await diagnostics.list()
+ expect(events).toHaveLength(3)
+ for (const event of events) {
+ expect(event.sessionId).toBe(context.sessionId)
+ expect(event.runId).toBe(context.runId)
+ }
+ const output = await diagnostics.export()
+ expect(output).toContain('"cacheReadTokens": null')
+ expect(output).not.toContain('private tool')
+ expect(output).not.toContain('messages')
+ })
+
+ test('disabling diagnostics also disables tool telemetry', async () => {
+ const { diagnosticsEnabled } = useDiagnosticsSettings()
+ const previous = diagnosticsEnabled.value
+ try {
+ diagnosticsEnabled.value = false
+ recordToolCompleted(
+ { tool: 'create_node', durationMs: 5, mutates: true, failed: false },
+ { sessionId: 'disabled', runId: 'disabled-run' }
+ )
+ expect(await diagnostics.list()).toEqual([])
+ } finally {
+ diagnosticsEnabled.value = previous
+ }
+ })
+
test('clears recorded events', async () => {
recordChatCompleted({ finishReason: 'stop' })
await diagnostics.clear()
diff --git a/tests/engine/app/document/close/controller.test.ts b/tests/engine/app/document/close/controller.test.ts
new file mode 100644
index 000000000..17acd1d3a
--- /dev/null
+++ b/tests/engine/app/document/close/controller.test.ts
@@ -0,0 +1,89 @@
+import { expect, test } from 'bun:test'
+
+import { confirmDocumentClose, type CloseChoice } from '@/app/document/close/controller'
+
+test.each<CloseChoice>(['cancel', 'discard'])('%s does not save the document', async (choice) => {
+ let saves = 0
+ const result = await confirmDocumentClose(
+ {
+ hasUnsavedChanges: () => true,
+ saveFigFile: async () => {
+ saves++
+ return true
+ }
+ },
+ async () => choice
+ )
+ expect(result).toBe(choice)
+ expect(saves).toBe(0)
+})
+
+test('clean documents close without prompting', async () => {
+ expect(
+ await confirmDocumentClose(
+ {
+ hasUnsavedChanges: () => false,
+ saveFigFile: async () => {
+ throw new Error('Unexpected save')
+ }
+ },
+ async () => {
+ throw new Error('Unexpected prompt')
+ }
+ )
+ ).toBe('saved')
+})
+
+test('a cancelled file picker prevents close', async () => {
+ expect(
+ await confirmDocumentClose(
+ {
+ hasUnsavedChanges: () => true,
+ saveFigFile: async () => false
+ },
+ async () => 'save'
+ )
+ ).toBe('cancel')
+})
+
+test('edits during a successful write prevent close', async () => {
+ expect(
+ await confirmDocumentClose(
+ {
+ hasUnsavedChanges: () => true,
+ saveFigFile: async () => true
+ },
+ async () => 'save'
+ )
+ ).toBe('cancel')
+})
+
+test('a successful save of the current revision permits close', async () => {
+ let dirty = true
+ expect(
+ await confirmDocumentClose(
+ {
+ hasUnsavedChanges: () => dirty,
+ saveFigFile: async () => {
+ dirty = false
+ return true
+ }
+ },
+ async () => 'save'
+ )
+ ).toBe('saved')
+})
+
+test('write failures propagate without authorizing close', async () => {
+ await expect(
+ confirmDocumentClose(
+ {
+ hasUnsavedChanges: () => true,
+ saveFigFile: async () => {
+ throw new Error('Disk full')
+ }
+ },
+ async () => 'save'
+ )
+ ).rejects.toThrow('Disk full')
+})
diff --git a/tests/engine/app/document/close/exit.test.ts b/tests/engine/app/document/close/exit.test.ts
new file mode 100644
index 000000000..95d3ed3de
--- /dev/null
+++ b/tests/engine/app/document/close/exit.test.ts
@@ -0,0 +1,49 @@
+import { expect, test } from 'bun:test'
+
+import { createExitApproval } from '@/app/document/close/exit'
+
+test('concurrent confirmations share one prompt run', async () => {
+ let prompts = 0
+ const approval = createExitApproval(async () => {
+ prompts++
+ await Promise.resolve()
+ return true
+ })
+
+ const results = await Promise.all([approval.confirm(), approval.confirm(), approval.confirm()])
+
+ expect(results).toEqual([true, true, true])
+ expect(prompts).toBe(1)
+ expect(approval.isApproved()).toBe(true)
+})
+
+test('a cancelled confirmation clears so the next request prompts again', async () => {
+ let prompts = 0
+ const approval = createExitApproval(async () => {
+ prompts++
+ return prompts > 1
+ })
+
+ expect(await approval.confirm()).toBe(false)
+ expect(approval.isApproved()).toBe(false)
+ expect(await approval.confirm()).toBe(true)
+ expect(prompts).toBe(2)
+
+ // Once approved, later requests never prompt.
+ expect(await approval.confirm()).toBe(true)
+ expect(prompts).toBe(2)
+})
+
+test('a failed confirmation retries instead of caching the rejection', async () => {
+ let attempts = 0
+ const approval = createExitApproval(async () => {
+ attempts++
+ if (attempts === 1) throw new Error('Write failed')
+ return true
+ })
+
+ await expect(approval.confirm()).rejects.toThrow('Write failed')
+ expect(approval.isApproved()).toBe(false)
+ expect(await approval.confirm()).toBe(true)
+ expect(attempts).toBe(2)
+})
diff --git a/tests/engine/app/document/close/native.test.ts b/tests/engine/app/document/close/native.test.ts
new file mode 100644
index 000000000..e338714fd
--- /dev/null
+++ b/tests/engine/app/document/close/native.test.ts
@@ -0,0 +1,48 @@
+import { expect, test } from 'bun:test'
+
+import { commonMessages, filesMessages } from '@open-pencil/vue'
+
+import { chooseNativeDocumentClose } from '@/app/document/close/native'
+
+type DialogCall = { message: string; options?: { title?: string; buttons?: unknown } }
+
+function dialogReturning(result: string) {
+ const calls: DialogCall[] = []
+ return {
+ calls,
+ show: async (message: string, options?: DialogCall['options']) => {
+ calls.push({ message, options })
+ return result
+ }
+ }
+}
+
+test('maps the native Save, Don’t Save, and Cancel results to close choices', async () => {
+ const files = filesMessages.get()
+ const common = commonMessages.get()
+ expect(await chooseNativeDocumentClose('Untitled', dialogReturning(common.save).show)).toBe(
+ 'save'
+ )
+ expect(await chooseNativeDocumentClose('Untitled', dialogReturning(files.discard).show)).toBe(
+ 'discard'
+ )
+ expect(await chooseNativeDocumentClose('Untitled', dialogReturning(common.cancel).show)).toBe(
+ 'cancel'
+ )
+ expect(await chooseNativeDocumentClose('Untitled', dialogReturning('Unexpected').show)).toBe(
+ 'cancel'
+ )
+})
+
+test('offers the localized buttons and names the document in the title', async () => {
+ const files = filesMessages.get()
+ const common = commonMessages.get()
+ const dialog = dialogReturning(common.cancel)
+ await chooseNativeDocumentClose('Brand kit', dialog.show)
+ expect(dialog.calls[0]?.options?.title).toBe(files.saveBeforeClosing({ name: 'Brand kit' }))
+ expect(dialog.calls[0]?.options?.buttons).toEqual({
+ yes: common.save,
+ no: files.discard,
+ cancel: common.cancel
+ })
+})
diff --git a/tests/engine/app/document/io/changes.test.ts b/tests/engine/app/document/io/changes.test.ts
new file mode 100644
index 000000000..b05d46701
--- /dev/null
+++ b/tests/engine/app/document/io/changes.test.ts
@@ -0,0 +1,48 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+import { createDocumentChanges } from '@/app/document/io/changes'
+
+test('repainting and selection do not dirty a document; content mutations do', () => {
+ const editor = createEditor()
+ const changes = createDocumentChanges(editor)
+ try {
+ editor.requestRender()
+ editor.requestRepaint()
+ editor.clearSelection()
+ expect(changes.hasUnsavedChanges()).toBe(false)
+ editor.createShape('RECTANGLE', 0, 0, 100, 100)
+ expect(changes.hasUnsavedChanges()).toBe(true)
+ changes.markSaved()
+ expect(changes.hasUnsavedChanges()).toBe(false)
+ editor.undo.record({
+ label: 'Variable edit',
+ forward: () => undefined,
+ inverse: () => undefined
+ })
+ expect(changes.hasUnsavedChanges()).toBe(true)
+ } finally {
+ changes.dispose()
+ editor.dispose()
+ }
+})
+
+test('saving an earlier revision cannot clear edits made while exporting or picking a file', () => {
+ const editor = createEditor()
+ const changes = createDocumentChanges(editor)
+ try {
+ editor.createShape('RECTANGLE', 0, 0, 100, 100)
+ const saving = changes.capture()
+ editor.createShape('ELLIPSE', 0, 0, 100, 100)
+ changes.markSaved(saving)
+ expect(changes.hasUnsavedChanges()).toBe(true)
+ changes.markSaved()
+ expect(changes.hasUnsavedChanges()).toBe(false)
+ changes.markChanged()
+ expect(changes.hasUnsavedChanges()).toBe(true)
+ } finally {
+ changes.dispose()
+ editor.dispose()
+ }
+})
diff --git a/tests/engine/app/settings/credential-migration.test.ts b/tests/engine/app/settings/credential-migration.test.ts
index 8deafe20e..57302d4a6 100644
--- a/tests/engine/app/settings/credential-migration.test.ts
+++ b/tests/engine/app/settings/credential-migration.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, test } from 'bun:test'
import { MemoryCredentialStore } from '@/app/settings/credentials/memory'
import {
+ hasLegacyCredential,
+ initializeCredentialMigration,
migrateLegacyCredentials,
PEXELS_CREDENTIAL,
providerCredentialRef
@@ -41,7 +43,58 @@ class UnavailableCredentialStore extends MemoryCredentialStore {
}
}
+class CountingStorage extends TestStorage {
+ scans = 0
+
+ override key(index: number): string | null {
+ this.scans++
+ return super.key(index)
+ }
+}
+
describe('legacy credential migration', () => {
+ test('recognizes pending credentials without migrating or removing them', () => {
+ const storage = new TestStorage()
+ storage.setItem('open-pencil:ai-key:openrouter', 'pending-key')
+ expect(hasLegacyCredential(providerCredentialRef('openrouter'), storage)).toBe(true)
+ expect(hasLegacyCredential(providerCredentialRef('anthropic'), storage)).toBe(false)
+ expect(
+ hasLegacyCredential(providerCredentialRef('openrouter', 'another-profile'), storage)
+ ).toBe(false)
+ expect(storage.getItem('open-pencil:ai-key:openrouter')).toBe('pending-key')
+ storage.setItem('open-pencil:credential-migration', '1')
+ expect(hasLegacyCredential(providerCredentialRef('openrouter'), storage)).toBe(false)
+ })
+
+ test('concurrent migrations share one in-flight run', async () => {
+ const storage = new CountingStorage()
+ storage.setItem('open-pencil:pexels-api-key', 'legacy-pexels-key')
+
+ await Promise.all([
+ initializeCredentialMigration(storage),
+ initializeCredentialMigration(storage)
+ ])
+
+ expect(storage.scans).toBe(storage.length)
+ expect(storage.getItem('open-pencil:pexels-api-key')).toBeNull()
+ })
+
+ test('concurrent migrations of distinct sources both complete', async () => {
+ const mediaStorage = new TestStorage()
+ const providerStorage = new TestStorage()
+ mediaStorage.setItem('open-pencil:pexels-api-key', 'legacy-pexels-key')
+ providerStorage.setItem('open-pencil:ai-key:anthropic', 'legacy-anthropic-key')
+
+ const results = await Promise.all([
+ initializeCredentialMigration(mediaStorage),
+ initializeCredentialMigration(providerStorage)
+ ])
+
+ expect(results).toEqual([true, true])
+ expect(mediaStorage.getItem('open-pencil:pexels-api-key')).toBeNull()
+ expect(providerStorage.getItem('open-pencil:ai-key:anthropic')).toBeNull()
+ })
+
test('verifies encrypted destinations before removing plaintext keys', async () => {
const storage = new TestStorage()
const store = new MemoryCredentialStore()
@@ -65,4 +118,16 @@ describe('legacy credential migration', () => {
expect(await migrateLegacyCredentials(storage, new UnavailableCredentialStore())).toBeFalse()
expect(storage.getItem('open-pencil:ai-key:openrouter')).toBe('keep-me')
})
+
+ test('clearing after migration removes a legacy-only credential for good', async () => {
+ const storage = new TestStorage()
+ const store = new MemoryCredentialStore()
+ storage.setItem('open-pencil:pexels-api-key', 'legacy-pexels-key')
+
+ expect(await migrateLegacyCredentials(storage, store)).toBeTrue()
+ await store.remove(PEXELS_CREDENTIAL)
+
+ expect(hasLegacyCredential(PEXELS_CREDENTIAL, storage)).toBeFalse()
+ expect(await store.read(PEXELS_CREDENTIAL)).toBeNull()
+ })
})
diff --git a/tests/engine/tools/stock-photo/credentials.test.ts b/tests/engine/tools/stock-photo/credentials.test.ts
new file mode 100644
index 000000000..664a34f42
--- /dev/null
+++ b/tests/engine/tools/stock-photo/credentials.test.ts
@@ -0,0 +1,37 @@
+import { expect, test } from 'bun:test'
+
+import {
+ getActiveProvider,
+ setActiveStockPhotoProvider,
+ setPexelsAPIKey,
+ setUnsplashAccessKey
+} from '#core/tools/stock-photo/providers'
+
+test.each(['pexels', 'unsplash'])('%s resolves credentials only when searching', async (name) => {
+ const previous = getActiveProvider()?.name ?? null
+ const setCredential = name === 'pexels' ? setPexelsAPIKey : setUnsplashAccessKey
+ let reads = 0
+
+ try {
+ setCredential(async () => {
+ reads++
+ return null
+ })
+ setActiveStockPhotoProvider(name)
+ const provider = getActiveProvider()
+ if (!provider) throw new Error('Missing registered provider')
+ expect(reads).toBe(0)
+
+ await expect(
+ provider.search('forest', {
+ perPage: 1,
+ orientation: 'landscape',
+ targetDim: 100
+ })
+ ).rejects.toThrow('not configured')
+ expect(reads).toBe(1)
+ } finally {
+ setCredential(null)
+ setActiveStockPhotoProvider(previous)
+ }
+})
diff --git a/tools/i18n/mixed-script-baseline.txt b/tools/i18n/mixed-script-baseline.txt
index bd0b94308..4ff04cfda 100644
--- a/tools/i18n/mixed-script-baseline.txt
+++ b/tools/i18n/mixed-script-baseline.txt
@@ -236,8 +236,6 @@ zh-cn:updates.installed
zh-cn:updates.unavailable
zh-cn:updates.upToDate
-ja:ai.copyACPLog
-zh-cn:ai.copyACPLog
ja:credentials.rememberDevice
zh-cn:credentials.rememberDevice
diff --git a/tools/tauri-menu/package.json b/tools/tauri-menu/package.json
index 2a2001a51..14982e3b8 100644
--- a/tools/tauri-menu/package.json
+++ b/tools/tauri-menu/package.json
@@ -1,5 +1,12 @@
{
"name": "@open-pencil/tauri-menu-tools",
"private": true,
- "type": "module"
+ "type": "module",
+ "scripts": {
+ "test": "bun test tests"
+ },
+ "devDependencies": {
+ "@open-pencil/package-artifacts": "workspace:*",
+ "@open-pencil/vue": "workspace:*"
+ }
}
diff --git a/tools/tauri-menu/src/generate.ts b/tools/tauri-menu/src/generate.ts
index c02357586..769fa289b 100644
--- a/tools/tauri-menu/src/generate.ts
+++ b/tools/tauri-menu/src/generate.ts
@@ -1,39 +1,9 @@
import { mkdirSync, writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
-import { editorCommandMetadata } from '@open-pencil/vue'
+import { MENU_ARTIFACTS } from './menu'
-import { APP_MENU_SCHEMA } from '@/app/shell/menu/schema'
-import type { AppMenuEntry, AppMenuGroupSchema } from '@/app/shell/menu/schema'
-import { shortcutTokenToAccelerator } from '@/app/shell/menu/shortcut'
-
-function isNativeVisible(entry: { target?: string }): boolean {
- return entry.target !== 'browser'
-}
-
-function cleanEntry(entry: AppMenuEntry): unknown | null {
- if (!isNativeVisible(entry)) return null
- if (entry.type === 'separator') return { type: 'separator' }
- const shortcut =
- entry.shortcut ?? (entry.command ? editorCommandMetadata(entry.command).shortcut : undefined)
- return {
- id: entry.id,
- label: entry.label,
- accelerator: entry.accelerator ?? shortcutTokenToAccelerator(shortcut),
- checkbox: entry.checkbox,
- sub: entry.sub?.map(cleanEntry).filter(Boolean)
- }
+for (const [path, render] of Object.entries(MENU_ARTIFACTS)) {
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, render())
}
-
-function cleanGroup(group: AppMenuGroupSchema): unknown | null {
- if (!isNativeVisible(group)) return null
- return {
- label: group.label,
- items: group.items.map(cleanEntry).filter(Boolean)
- }
-}
-
-const outputPath = 'desktop/generated/menu.json'
-const menu = APP_MENU_SCHEMA.map(cleanGroup).filter(Boolean)
-mkdirSync(dirname(outputPath), { recursive: true })
-writeFileSync(outputPath, `${JSON.stringify(menu, null, 2)}\n`)
diff --git a/tools/tauri-menu/src/menu.ts b/tools/tauri-menu/src/menu.ts
new file mode 100644
index 000000000..8db53855d
--- /dev/null
+++ b/tools/tauri-menu/src/menu.ts
@@ -0,0 +1,60 @@
+import { editorCommandMetadata } from '@open-pencil/vue'
+
+import { APP_MENU_APP_ITEMS, APP_MENU_SCHEMA } from '@/app/shell/menu/schema'
+import type { AppMenuActionItem, AppMenuEntry, AppMenuGroupSchema } from '@/app/shell/menu/schema'
+import { shortcutTokenToAccelerator } from '@/app/shell/menu/shortcut'
+
+export const MENU_PATH = 'desktop/generated/menu.json'
+export const APP_MENU_PATH = 'desktop/generated/app-menu.json'
+
+function isNativeVisible(entry: { target?: string }): boolean {
+ return entry.target !== 'browser'
+}
+
+function entryAccelerator(entry: AppMenuActionItem): string | undefined {
+ const shortcut =
+ entry.shortcut ?? (entry.command ? editorCommandMetadata(entry.command).shortcut : undefined)
+ return entry.accelerator ?? shortcutTokenToAccelerator(shortcut)
+}
+
+function cleanEntry(entry: AppMenuEntry): unknown | null {
+ if (!isNativeVisible(entry)) return null
+ if (entry.type === 'separator') return { type: 'separator' }
+ return {
+ id: entry.id,
+ label: entry.label,
+ accelerator: entryAccelerator(entry),
+ checkbox: entry.checkbox,
+ sub: entry.sub?.map(cleanEntry).filter(Boolean)
+ }
+}
+
+function cleanGroup(group: AppMenuGroupSchema): unknown | null {
+ if (!isNativeVisible(group)) return null
+ return {
+ label: group.label,
+ items: group.items.map(cleanEntry).filter(Boolean)
+ }
+}
+
+export function renderMenu(): string {
+ const menu = APP_MENU_SCHEMA.map(cleanGroup).filter(Boolean)
+ return `${JSON.stringify(menu, null, 2)}\n`
+}
+
+function renderAppMenu(): string {
+ // Keyed by id so the native builder cannot silently drop a label.
+ const items = Object.fromEntries(
+ APP_MENU_APP_ITEMS.map((entry) => [
+ entry.id,
+ { label: entry.label, accelerator: entryAccelerator(entry) }
+ ])
+ )
+ return `${JSON.stringify(items, null, 2)}\n`
+}
+
+/** Committed artifacts, keyed by workspace-relative path. */
+export const MENU_ARTIFACTS: Record<string, () => string> = {
+ [MENU_PATH]: renderMenu,
+ [APP_MENU_PATH]: renderAppMenu
+}
diff --git a/tools/tauri-menu/tests/artifacts.test.ts b/tools/tauri-menu/tests/artifacts.test.ts
new file mode 100644
index 000000000..df4835d1b
--- /dev/null
+++ b/tools/tauri-menu/tests/artifacts.test.ts
@@ -0,0 +1,15 @@
+import { expect, test } from 'bun:test'
+import { readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts'
+
+import { MENU_ARTIFACTS } from '../src/menu'
+
+test('committed menus match the schema', async () => {
+ const root = await resolveWorkspaceRoot(import.meta.dir)
+
+ for (const [path, render] of Object.entries(MENU_ARTIFACTS)) {
+ expect(await readFile(join(root, path), 'utf8'), `${path} is stale`).toBe(render())
+ }
+})