AI-native design editor. Open-source Figma alternative.
feat(desktop): show updates in a Software Update window (#936)
Danila Poyarkov55d8c57822d4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fbcd9ab79..f64c881dd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@- Shared rooms record the layer tree in a new format, so people on this version and on earlier versions can no longer join each other's rooms. A room this browser saved with an earlier version converts when you open it again.- `SceneGraph.hitTestFrame` is now `hitTestDropTarget`, which returns only layers that take a drop, as in Figma: it skips groups, boolean operations, component sets, and locked layers, follows rotation, and respects clipping. The editor's `adoptNodesIntoSection` is now `adoptCoveredLayers`, which also takes a frame, and leaves locked layers out.- `buildDerivedTextDataV4` is removed from `@open-pencil/core`, and `sceneNodeToKiwi` no longer writes glyph outlines by itself: pass the `runtime` that `withFigExportRuntime(graph, canvasKit, write)` hands its callback. In `@open-pencil/fig/node-change`, `FigNodeChangeExportRuntime` takes `shapeText(node)` instead of `getGlyphOutlineMetrics`, `buildDerivedTextData` takes the `baselines` it writes, and `convertFigmaDerivedTextGlyphs` takes the text's characters.+- The `updates` messages from `@open-pencil/vue` no longer include `availableTitle`, `installPrompt`, `installedTitle`, and `downloading`, which only the system update dialogs and download toast used; `installed` now takes only `{ version }`, and `install` reads "Install Update". The Software Update window uses the new `windowTitle`, `currentVersion`, `whatsNew`, `installAndRestart`, `restartNow`, and related messages.### Added@@ -71,6 +72,7 @@### Changed+- The desktop app shows an available update in a Software Update window with formatted, scrollable release notes, a link to the full notes, and download progress you can cancel, instead of a system dialog that showed raw Markdown and could grow taller than the screen (#743). On macOS and Linux the update installs first and you choose when to restart; restarting, and on Windows installing, first asks about unsaved documents as Quit does.- `openpencil eval` prints the value of a script's last expression, as the `eval` tool and app automation already do, so `-c 'figma.currentPage.children.length'` prints the count without a `return`.- In scripts, children of groups and booleans report `x`, `y`, and `relativeTransform` in their container's space, as in Figma, and a group refits whenever a script moves, resizes, rotates, adds, or removes one of its children; a group left without children is removed. The canvas and the plugin API share the refit.- Group, Frame selection, Create component, and boolean operations match Figma from the canvas and from scripts, through one shared implementation. From the canvas, the new layer takes the topmost selected layer's place in the layer list, Frame selection adds no fill and does not clip, a component wrapped around layers is white and takes a single layer's name, and a boolean is filled like its topmost operand, or its base for Subtract, without strokes. In scripts, `figma.ungroup()` leaves the children in the group's place instead of moving them to the top, booleans are named Union, Subtract, Intersect, or Exclude with the default grey fill, and `figma.createComponentFromNode()` turns a frame or group into a component that keeps its children instead of copying them, and wraps any other layer. Undoing a group or boolean returns each layer to its own place in the layer list.diff --git a/desktop/AGENTS.md b/desktop/AGENTS.mdindex afab90f78..95f5fa0e8 100644--- a/desktop/AGENTS.md+++ b/desktop/AGENTS.md@@ -8,6 +8,8 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j- ACP and harness process changes require checking `desktop/capabilities/**`.- The fs scope allows documents anywhere but denies, in the global `fs:scope`, every place where a written file would run, and `requireLiteralLeadingDot` keeps hidden files out of `**` on every platform; a new write path must not reopen either (`tests/e2e/native/fs-scope.spec.ts`).- A `shell:allow-spawn` entry pins the whole command line: no `"args": true`, and a Windows `.cmd` shim runs through its own `cmd-<name>` entry with fixed `/c <name> …` arguments, which `resolvePlatformCommand` selects (`tests/engine/tauri/command.test.ts`).+- The Software Update window is a second webview labelled `updater` that loads `updater.html` (`src/updater.ts`), never the editor's `index.html`; its own capability, `desktop/capabilities/updater.json`, grants only checking, installing, restarting, closing, and opening links. It owns no documents, so before a restart or a Windows install it asks the editor window over `updater:restart-request` to run the Quit approval (`src/app/shell/updater/approvals.ts`, `tests/app/shell/updater/session.test.ts`).+- Never click Install in a `tauri dev` build: the updater unpacks the release next to the running binary, which there is `desktop/target/debug`.- `desktop/generated/menu.json` is produced by `bun run generate:tauri-menu` from `src/app/shell/menu/schema.ts`; do not edit or import it directly.- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.- `build_fig_file` performs `.fig` export on desktop; the browser path uses fflate (`packages/fig/AGENTS.md`).diff --git a/desktop/capabilities/default.json b/desktop/capabilities/default.jsonindex fe39ba63f..b3251c235 100644--- a/desktop/capabilities/default.json+++ b/desktop/capabilities/default.json@@ -6,6 +6,9 @@"permissions": ["core:default","core:window:allow-destroy",+ "core:webview:allow-create-webview-window",+ "core:window:allow-set-focus",+ "core:window:allow-unminimize","opener:default","dialog:default","dialog:allow-save",diff --git a/desktop/capabilities/updater.json b/desktop/capabilities/updater.jsonnew file mode 100644index 000000000..dafd26ee4--- /dev/null+++ b/desktop/capabilities/updater.json@@ -0,0 +1,14 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "updater",+ "description": "Capability for the Software Update window: check, install, restart, close, and open release notes",+ "windows": ["updater"],+ "permissions": [+ "core:default",+ "core:window:allow-close",+ "core:window:allow-destroy",+ "opener:default",+ "updater:default",+ "process:allow-restart"+ ]+}diff --git a/packages/vue/src/i18n/locales/de/updates.json b/packages/vue/src/i18n/locales/de/updates.jsonindex 982fdea23..4b7762ef1 100644--- a/packages/vue/src/i18n/locales/de/updates.json+++ b/packages/vue/src/i18n/locales/de/updates.json@@ -1,13 +1,25 @@{"upToDate": "OpenPencil ist auf dem neuesten Stand",- "availableTitle": "OpenPencil aktualisieren",- "available": "OpenPencil {version} ist verfügbar.",- "installPrompt": "Jetzt herunterladen und installieren? Die App wird nach der Installation neu gestartet.",- "downloading": "OpenPencil {version} wird heruntergeladen",+ "windowTitle": "Softwareaktualisierung",+ "checking": "Suche nach Updates …",+ "available": "OpenPencil {version} ist verfügbar",+ "currentVersion": "Du hast Version {version}.",+ "whatsNew": "Neuerungen",+ "noNotes": "Für dieses Release gibt es keine Versionshinweise.",+ "fullReleaseNotes": "Alle Versionshinweise",+ "later": "Später",+ "install": "Update installieren",+ "installAndRestart": "Installieren und neu starten",+ "retry": "Erneut versuchen","downloadProgress": "{percent} % · {downloaded} von {total}","downloadProgressUnknown": "{downloaded} heruntergeladen",- "installedTitle": "Update installiert",- "installed": "OpenPencil {version} wurde installiert{size}. Neustart jetzt.",+ "installing": "Wird installiert …",+ "installed": "OpenPencil {version} ist installiert",+ "restartToFinish": "Starte OpenPencil neu, um die neue Version zu verwenden.",+ "restartNow": "Jetzt neu starten",+ "downloadFailed": "Das Update konnte nicht heruntergeladen werden: {error}",+ "installFailed": "Das Update konnte nicht installiert werden: {error}",+ "restartFailed": "OpenPencil konnte nicht neu gestartet werden: {error}","unavailable": "Updates sind noch nicht verfügbar. Veröffentliche zuerst ein signiertes Release mit latest.json.","checkFailed": "Updates konnten nicht geprüft werden: {error}"}diff --git a/packages/vue/src/i18n/locales/es/updates.json b/packages/vue/src/i18n/locales/es/updates.jsonindex afd9711eb..1c9349741 100644--- a/packages/vue/src/i18n/locales/es/updates.json+++ b/packages/vue/src/i18n/locales/es/updates.json@@ -1,13 +1,25 @@{"upToDate": "OpenPencil está actualizado",- "availableTitle": "Actualizar OpenPencil",- "available": "Está disponible la versión {version} de OpenPencil.",- "installPrompt": "¿Descargar e instalar ahora? La app se reiniciará después de instalar la actualización.",- "downloading": "Descargando OpenPencil {version}",+ "windowTitle": "Actualización de software",+ "checking": "Buscando actualizaciones…",+ "available": "OpenPencil {version} está disponible",+ "currentVersion": "Tienes la versión {version}.",+ "whatsNew": "Novedades",+ "noNotes": "Esta versión no tiene notas de la versión.",+ "fullReleaseNotes": "Notas de la versión completas",+ "later": "Más tarde",+ "install": "Instalar actualización",+ "installAndRestart": "Instalar y reiniciar",+ "retry": "Reintentar","downloadProgress": "{percent} % · {downloaded} de {total}","downloadProgressUnknown": "{downloaded} descargados",- "installedTitle": "Actualización instalada",- "installed": "Se ha instalado la versión {version} de OpenPencil{size}. Reiniciando ahora...",+ "installing": "Instalando…",+ "installed": "OpenPencil {version} está instalado",+ "restartToFinish": "Reinicia OpenPencil para empezar a usar la nueva versión.",+ "restartNow": "Reiniciar ahora",+ "downloadFailed": "No se pudo descargar la actualización: {error}",+ "installFailed": "No se pudo instalar la actualización: {error}",+ "restartFailed": "No se pudo reiniciar OpenPencil: {error}","unavailable": "Las actualizaciones aún no están disponibles. Publica primero una versión firmada con latest.json.","checkFailed": "Error al encontrar actualizaciones: {error}"}diff --git a/packages/vue/src/i18n/locales/fr/updates.json b/packages/vue/src/i18n/locales/fr/updates.jsonindex a145984c3..c9e80ad02 100644--- a/packages/vue/src/i18n/locales/fr/updates.json+++ b/packages/vue/src/i18n/locales/fr/updates.json@@ -1,13 +1,25 @@{"upToDate": "OpenPencil est à jour",- "availableTitle": "Mettre à jour OpenPencil",- "available": "OpenPencil {version} est disponible.",- "installPrompt": "Télécharger et installer maintenant ? L’app redémarrera après l’installation de la mise à jour.",- "downloading": "Téléchargement d’OpenPencil {version}",+ "windowTitle": "Mise à jour logicielle",+ "checking": "Recherche de mises à jour…",+ "available": "OpenPencil {version} est disponible",+ "currentVersion": "Vous avez la version {version}.",+ "whatsNew": "Nouveautés",+ "noNotes": "Cette version n’a pas de notes de version.",+ "fullReleaseNotes": "Notes de version complètes",+ "later": "Plus tard",+ "install": "Installer la mise à jour",+ "installAndRestart": "Installer et redémarrer",+ "retry": "Réessayer","downloadProgress": "{percent} % · {downloaded} sur {total}","downloadProgressUnknown": "{downloaded} téléchargés",- "installedTitle": "Mise à jour installée",- "installed": "OpenPencil {version} a été installé{size}. Redémarrage maintenant.",+ "installing": "Installation…",+ "installed": "OpenPencil {version} est installé",+ "restartToFinish": "Redémarrez OpenPencil pour utiliser la nouvelle version.",+ "restartNow": "Redémarrer maintenant",+ "downloadFailed": "Impossible de télécharger la mise à jour : {error}",+ "installFailed": "Impossible d’installer la mise à jour : {error}",+ "restartFailed": "Impossible de redémarrer OpenPencil : {error}","unavailable": "Les mises à jour ne sont pas encore disponibles. Publiez d’abord une version signée avec latest.json.","checkFailed": "Impossible de rechercher des mises à jour : {error}"}diff --git a/packages/vue/src/i18n/locales/it/updates.json b/packages/vue/src/i18n/locales/it/updates.jsonindex 31a6b7966..159187c79 100644--- a/packages/vue/src/i18n/locales/it/updates.json+++ b/packages/vue/src/i18n/locales/it/updates.json@@ -1,13 +1,25 @@{"upToDate": "OpenPencil è aggiornato",- "availableTitle": "Aggiorna OpenPencil",- "available": "OpenPencil {version} è disponibile.",- "installPrompt": "Scaricare e installare ora? L’app verrà riavviata dopo l’installazione dell’aggiornamento.",- "downloading": "Download di OpenPencil {version}",+ "windowTitle": "Aggiornamento software",+ "checking": "Ricerca aggiornamenti…",+ "available": "OpenPencil {version} è disponibile",+ "currentVersion": "Hai la versione {version}.",+ "whatsNew": "Novità",+ "noNotes": "Questa versione non ha note di rilascio.",+ "fullReleaseNotes": "Note di rilascio complete",+ "later": "Più tardi",+ "install": "Installa aggiornamento",+ "installAndRestart": "Installa e riavvia",+ "retry": "Riprova","downloadProgress": "{percent}% · {downloaded} di {total}","downloadProgressUnknown": "{downloaded} scaricati",- "installedTitle": "Aggiornamento installato",- "installed": "OpenPencil {version} è stato installato{size}. Riavvio in corso.",+ "installing": "Installazione…",+ "installed": "OpenPencil {version} è installato",+ "restartToFinish": "Riavvia OpenPencil per iniziare a usare la nuova versione.",+ "restartNow": "Riavvia ora",+ "downloadFailed": "Impossibile scaricare l’aggiornamento: {error}",+ "installFailed": "Impossibile installare l’aggiornamento: {error}",+ "restartFailed": "Impossibile riavviare OpenPencil: {error}","unavailable": "Gli aggiornamenti non sono ancora disponibili. Pubblica prima una release firmata con latest.json.","checkFailed": "Impossibile controllare gli aggiornamenti: {error}"}diff --git a/packages/vue/src/i18n/locales/ja/updates.json b/packages/vue/src/i18n/locales/ja/updates.jsonindex ae8e5f747..c21514f8f 100644--- a/packages/vue/src/i18n/locales/ja/updates.json+++ b/packages/vue/src/i18n/locales/ja/updates.json@@ -1,13 +1,25 @@{"upToDate": "OpenPencilは最新の状態です",- "availableTitle": "OpenPencilのアップデート",- "available": "OpenPencil のバージョン {version} が利用可能です。",- "installPrompt": "今すぐダウンロードしてインストールしますか?インストール後、アプリが再起動します。",- "downloading": "OpenPencil {version} をダウンロード中",+ "windowTitle": "ソフトウェア・アップデート",+ "checking": "アップデートを確認しています…",+ "available": "OpenPencil {version} が利用可能です",+ "currentVersion": "現在のバージョンは {version} です。",+ "whatsNew": "新機能",+ "noNotes": "このリリースにはリリースノートがありません。",+ "fullReleaseNotes": "リリースノートをすべて表示",+ "later": "後で",+ "install": "アップデートをインストール",+ "installAndRestart": "インストールして再起動",+ "retry": "再試行","downloadProgress": "{percent}% · {downloaded} / {total}","downloadProgressUnknown": "{downloaded} をダウンロード済み",- "installedTitle": "アップデート完了",- "installed": "OpenPencil のバージョン {version} がインストールされました{size}。再起動しています...",+ "installing": "インストールしています…",+ "installed": "OpenPencil {version} をインストールしました",+ "restartToFinish": "新しいバージョンを使うには OpenPencil を再起動してください。",+ "restartNow": "今すぐ再起動",+ "downloadFailed": "アップデートをダウンロードできませんでした: {error}",+ "installFailed": "アップデートをインストールできませんでした: {error}",+ "restartFailed": "OpenPencil を再起動できませんでした: {error}","unavailable": "アップデートはまだ利用できません。まず、latest.json を含む署名付きバージョンを公開してください。","checkFailed": "アップデートの確認中にエラーが発生しました: {error}"}diff --git a/packages/vue/src/i18n/locales/pl/updates.json b/packages/vue/src/i18n/locales/pl/updates.jsonindex 2f3ad3c2c..57c0b23c6 100644--- a/packages/vue/src/i18n/locales/pl/updates.json+++ b/packages/vue/src/i18n/locales/pl/updates.json@@ -1,13 +1,25 @@{"upToDate": "OpenPencil jest aktualny",- "availableTitle": "Zaktualizuj OpenPencil",- "available": "OpenPencil {version} jest dostępny.",- "installPrompt": "Pobrać i zainstalować teraz? Aplikacja uruchomi się ponownie po zainstalowaniu aktualizacji.",- "downloading": "Pobieranie OpenPencil {version}",+ "windowTitle": "Uaktualnienie oprogramowania",+ "checking": "Sprawdzanie aktualizacji…",+ "available": "Dostępny jest OpenPencil {version}",+ "currentVersion": "Masz wersję {version}.",+ "whatsNew": "Co nowego",+ "noNotes": "To wydanie nie ma informacji o wydaniu.",+ "fullReleaseNotes": "Pełne informacje o wydaniu",+ "later": "Później",+ "install": "Zainstaluj aktualizację",+ "installAndRestart": "Zainstaluj i uruchom ponownie",+ "retry": "Spróbuj ponownie","downloadProgress": "{percent}% · {downloaded} z {total}","downloadProgressUnknown": "Pobrano {downloaded}",- "installedTitle": "Aktualizacja zainstalowana",- "installed": "OpenPencil {version} został zainstalowany{size}. Ponowne uruchamianie.",+ "installing": "Instalowanie…",+ "installed": "Zainstalowano OpenPencil {version}",+ "restartToFinish": "Uruchom ponownie OpenPencil, aby korzystać z nowej wersji.",+ "restartNow": "Uruchom ponownie teraz",+ "downloadFailed": "Nie udało się pobrać aktualizacji: {error}",+ "installFailed": "Nie udało się zainstalować aktualizacji: {error}",+ "restartFailed": "Nie udało się ponownie uruchomić OpenPencil: {error}","unavailable": "Aktualizacje nie są jeszcze dostępne. Najpierw opublikuj podpisane wydanie z latest.json.","checkFailed": "Nie udało się sprawdzić aktualizacji: {error}"}diff --git a/packages/vue/src/i18n/locales/ru/updates.json b/packages/vue/src/i18n/locales/ru/updates.jsonindex 03c4117ee..214942e5f 100644--- a/packages/vue/src/i18n/locales/ru/updates.json+++ b/packages/vue/src/i18n/locales/ru/updates.json@@ -1,13 +1,25 @@{"upToDate": "OpenPencil обновлён до последней версии",- "availableTitle": "Обновить OpenPencil",- "available": "Доступен OpenPencil {version}.",- "installPrompt": "Скачать и установить сейчас? После установки обновления приложение перезапустится.",- "downloading": "Загрузка OpenPencil {version}",+ "windowTitle": "Обновление ПО",+ "checking": "Проверка обновлений…",+ "available": "Доступен OpenPencil {version}",+ "currentVersion": "У вас версия {version}.",+ "whatsNew": "Что нового",+ "noNotes": "У этого выпуска нет примечаний.",+ "fullReleaseNotes": "Все примечания к выпуску",+ "later": "Позже",+ "install": "Установить обновление",+ "installAndRestart": "Установить и перезапустить",+ "retry": "Повторить","downloadProgress": "{percent}% · {downloaded} из {total}","downloadProgressUnknown": "Загружено {downloaded}",- "installedTitle": "Обновление установлено",- "installed": "OpenPencil {version} установлен{size}. Перезапуск.",+ "installing": "Установка…",+ "installed": "OpenPencil {version} установлен",+ "restartToFinish": "Перезапустите OpenPencil, чтобы начать пользоваться новой версией.",+ "restartNow": "Перезапустить",+ "downloadFailed": "Не удалось загрузить обновление: {error}",+ "installFailed": "Не удалось установить обновление: {error}",+ "restartFailed": "Не удалось перезапустить OpenPencil: {error}","unavailable": "Обновления пока недоступны. Сначала опубликуйте подписанный релиз с latest.json.","checkFailed": "Не удалось проверить обновления: {error}"}diff --git a/packages/vue/src/i18n/locales/zh-cn/updates.json b/packages/vue/src/i18n/locales/zh-cn/updates.jsonindex 7c2a7d28a..efbf6e7ac 100644--- a/packages/vue/src/i18n/locales/zh-cn/updates.json+++ b/packages/vue/src/i18n/locales/zh-cn/updates.json@@ -1,13 +1,25 @@{"upToDate": "OpenPencil 已是最新版本",- "availableTitle": "更新 OpenPencil",- "available": "OpenPencil {version} 可用。",- "installPrompt": "现在下载并安装吗?安装更新后应用将重新启动。",- "downloading": "正在下载 OpenPencil {version}",+ "windowTitle": "软件更新",+ "checking": "正在检查更新…",+ "available": "OpenPencil {version} 现已推出",+ "currentVersion": "你当前的版本是 {version}。",+ "whatsNew": "新功能",+ "noNotes": "此版本没有发行说明。",+ "fullReleaseNotes": "完整发行说明",+ "later": "稍后",+ "install": "安装更新",+ "installAndRestart": "安装并重新启动",+ "retry": "重试","downloadProgress": "{percent}% · {downloaded} / {total}","downloadProgressUnknown": "已下载 {downloaded}",- "installedTitle": "更新已安装",- "installed": "OpenPencil {version} 已安装{size}。正在重新启动。",+ "installing": "正在安装…",+ "installed": "OpenPencil {version} 已安装",+ "restartToFinish": "重新启动 OpenPencil 以开始使用新版本。",+ "restartNow": "立即重新启动",+ "downloadFailed": "无法下载更新:{error}",+ "installFailed": "无法安装更新:{error}",+ "restartFailed": "无法重新启动 OpenPencil:{error}","unavailable": "更新暂不可用。请先发布包含 latest.json 的已签名版本。","checkFailed": "无法检查更新:{error}"}diff --git a/packages/vue/src/i18n/messages/updates.ts b/packages/vue/src/i18n/messages/updates.tsindex d948919f5..331424f54 100644--- a/packages/vue/src/i18n/messages/updates.ts+++ b/packages/vue/src/i18n/messages/updates.ts@@ -4,14 +4,26 @@ import { i18n } from '#vue/i18n/create'export const updatesMessageDefaults = {upToDate: 'OpenPencil is up to date',- availableTitle: 'Update OpenPencil',- available: params('OpenPencil {version} is available.'),- installPrompt: 'Download and install it now? The app will restart after the update is installed.',- downloading: params('Downloading OpenPencil {version}'),+ windowTitle: 'Software Update',+ checking: 'Checking for updates…',+ available: params('OpenPencil {version} is available'),+ currentVersion: params('You have version {version}.'),+ whatsNew: 'What’s new',+ noNotes: 'This release has no release notes.',+ fullReleaseNotes: 'Full release notes',+ later: 'Later',+ install: 'Install Update',+ installAndRestart: 'Install and Restart',+ retry: 'Try Again',downloadProgress: params('{percent}% · {downloaded} of {total}'),downloadProgressUnknown: params('{downloaded} downloaded'),- installedTitle: 'Update installed',- installed: params('OpenPencil {version} was installed{size}. Restarting now.'),+ installing: 'Installing…',+ installed: params('OpenPencil {version} is installed'),+ restartToFinish: 'Restart OpenPencil to start using the new version.',+ restartNow: 'Restart Now',+ downloadFailed: params('Could not download the update: {error}'),+ installFailed: params('Could not install the update: {error}'),+ restartFailed: params('Could not restart OpenPencil: {error}'),unavailable: 'Updates are not available yet. Publish a signed release with latest.json first.',checkFailed: params('Could not check for updates: {error}')} as constdiff --git a/src/App.vue b/src/App.vueindex 2ba2bf4aa..516ceca9d 100644--- a/src/App.vue+++ b/src/App.vue@@ -12,7 +12,8 @@ import { useFollowingEditorStore } from '@/app/editor/active-store'import { animationsEnabled } from '@/app/shell/motion'import { useAppTheme } from '@/app/shell/theme'import { toast } from '@/app/shell/ui'-import { scheduleStartupUpdateCheck } from '@/app/shell/updater'+import { useRestartApprovals } from '@/app/shell/updater/approvals'+import { scheduleStartupUpdateCheck } from '@/app/shell/updater/check'import { kickSyncEngine } from '@/app/storage/sync'import { prepareForReload } from '@/app/tabs'import UnsavedChangesDialog from '@/components/document/UnsavedChangesDialog.vue'@@ -36,6 +37,7 @@ useHead({provideEditor(useFollowingEditorStore())useAppTheme()useDocumentCloseProtection()+useRestartApprovals()useEventListener(window, 'pagehide', () => {void prepareForReload()})diff --git a/src/app.css b/src/app.cssindex 6298d0141..41ee58822 100644--- a/src/app.css+++ b/src/app.css@@ -1,7 +1,7 @@@import 'tailwindcss';@import 'tw-animate-css';@import 'vue-stream-markdown/index.css' layer(components);-@import './theme/chat/markdown.css';+@import './theme/markdown/markdown.css';@custom-variant motion-safe {@media (prefers-reduced-motion: no-preference) {diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.tsindex 38fcf3688..f9dbd2d74 100644--- a/src/app/shell/menu/shell.ts+++ b/src/app/shell/menu/shell.ts@@ -12,7 +12,7 @@ import { useNativeMenuEvents } from '@/app/shell/menu/native-events'import { openStorageWorkspace } from '@/app/shell/menu/navigation'import { APP_MENU_SCHEMA, type AppMenuEntry } from '@/app/shell/menu/schema'import { useAppTheme } from '@/app/shell/theme'-import { checkForAppUpdate } from '@/app/shell/updater'+import { checkForAppUpdate } from '@/app/shell/updater/check'import { isTauri } from '@/app/tauri/env'function shellMenuIds(entries: readonly AppMenuEntry[]): string[] {diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.tsindex eca8c78af..75853eb27 100644--- a/src/app/shell/ui.ts+++ b/src/app/shell/ui.ts@@ -3,9 +3,10 @@ import { ref } from 'vue'import { recordRuntimeError } from '@/app/diagnostics'import { isTauri } from '@/app/tauri/env'-import type { ToastProgress, ToastVariant } from '@/components/ui/feedback/toast'+import type { ProgressAmount } from '@/components/ui/feedback/progress'+import type { ToastVariant } from '@/components/ui/feedback/toast'-export type { ToastProgress, ToastVariant } from '@/components/ui/feedback/toast'+export type { ToastVariant } from '@/components/ui/feedback/toast'export interface ToastAction {label: string@@ -20,7 +21,7 @@ export interface Toast {count: numberaction?: ToastAction/** Present while a long-running operation behind this toast reports progress. */- progress?: ToastProgress+ progress?: ProgressAmount/** Measurement text beside the progress bar, formatted by the producing domain. */progressLabel?: string}@@ -28,7 +29,7 @@ export interface Toast {export interface ToastPatch {message?: string/** `null` clears the bar, which resumes the toast's normal auto-dismissal. */- progress?: ToastProgress | null+ progress?: ProgressAmount | null/** `null` removes the measurement line. */progressLabel?: string | null}@@ -83,7 +84,7 @@ export function toastDuration(entry: Toast): number {function startProgress(message: string,- options: { variant?: ToastVariant; progress?: ToastProgress; progressLabel?: string } = {}+ options: { variant?: ToastVariant; progress?: ProgressAmount; progressLabel?: string } = {}): ToastHandle {const id = ++nextIdtoasts.value.push({diff --git a/src/app/shell/updater.ts b/src/app/shell/updater.tsdeleted file mode 100644index 434d651ec..000000000--- a/src/app/shell/updater.ts+++ /dev/null@@ -1,157 +0,0 @@-import { promiseTimeout } from '@vueuse/core'-import type { Ref } from 'vue'--import { toast } from '@/app/shell/ui'-import { isTauri } from '@/app/tauri/env'--const STARTUP_UPDATE_CHECK_DELAY_MS = 2500--interface UpdaterMessages {- upToDate: string- availableTitle: string- available: (params: { version: string }) => string- installPrompt: string- downloading: (params: { version: string }) => string- downloadProgress: (params: { percent: number; downloaded: string; total: string }) => string- downloadProgressUnknown: (params: { downloaded: string }) => string- installedTitle: string- installed: (params: { version: string; size: string }) => string- unavailable: string- checkFailed: (params: { error: string }) => string-}--interface UpdateCheckOptions {- silent?: boolean- messages: Ref<UpdaterMessages>-}--let startupCheckStarted = false-let updateCheckInFlight: Promise<void> | null = null--export async function checkForAppUpdate(options: UpdateCheckOptions) {- if (!isTauri()) return- if (updateCheckInFlight) return updateCheckInFlight-- const { silent = false, messages } = options- updateCheckInFlight = runUpdateCheck(silent, messages).finally(() => {- updateCheckInFlight = null- })- return updateCheckInFlight-}--export function scheduleStartupUpdateCheck(messages: Ref<UpdaterMessages>) {- if (startupCheckStarted || !isTauri()) return- startupCheckStarted = true- void promiseTimeout(STARTUP_UPDATE_CHECK_DELAY_MS).then(() =>- checkForAppUpdate({ silent: true, messages })- )-}--async function runUpdateCheck(silent: boolean, messages: Ref<UpdaterMessages>) {- try {- const [{ check }, { confirm, message }, { relaunch }] = await Promise.all([- import('@tauri-apps/plugin-updater'),- import('@tauri-apps/plugin-dialog'),- import('@tauri-apps/plugin-process')- ])-- const update = await check()- const t = messages.value-- if (!update) {- if (!silent) toast.info(t.upToDate)- return- }-- const details = [- t.available({ version: update.version }),- update.body ? `\n${update.body}` : '',- `\n${t.installPrompt}`- ].join('')-- const shouldInstall = await confirm(details, {- title: t.availableTitle,- kind: 'info'- })-- if (!shouldInstall) return-- let downloaded = 0- let contentLength: number | undefined- const progressToast = toast.startProgress(t.downloading({ version: update.version }))- let reportedLabel = ''-- // Skip chunks that leave the displayed percentage and rounded byte counts- // unchanged. This deduplicates labels; it is not a fixed-rate throttle.- const reportProgress = () => {- const label = downloadProgressLabel(t, downloaded, contentLength)- if (label === reportedLabel) return- reportedLabel = label- progressToast.update({- progressLabel: label,- progress: contentLength ? { value: downloaded, max: contentLength } : { value: downloaded }- })- }-- try {- await update.downloadAndInstall((event) => {- if (event.event === 'Started') {- contentLength = event.data.contentLength- reportProgress()- return- }- if (event.event === 'Progress') {- downloaded += event.data.chunkLength- reportProgress()- }- })- } finally {- // Dismissed on failure too: a toast with a progress bar never expires on its own.- progressToast.dismiss()- }-- const sizeLabel = contentLength- ? ` (${formatBytes(downloaded)} of ${formatBytes(contentLength)})`- : ''- await message(t.installed({ version: update.version, size: sizeLabel }), {- title: t.installedTitle,- kind: 'info'- })- await relaunch()- } catch (error) {- if (!silent) {- const errorMessage = error instanceof Error ? error.message : String(error)- toast.warning(- isMissingUpdateManifestError(errorMessage)- ? messages.value.unavailable- : messages.value.checkFailed({ error: errorMessage })- )- }- }-}--function isMissingUpdateManifestError(message: string) {- return message.toLowerCase().includes('valid release json')-}--function downloadProgressLabel(- messages: UpdaterMessages,- downloaded: number,- contentLength?: number-) {- if (!contentLength)- return messages.downloadProgressUnknown({ downloaded: formatBytes(downloaded) })- const percent = Math.min(100, Math.max(0, Math.round((downloaded / contentLength) * 100)))- return messages.downloadProgress({- percent,- downloaded: formatBytes(downloaded),- total: formatBytes(contentLength)- })-}--function formatBytes(bytes: number) {- if (bytes < 1024) return `${bytes} B`- const kib = bytes / 1024- if (kib < 1024) return `${kib.toFixed(1)} KiB`- return `${(kib / 1024).toFixed(1)} MiB`-}diff --git a/src/app/shell/updater/approvals.ts b/src/app/shell/updater/approvals.tsnew file mode 100644index 000000000..8207c6ba2--- /dev/null+++ b/src/app/shell/updater/approvals.ts@@ -0,0 +1,39 @@+import * as v from 'valibot'+import { onScopeDispose } from 'vue'++import { confirmAppExit } from '@/app/document/close/exit'+import { isTauri } from '@/app/tauri/env'++import { RESTART_REPLY_EVENT, RESTART_REQUEST_EVENT, RestartRequest } from './restart'+import { UPDATER_WINDOW_LABEL } from './window'++/** Lets the editor window answer restart requests from the Software Update window. */+export function useRestartApprovals(): void {+ if (!isTauri()) return+ let stop: (() => void) | undefined+ let disposed = false++ async function register() {+ const { emitTo, listen } = await import('@tauri-apps/api/event')+ const unlisten = await listen<unknown>(RESTART_REQUEST_EVENT, ({ payload }) => {+ const parsed = v.safeParse(RestartRequest, payload)+ if (!parsed.success) return+ const { id } = parsed.output+ // Always answer, so the Software Update window never waits on a failed prompt.+ void confirmAppExit()+ .catch((error: unknown) => {+ console.error('[Updater] Could not ask about unsaved documents', error)+ return false+ })+ .then((approved) => emitTo(UPDATER_WINDOW_LABEL, RESTART_REPLY_EVENT, { id, approved }))+ })+ if (disposed) unlisten()+ else stop = unlisten+ }+ void register()++ onScopeDispose(() => {+ disposed = true+ stop?.()+ })+}diff --git a/src/app/shell/updater/check.ts b/src/app/shell/updater/check.tsnew file mode 100644index 000000000..b3571e8db--- /dev/null+++ b/src/app/shell/updater/check.ts@@ -0,0 +1,57 @@+import { promiseTimeout } from '@vueuse/core'+import type { Ref } from 'vue'++import { toast } from '@/app/shell/ui'+import { isTauri } from '@/app/tauri/env'++import { updateFailureText, type UpdaterMessages } from './messages'+import { openUpdaterWindow } from './window'++const STARTUP_UPDATE_CHECK_DELAY_MS = 2500++interface UpdateCheckOptions {+ silent?: boolean+ messages: Ref<UpdaterMessages>+}++let startupCheckStarted = false+let updateCheckInFlight: Promise<void> | null = null++export async function checkForAppUpdate(options: UpdateCheckOptions) {+ if (!isTauri()) return+ if (updateCheckInFlight) return updateCheckInFlight++ const { silent = false, messages } = options+ updateCheckInFlight = runUpdateCheck(silent, messages).finally(() => {+ updateCheckInFlight = null+ })+ return updateCheckInFlight+}++export function scheduleStartupUpdateCheck(messages: Ref<UpdaterMessages>) {+ if (startupCheckStarted || !isTauri()) return+ startupCheckStarted = true+ void promiseTimeout(STARTUP_UPDATE_CHECK_DELAY_MS).then(() =>+ checkForAppUpdate({ silent: true, messages })+ )+}++// The main window only learns whether an update exists; the Software Update+// window checks again for its own handle, then shows the notes and installs.+async function runUpdateCheck(silent: boolean, messages: Ref<UpdaterMessages>) {+ try {+ const { check } = await import('@tauri-apps/plugin-updater')+ const update = await check()+ if (!update) {+ if (!silent) toast.info(messages.value.upToDate)+ return+ }+ await update.close()+ await openUpdaterWindow(messages.value.windowTitle)+ } catch (error) {+ if (!silent) {+ const message = error instanceof Error ? error.message : String(error)+ toast.warning(updateFailureText(messages.value, 'check', message))+ }+ }+}diff --git a/src/app/shell/updater/messages.ts b/src/app/shell/updater/messages.tsnew file mode 100644index 000000000..2599e37d8--- /dev/null+++ b/src/app/shell/updater/messages.ts@@ -0,0 +1,18 @@+import type { useI18n } from '@open-pencil/vue'++export type UpdaterMessages = ReturnType<typeof useI18n>['updates']['value']++export type UpdateFailureStep = 'check' | 'download' | 'install' | 'restart'++/** Translated text for an updater failure; a missing manifest means no signed release yet. */+export function updateFailureText(+ messages: UpdaterMessages,+ step: UpdateFailureStep,+ error: string+): string {+ if (step === 'download') return messages.downloadFailed({ error })+ if (step === 'install') return messages.installFailed({ error })+ if (step === 'restart') return messages.restartFailed({ error })+ if (error.toLowerCase().includes('valid release json')) return messages.unavailable+ return messages.checkFailed({ error })+}diff --git a/src/app/shell/updater/progress.ts b/src/app/shell/updater/progress.tsnew file mode 100644index 000000000..5a73eec16--- /dev/null+++ b/src/app/shell/updater/progress.ts@@ -0,0 +1,27 @@+import { progressPercent } from '@/components/ui/feedback/progress'++import type { UpdaterMessages } from './messages'++export interface DownloadProgress {+ downloaded: number+ total?: number+}++export function downloadProgressLabel(+ messages: UpdaterMessages,+ { downloaded, total }: DownloadProgress+): string {+ if (!total) return messages.downloadProgressUnknown({ downloaded: formatBytes(downloaded) })+ return messages.downloadProgress({+ percent: progressPercent({ value: downloaded, max: total }) ?? 0,+ downloaded: formatBytes(downloaded),+ total: formatBytes(total)+ })+}++export function formatBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`+ const kib = bytes / 1024+ if (kib < 1024) return `${kib.toFixed(1)} KiB`+ return `${(kib / 1024).toFixed(1)} MiB`+}diff --git a/src/app/shell/updater/restart.ts b/src/app/shell/updater/restart.tsnew file mode 100644index 000000000..e3004e33e--- /dev/null+++ b/src/app/shell/updater/restart.ts@@ -0,0 +1,42 @@+import * as v from 'valibot'++import { randomHex } from '@open-pencil/scene-graph/random'++import { createDeferred } from '@/app/runtime/deferred'++// The Software Update window owns no documents, so it asks the editor window+// to run the same unsaved-changes approval as Quit before the app restarts.+export const RESTART_REQUEST_EVENT = 'updater:restart-request'+export const RESTART_REPLY_EVENT = 'updater:restart-reply'+export const EDITOR_WINDOW_LABEL = 'main'++export const RestartRequest = v.object({ id: v.string() })+export const RestartReply = v.object({ id: v.string(), approved: v.boolean() })++/** Called from the Software Update window; resolves true once the editor's documents may close. */+export async function requestRestartApproval(): Promise<boolean> {+ const [{ emitTo, listen, TauriEvent }, { WebviewWindow }] = await Promise.all([+ import('@tauri-apps/api/event'),+ import('@tauri-apps/api/webviewWindow')+ ])+ const editor = await WebviewWindow.getByLabel(EDITOR_WINDOW_LABEL)+ if (!editor) return true++ const id = randomHex(8)+ const reply = createDeferred<boolean>()+ const stopReply = await listen<unknown>(RESTART_REPLY_EVENT, ({ payload }) => {+ const parsed = v.safeParse(RestartReply, payload)+ if (parsed.success && parsed.output.id === id) reply.resolve(parsed.output.approved)+ })+ // No timeout: the reply waits for the person to answer the unsaved-documents prompt.+ // An editor closed meanwhile has run its own prompt and holds no documents, so it approves.+ const stopDestroyed = await editor.once(TauriEvent.WINDOW_DESTROYED, () => reply.resolve(true))+ if (!(await WebviewWindow.getByLabel(EDITOR_WINDOW_LABEL))) reply.resolve(true)+ try {+ await emitTo(EDITOR_WINDOW_LABEL, RESTART_REQUEST_EVENT, { id })+ return await reply.promise+ } finally {+ stopReply()+ stopDestroyed()+ }+}diff --git a/src/app/shell/updater/session.ts b/src/app/shell/updater/session.tsnew file mode 100644index 000000000..5c8663a4c--- /dev/null+++ b/src/app/shell/updater/session.ts@@ -0,0 +1,258 @@+import type { DownloadEvent } from '@tauri-apps/plugin-updater'+import { shallowRef, type ShallowRef } from 'vue'++import type { UpdateFailureStep } from './messages'+import type { DownloadProgress } from './progress'+import { requestRestartApproval } from './restart'++export interface ReleaseInfo {+ version: string+ currentVersion: string+ /** The release's `CHANGELOG.md` section, as Markdown. */+ notes: string+}++export type UpdaterState =+ | { status: 'checking' }+ | { status: 'up-to-date' }+ | { status: 'available'; release: ReleaseInfo }+ | { status: 'downloading'; release: ReleaseInfo; progress: DownloadProgress }+ | { status: 'installing'; release: ReleaseInfo }+ /** Installed on disk (macOS and Linux); it runs once the app restarts. */+ | { status: 'installed'; release: ReleaseInfo }+ | { status: 'failed'; step: UpdateFailureStep; release?: ReleaseInfo; error: string }++/** The slice of a Tauri `Update` the window uses. */+export interface PendingUpdate {+ version: string+ currentVersion: string+ body?: string+ download(onEvent: (event: DownloadEvent) => void): Promise<void>+ install(): Promise<void>+ close(): Promise<void>+}++export interface UpdaterBackend {+ check(): Promise<PendingUpdate | null>+ /** Asks the editor to close its documents, as Quit does; true once they agreed. */+ confirmRestart(): Promise<boolean>+ relaunch(): Promise<void>+ closeWindow(): Promise<void>+ /** Windows installers quit the app themselves, so documents must close before installing. */+ installQuitsApp: boolean+}++export interface UpdaterSession {+ state: ShallowRef<UpdaterState>+ check(): Promise<void>+ install(): Promise<void>+ /** Stops showing the download; it keeps running and a later install reuses it. */+ cancel(): void+ restart(): Promise<void>+ /** Repeats the step that failed. */+ retry(): Promise<void>+ dismiss(): Promise<void>+}++interface Download {+ done: Promise<void>+ progress: DownloadProgress+}++export function createUpdaterSession(backend: UpdaterBackend): UpdaterSession {+ const state = shallowRef<UpdaterState>({ status: 'checking' })+ let pending: PendingUpdate | null = null+ // Tauri cannot abort a download, so cancelling only detaches the window from it.+ let download: Download | null = null+ let attachedTo: Download | null = null++ async function release() {+ const update = pending+ pending = null+ download = null+ attachedTo = null+ await update?.close()+ }++ async function check() {+ state.value = { status: 'checking' }+ try {+ await release()+ pending = await backend.check()+ state.value = pending+ ? { status: 'available', release: releaseInfo(pending) }+ : { status: 'up-to-date' }+ } catch (error) {+ state.value = { status: 'failed', step: 'check', error: errorMessage(error) }+ }+ }++ function startDownload(update: PendingUpdate): Download {+ const progress: DownloadProgress = { downloaded: 0 }+ const info = releaseInfo(update)+ const current: Download = {+ progress,+ done: update.download((event) => {+ if (event.event === 'Started') progress.total = event.data.contentLength+ else if (event.event === 'Progress') progress.downloaded += event.data.chunkLength+ else return+ if (attachedTo === current) {+ state.value = { status: 'downloading', release: info, progress: { ...progress } }+ }+ })+ }+ // A failed download is never reused; the next install starts another.+ current.done.catch(() => {+ if (download === current) download = null+ })+ return current+ }++ // A function, so the check reads the current value after an await.+ function isAttached(target: Download): boolean {+ return attachedTo === target+ }++ async function install() {+ const update = pending+ const current = state.value+ if (!update || (current.status !== 'available' && current.status !== 'failed')) return+ const info = releaseInfo(update)++ download ??= startDownload(update)+ const active = download+ attachedTo = active+ state.value = { status: 'downloading', release: info, progress: { ...active.progress } }++ try {+ await active.done+ } catch (error) {+ if (isAttached(active)) {+ attachedTo = null+ state.value = {+ status: 'failed',+ step: 'download',+ release: info,+ error: errorMessage(error)+ }+ }+ return+ }+ if (!isAttached(active)) return++ if (backend.installQuitsApp) {+ // The installer quits the app, so the editor's documents must agree to close first.+ let approved: boolean+ try {+ approved = await backend.confirmRestart()+ } catch (error) {+ if (isAttached(active)) {+ state.value = {+ status: 'failed',+ step: 'install',+ release: info,+ error: errorMessage(error)+ }+ }+ attachedTo = null+ return+ }+ // Cancel or Later while the editor was asking wins over a late approval.+ if (!isAttached(active)) return+ if (!approved) {+ attachedTo = null+ state.value = { status: 'available', release: info }+ return+ }+ }+ attachedTo = null++ state.value = { status: 'installing', release: info }+ try {+ await update.install()+ } catch (error) {+ download = null+ state.value = { status: 'failed', step: 'install', release: info, error: errorMessage(error) }+ return+ }+ state.value = { status: 'installed', release: info }+ }++ function cancel() {+ const current = state.value+ if (current.status !== 'downloading') return+ attachedTo = null+ state.value = { status: 'available', release: current.release }+ }++ let restarting = false++ async function restart() {+ const current = state.value+ if (current.status !== 'installed' || restarting) return+ restarting = true+ try {+ if (!(await backend.confirmRestart())) return+ await backend.relaunch()+ } catch (error) {+ state.value = {+ status: 'failed',+ step: 'restart',+ release: current.release,+ error: errorMessage(error)+ }+ } finally {+ restarting = false+ }+ }++ async function retry() {+ const current = state.value+ if (current.status !== 'failed') return+ if (!current.release || !pending || current.step === 'check') return check()+ if (current.step === 'restart') {+ state.value = { status: 'installed', release: current.release }+ return restart()+ }+ return install()+ }++ async function dismiss() {+ if (state.value.status === 'installing') return+ await release()+ await backend.closeWindow()+ }++ return { state, check, install, cancel, restart, retry, dismiss }+}++function releaseInfo(update: PendingUpdate): ReleaseInfo {+ return {+ version: update.version,+ currentVersion: update.currentVersion,+ notes: update.body?.trim() ?? ''+ }+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++export function createTauriUpdaterBackend(): UpdaterBackend {+ return {+ async check() {+ const { check } = await import('@tauri-apps/plugin-updater')+ return check()+ },+ confirmRestart: requestRestartApproval,+ async relaunch() {+ const { relaunch } = await import('@tauri-apps/plugin-process')+ await relaunch()+ },+ async closeWindow() {+ const { getCurrentWindow } = await import('@tauri-apps/api/window')+ await getCurrentWindow().close()+ },+ installQuitsApp: navigator.userAgent.includes('Windows')+ }+}diff --git a/src/app/shell/updater/window.ts b/src/app/shell/updater/window.tsnew file mode 100644index 000000000..47aab1843--- /dev/null+++ b/src/app/shell/updater/window.ts@@ -0,0 +1,34 @@+export const UPDATER_WINDOW_LABEL = 'updater'+/** Separate Vite entry, so the window never boots the editor. */+export const UPDATER_WINDOW_URL = 'updater.html'++const UPDATER_WINDOW_WIDTH = 560+const UPDATER_WINDOW_HEIGHT = 520++/** Shows the Software Update window, focusing it when it is already open. */+export async function openUpdaterWindow(title: string): Promise<void> {+ const { WebviewWindow } = await import('@tauri-apps/api/webviewWindow')+ const existing = await WebviewWindow.getByLabel(UPDATER_WINDOW_LABEL)+ if (existing) {+ await existing.unminimize()+ await existing.setFocus()+ return+ }++ const window = new WebviewWindow(UPDATER_WINDOW_LABEL, {+ url: UPDATER_WINDOW_URL,+ title,+ width: UPDATER_WINDOW_WIDTH,+ height: UPDATER_WINDOW_HEIGHT,+ minWidth: UPDATER_WINDOW_WIDTH,+ minHeight: UPDATER_WINDOW_HEIGHT,+ center: true,+ minimizable: false,+ maximizable: false,+ dragDropEnabled: false,+ focus: true+ })+ await window.once<unknown>('tauri://error', (event) => {+ console.error('Could not open the Software Update window', event.payload)+ })+}diff --git a/src/components/chat/ChatMarkdown.vue b/src/components/chat/ChatMarkdown.vueindex 418c7a0d2..ce437f6e6 100644--- a/src/components/chat/ChatMarkdown.vue+++ b/src/components/chat/ChatMarkdown.vue@@ -1,15 +1,8 @@<script setup lang="ts">import { computed } from 'vue'-import { Markdown } from 'vue-stream-markdown'-import { IS_BROWSER } from '@open-pencil/core/constants'--import { createMarkdownHardenOptions, markdownExtensions } from '@/app/shell/markdown/config'import { markdownRenderKey, type MarkdownSurface } from '@/app/shell/markdown/state'-import { animationsEnabled } from '@/app/shell/motion'-import { resolvedAppTheme } from '@/app/shell/theme'-import InlineCode from '@/components/chat/markdown/InlineCode.vue'-import { chatMarkdownTheme } from '@/theme/chat/markdown'+import MarkdownContent from '@/components/markdown/MarkdownContent.vue'const {content,@@ -21,30 +14,16 @@ const {surface?: MarkdownSurface}>()-const isDark = computed(() => resolvedAppTheme.value === 'dark')-const ui = chatMarkdownTheme()-const markdownComponents = { code: InlineCode }-const hardenOptions = computed(() =>- createMarkdownHardenOptions(IS_BROWSER ? window.location.origin : 'http://localhost/')-)const renderKey = computed(() => markdownRenderKey({ mode, surface }))</script><template>- <div data-slot="chat-markdown" :class="ui.root()">- <Markdown- :key="renderKey"- :components="markdownComponents"- :content="content"- :is-dark="isDark"- :enable-animate="animationsEnabled"- :mode="mode"- :extensions="markdownExtensions"- :harden-options="hardenOptions"- :previewers="false"- :controls="{ code: { download: false, fullscreen: false } }"- :data-chat-markdown-mode="mode"- :class="ui.markdown()"- />- </div>+ <MarkdownContent+ :key="renderKey"+ data-slot="chat-markdown"+ :content="content"+ :mode="mode"+ density="compact"+ highlight-code+ /></template>diff --git a/src/components/chat/markdown/InlineCode.vue b/src/components/markdown/InlineCode.vuesimilarity index 67%rename from src/components/chat/markdown/InlineCode.vuerename to src/components/markdown/InlineCode.vueindex 843caf9fb..0b49c636c 100644--- a/src/components/chat/markdown/InlineCode.vue+++ b/src/components/markdown/InlineCode.vue@@ -7,7 +7,7 @@ const { node: _node } = defineProps<MarkdownComponentProps>()<template><codedata-stream-markdown="inline-code"- class="rounded bg-hover px-1 py-px font-mono text-[11px] leading-4 text-surface break-words whitespace-normal"+ class="rounded bg-hover px-1 py-px font-mono text-[length:inherit] leading-[inherit] text-surface break-words whitespace-normal"dir="ltr"><slot />diff --git a/src/components/markdown/MarkdownContent.vue b/src/components/markdown/MarkdownContent.vuenew file mode 100644index 000000000..ea2fcfcbd--- /dev/null+++ b/src/components/markdown/MarkdownContent.vue@@ -0,0 +1,54 @@+<script setup lang="ts">+import { computed } from 'vue'+import { Markdown } from 'vue-stream-markdown'++import { IS_BROWSER } from '@open-pencil/core/constants'++import { createMarkdownHardenOptions, markdownExtensions } from '@/app/shell/markdown/config'+import { animationsEnabled } from '@/app/shell/motion'+import { resolvedAppTheme } from '@/app/shell/theme'+import InlineCode from '@/components/markdown/InlineCode.vue'+import { markdownTheme, type MarkdownDensity } from '@/theme/markdown'++const {+ content,+ mode = 'static',+ density = 'compact',+ highlightCode = false,+ class: className+} = defineProps<{+ content: string+ mode?: 'static' | 'streaming'+ density?: MarkdownDensity+ /** Loads Shiki for fenced code blocks; leave off where code is rare. */+ highlightCode?: boolean+ class?: string+}>()++const isDark = computed(() => resolvedAppTheme.value === 'dark')+const ui = markdownTheme()+const markdownComponents = { code: InlineCode }+const extensions = computed(() => (highlightCode ? markdownExtensions : undefined))+const hardenOptions = computed(() =>+ createMarkdownHardenOptions(IS_BROWSER ? window.location.origin : 'http://localhost/')+)+</script>++<template>+ <div data-slot="markdown" :class="ui.root({ class: className })">+ <Markdown+ :components="markdownComponents"+ :content="content"+ :is-dark="isDark"+ :enable-animate="animationsEnabled"+ :mode="mode"+ :extensions="extensions"+ :harden-options="hardenOptions"+ :previewers="false"+ :controls="{ code: { download: false, fullscreen: false } }"+ :data-markdown-mode="mode"+ :data-markdown-density="density"+ :class="ui.markdown()"+ />+ </div>+</template>diff --git a/src/components/ui/feedback/AppPlaceholder.vue b/src/components/ui/feedback/AppPlaceholder.vueindex ea1aaa0ed..ee2791fc5 100644--- a/src/components/ui/feedback/AppPlaceholder.vue+++ b/src/components/ui/feedback/AppPlaceholder.vue@@ -19,7 +19,7 @@ const {} = defineProps<{label: string/** A heading level when the placeholder stands for a whole page or view. */- labelAs?: 'p' | 'h2' | 'h3'+ labelAs?: 'p' | 'h1' | 'h2' | 'h3'description?: stringfill?: booleansize?: PlaceholderVariants['size']diff --git a/src/components/ui/feedback/AppProgress.stories.ts b/src/components/ui/feedback/AppProgress.stories.tsnew file mode 100644index 000000000..8133807c3--- /dev/null+++ b/src/components/ui/feedback/AppProgress.stories.ts@@ -0,0 +1,40 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'++import AppProgress from './AppProgress.vue'+import type { ProgressAmount, ProgressTone } from './progress'++type ProgressStoryArgs = {+ amount: ProgressAmount+ label?: string+ tone?: ProgressTone+}++const meta = {+ title: 'Design System/Progress',+ component: AppProgress,+ args: { amount: { value: 42, max: 100 }, label: '42% · 9.6 MiB of 22.9 MiB' },+ render: (args) => ({+ components: { AppProgress },+ setup: () => ({ args }),+ template: '<div class="w-72 bg-panel p-4"><AppProgress v-bind="args" /></div>'+ })+} satisfies Meta<ProgressStoryArgs>++export default meta+type Story = StoryObj<typeof meta>++export const Determinate: Story = {}++export const Indeterminate: Story = {+ args: { amount: {}, label: 'Installing…' }+}++export const OnColouredSurface: Story = {+ args: { tone: 'current' },+ render: (args) => ({+ components: { AppProgress },+ setup: () => ({ args }),+ template:+ '<div class="w-72 rounded-md bg-accent p-3 text-white"><AppProgress v-bind="args" /></div>'+ })+}diff --git a/src/components/ui/feedback/AppProgress.vue b/src/components/ui/feedback/AppProgress.vuenew file mode 100644index 000000000..eebadfadd--- /dev/null+++ b/src/components/ui/feedback/AppProgress.vue@@ -0,0 +1,60 @@+<script setup lang="ts">+import { ProgressIndicator, ProgressRoot } from 'reka-ui'+import { computed } from 'vue'++import {+ progress as progressTheme,+ progressPercent,+ type ProgressAmount,+ type ProgressTone,+ type ProgressUI+} from './progress'++const {+ amount,+ label,+ ariaLabel,+ tone = 'accent',+ class: className,+ ui+} = defineProps<{+ /** Omit `value` or `max` for work that cannot be measured. */+ amount: ProgressAmount+ /** Measurement text under the bar, formatted by the producing domain. */+ label?: string+ /** Names the bar for assistive technology; defaults to `label`. */+ ariaLabel?: string+ tone?: ProgressTone+ class?: string+ ui?: ProgressUI+}>()++const percent = computed(() => progressPercent(amount))+const styles = computed(() => {+ const theme = progressTheme({ tone })+ return {+ root: theme.root({ class: [className, ui?.root] }),+ track: theme.track({ class: ui?.track }),+ fill: theme.fill({ class: ui?.fill }),+ label: theme.label({ class: ui?.label })+ }+})+</script>++<template>+ <div data-slot="progress" :class="styles.root">+ <ProgressRoot+ :model-value="percent"+ :max="100"+ :aria-label="ariaLabel ?? label"+ :class="styles.track"+ >+ <ProgressIndicator+ data-slot="progress-fill"+ :class="styles.fill"+ :style="percent === null ? undefined : { width: `${percent}%` }"+ />+ </ProgressRoot>+ <p v-if="label" data-slot="progress-label" :class="styles.label">{{ label }}</p>+ </div>+</template>diff --git a/src/components/ui/feedback/AppToast.stories.ts b/src/components/ui/feedback/AppToast.stories.tsindex 9a12a3ee4..66aa01221 100644--- a/src/components/ui/feedback/AppToast.stories.ts+++ b/src/components/ui/feedback/AppToast.stories.ts@@ -5,7 +5,8 @@ import { computed, ref } from 'vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppToast from './AppToast.vue'-import { toastProgressPercent, type ToastProps, type ToastProgress } from './toast'+import { progressPercent, type ProgressAmount } from './progress'+import type { ToastProps } from './toast'const meta = {title: 'Design System/Toast',@@ -105,14 +106,14 @@ export const ProgressLifecycle: Story = {const totalBytes = ref<number | null>(TOTAL_BYTES)const reporting = ref(true)- const progress = computed<ToastProgress | null>(() => {+ const progress = computed<ProgressAmount | null>(() => {if (!reporting.value) return nullreturn totalBytes.value === null? { value: downloaded.value }: { value: downloaded.value, max: totalBytes.value }})const progressLabel = computed(() => {- const percent = toastProgressPercent(progress.value)+ const percent = progressPercent(progress.value)if (percent === null) return `${formatMiB(downloaded.value)} downloaded`return `${percent}% · ${formatMiB(downloaded.value)} of ${formatMiB(totalBytes.value ?? 0)}`})diff --git a/src/components/ui/feedback/AppToast.vue b/src/components/ui/feedback/AppToast.vueindex e283715c0..7f39938ba 100644--- a/src/components/ui/feedback/AppToast.vue+++ b/src/components/ui/feedback/AppToast.vue@@ -5,12 +5,8 @@ import { computed } from 'vue'import Tip from '@/components/ui/overlay/Tip.vue'-import {- toast as toastTheme,- toastProgressPercent,- toastProgressState,- type ToastProps-} from './toast'+import AppProgress from './AppProgress.vue'+import { toast as toastTheme, toastProgressState, type ToastProps } from './toast'const {message,@@ -31,7 +27,6 @@ const emit = defineEmits<{ close: []; action: [] }>()const { copy, copied } = useClipboard({ copiedDuring: 1500 })const state = computed(() => toastProgressState(progress))-const percent = computed(() => toastProgressPercent(progress))const styles = computed(() => {const theme = toastTheme({ tone: variant, progress: state.value })return {@@ -41,9 +36,6 @@ const styles = computed(() => {message: theme.message({ class: ui?.message }),count: theme.count({ class: ui?.count }),progress: theme.progress({ class: ui?.progress }),- progressTrack: theme.progressTrack({ class: ui?.progressTrack }),- progressFill: theme.progressFill({ class: ui?.progressFill }),- progressLabel: theme.progressLabel({ class: ui?.progressLabel }),action: theme.action({ class: ui?.action }),control: theme.control({ class: ui?.control })}@@ -73,25 +65,14 @@ const styles = computed(() => {<ToastDescription :class="styles.message">{{ message }}<span v-if="count > 1" :class="styles.count">×{{ count }}</span></ToastDescription>- <div v-if="state !== 'none'" :class="styles.progress" data-slot="toast-progress">- <div- role="progressbar"- :class="styles.progressTrack"- :aria-label="progressLabel ?? message"- :aria-valuenow="percent ?? undefined"- :aria-valuemin="percent === null ? undefined : 0"- :aria-valuemax="percent === null ? undefined : 100"- >- <div- :class="styles.progressFill"- :style="percent === null ? undefined : { width: `${percent}%` }"- data-slot="toast-progress-fill"- />- </div>- <p v-if="progressLabel" :class="styles.progressLabel" data-slot="toast-progress-label">- {{ progressLabel }}- </p>- </div>+ <AppProgress+ v-if="progress"+ :amount="progress"+ :label="progressLabel"+ :aria-label="progressLabel ?? message"+ tone="current"+ :class="styles.progress"+ /><slot /></div><button v-if="actionLabel" type="button" :class="styles.action" @click="emit('action')">diff --git a/src/components/ui/feedback/progress.ts b/src/components/ui/feedback/progress.tsnew file mode 100644index 000000000..07be5d008--- /dev/null+++ b/src/components/ui/feedback/progress.ts@@ -0,0 +1,23 @@+import { tv, type VariantProps } from 'tailwind-variants'++import type { ComponentUI } from '@/components/ui/types'+import progressTheme from '@/theme/feedback/progress'++export const progress = tv(progressTheme)+export type ProgressUI = ComponentUI<typeof progressTheme>+export type ProgressTone = VariantProps<typeof progress>['tone']++/** Work reported by a long-running operation. */+export interface ProgressAmount {+ /** Completed units. */+ value?: number+ /** Total units; omit alongside `value` when the producer cannot measure the work. */+ max?: number+}++/** The rounded share of the work done, or null when it cannot be measured. */+export function progressPercent(amount?: ProgressAmount | null): number | null {+ if (amount?.value === undefined || amount.max === undefined) return null+ if (amount.max <= 0) return null+ return Math.min(100, Math.max(0, Math.round((amount.value / amount.max) * 100)))+}diff --git a/src/components/ui/feedback/toast.ts b/src/components/ui/feedback/toast.tsindex eb7c0f1ca..eae6cd429 100644--- a/src/components/ui/feedback/toast.ts+++ b/src/components/ui/feedback/toast.ts@@ -3,6 +3,8 @@ import { tv, type VariantProps } from 'tailwind-variants'import type { ComponentUI } from '@/components/ui/types'import toastTheme from '@/theme/feedback/toast'+import { progressPercent, type ProgressAmount } from './progress'+export const toast = tv(toastTheme)export type ToastUI = ComponentUI<typeof toastTheme>export type ToastProgressState = VariantProps<typeof toast>['progress']@@ -10,23 +12,9 @@ export type ToastProgressState = VariantProps<typeof toast>['progress']/** Selects the toast treatment; non-default tones are dismissible and copyable. */export type ToastVariant = 'default' | 'warning' | 'error'-/** Progress reported by a long-running operation behind a toast. */-export interface ToastProgress {- /** Completed units. */- value?: number- /** Total units; omit alongside `value` when the producer cannot measure the work. */- max?: number-}--export function toastProgressPercent(progress?: ToastProgress | null): number | null {- if (progress?.value === undefined || progress.max === undefined) return null- if (progress.max <= 0) return null- return Math.min(100, Math.max(0, Math.round((progress.value / progress.max) * 100)))-}--export function toastProgressState(progress?: ToastProgress | null): ToastProgressState {+export function toastProgressState(progress?: ProgressAmount | null): ToastProgressState {if (!progress) return 'none'- return toastProgressPercent(progress) === null ? 'indeterminate' : 'determinate'+ return progressPercent(progress) === null ? 'indeterminate' : 'determinate'}export interface ToastProps {@@ -35,7 +23,7 @@ export interface ToastProps {/** Number of times this message repeated while it stayed visible. */count?: number/** Present while a long-running operation reports progress. */- progress?: ToastProgress | null+ progress?: ProgressAmount | null/** Measurement text beside the bar, formatted by the producing domain. */progressLabel?: string/** Renders an inline action that emits `action` when pressed. */diff --git a/src/components/updater/UpdatePrompt.stories.ts b/src/components/updater/UpdatePrompt.stories.tsnew file mode 100644index 000000000..37152af55--- /dev/null+++ b/src/components/updater/UpdatePrompt.stories.ts@@ -0,0 +1,110 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'++import type { ReleaseInfo, UpdaterState } from '@/app/shell/updater/session'++import UpdatePrompt from './UpdatePrompt.vue'++const release: ReleaseInfo = {+ version: '0.15.1',+ currentVersion: '0.15.0',+ notes: `### Added++- Configure built-in AI and local MCP tool access independently on a **Tool access** page, including optional extended AI tools and per-target defaults (#584).+- Set the built-in AI's maximum steps per message in Chat settings (#573).+- Open documents and jump to a named layer from \`openpencil://open?file=&node=\` links.++### Changed++- Create new documents with the sRGB colour profile, so Display P3 is reserved for documents that declare it.+- Export diagnostics from Settings only, with a retention count you choose.++### Fixed++- Store colours edited in the colour picker in the document's colour profile, and convert them on the way to the display.+- Let the desktop app use an MCP server you started yourself by allowing the app's own origin by default, instead of requiring \`OPENPENCIL_MCP_CORS_ORIGIN\`.+- Mark unsaved documents and ask whether to save before closing a tab, the desktop window, or the application.+- Update instance text properties on the canvas while typing, with grouped undo for rapid edits.+- Point Homebrew installation instructions to the official [\`openpencil\` cask](https://formulae.brew.sh/cask/openpencil).++### Performance++- Reduce editor pauses while generating recovery snapshots and exporting text-heavy \`.fig\` documents.+- Recompute layout only for the pages an edit affects, instead of every page.`+}++type Args = { state: UpdaterState; currentVersion: string; installQuitsApp?: boolean }+type Story = StoryObj<Args>++const meta = {+ title: 'Shell/Update Prompt',+ component: UpdatePrompt,+ parameters: { layout: 'centered' },+ args: { currentVersion: '0.15.0' },+ render: (args) => ({+ components: { UpdatePrompt },+ setup: () => ({ args }),+ // The size the Software Update window opens at.+ template:+ '<div class="h-[520px] w-[560px] overflow-hidden rounded-lg border border-border"><UpdatePrompt v-bind="args" /></div>'+ })+} satisfies Meta<Args>++export default meta++export const Available: Story = {+ args: { state: { status: 'available', release } }+}++export const WithoutNotes: Story = {+ args: { state: { status: 'available', release: { ...release, notes: '' } } }+}++export const Downloading: Story = {+ args: {+ state: {+ status: 'downloading',+ release,+ progress: { downloaded: 23_500_000, total: 61_200_000 }+ }+ }+}++export const DownloadingUnknownSize: Story = {+ args: { state: { status: 'downloading', release, progress: { downloaded: 23_500_000 } } }+}++export const AvailableOnWindows: Story = {+ args: { state: { status: 'available', release }, installQuitsApp: true }+}++export const DownloadFailed: Story = {+ args: {+ state: { status: 'failed', step: 'download', release, error: 'connection reset' }+ }+}++export const Installed: Story = {+ args: { state: { status: 'installed', release } }+}++export const Installing: Story = {+ args: { state: { status: 'installing', release } }+}++export const InstallFailed: Story = {+ args: {+ state: { status: 'failed', step: 'install', release, error: 'signature verification failed' }+ }+}++export const Checking: Story = {+ args: { state: { status: 'checking' } }+}++export const UpToDate: Story = {+ args: { state: { status: 'up-to-date' } }+}++export const CheckFailed: Story = {+ args: { state: { status: 'failed', step: 'check', error: 'network unreachable' } }+}diff --git a/src/components/updater/UpdatePrompt.vue b/src/components/updater/UpdatePrompt.vuenew file mode 100644index 000000000..54fa64045--- /dev/null+++ b/src/components/updater/UpdatePrompt.vue@@ -0,0 +1,177 @@+<script setup lang="ts">+import { mapValues } from 'es-toolkit'+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { openExternalLink } from '@/app/shell/ui'+import { updateFailureText } from '@/app/shell/updater/messages'+import { downloadProgressLabel } from '@/app/shell/updater/progress'+import type { UpdaterState } from '@/app/shell/updater/session'+import BrandMark from '@/components/brand/BrandMark.vue'+import ExternalLink from '@/components/links/ExternalLink.vue'+import MarkdownContent from '@/components/markdown/MarkdownContent.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import AppProgress from '@/components/ui/feedback/AppProgress.vue'+import { releaseNotesURL } from '@/constants'+import { motionStyles } from '@/theme/motion/styles'+import { updatePromptTheme, updateStatusUI } from '@/theme/updater'++const {+ state,+ currentVersion,+ installQuitsApp = false,+ class: className+} = defineProps<{+ state: UpdaterState+ /** The running app's version, shown before the update check knows it. */+ currentVersion: string+ /** Windows installers quit the app, so installing and restarting are one step. */+ installQuitsApp?: boolean+ class?: string+}>()+const emit = defineEmits<{+ install: []+ cancel: []+ restart: []+ retry: []+ dismiss: []+}>()++const { updates: t, common } = useI18n()++const release = computed(() => ('release' in state ? state.release : undefined))+const progress = computed(() => {+ if (state.status === 'installing') return { amount: {}, label: t.value.installing }+ if (state.status !== 'downloading') return null+ const { downloaded, total } = state.progress+ return {+ amount: { value: downloaded, max: total },+ label: downloadProgressLabel(t.value, state.progress)+ }+})+const failure = computed(() =>+ state.status === 'failed' ? updateFailureText(t.value, state.step, state.error) : null+)+const ui = computed(() => {+ const theme = updatePromptTheme()+ return {+ ...mapValues(theme, (slot) => slot()),+ root: theme.root({ class: className }),+ spinner: theme.spinner({ class: motionStyles.spinner })+ }+})++/** Notes links open in the system browser; the window must never navigate away. */+function openNotesLink(event: MouseEvent) {+ if (!(event.target instanceof Element)) return+ const anchor = event.target.closest('a[href]')+ if (!(anchor instanceof HTMLAnchorElement)) return+ event.preventDefault()+ event.stopPropagation()+ void openExternalLink(anchor.href)+}+</script>++<template>+ <div data-slot="update-prompt" :data-status="state.status" :class="ui.root">+ <div v-if="release" :class="ui.main">+ <BrandMark variant="app-icon" decorative :class="ui.icon" />++ <div :class="ui.content">+ <AppAlert v-if="failure" tone="error" :heading="failure" :class="ui.alert" />++ <template v-if="state.status === 'installed'">+ <h1 :class="ui.title">{{ t.installed({ version: release.version }) }}</h1>+ <p :class="ui.subtitle">{{ t.restartToFinish }}</p>+ </template>+ <template v-else>+ <h1 :class="ui.title">{{ t.available({ version: release.version }) }}</h1>+ <p :class="ui.subtitle">{{ t.currentVersion({ version: release.currentVersion }) }}</p>+ </template>++ <div :class="ui.notesHeader">+ <h2 :class="ui.notesLabel">{{ t.whatsNew }}</h2>+ <ExternalLink :href="releaseNotesURL(release.version)" class="text-[11px]">+ {{ t.fullReleaseNotes }}+ </ExternalLink>+ </div>+ <div data-slot="update-notes" :class="ui.notes" @click.capture="openNotesLink">+ <MarkdownContent v-if="release.notes" :content="release.notes" density="comfortable" />+ <p v-else :class="ui.empty">{{ t.noNotes }}</p>+ </div>+ </div>+ </div>++ <AppPlaceholder+ v-else+ role="status"+ size="page"+ label-as="h1"+ :label="state.status === 'up-to-date' ? t.upToDate : t.windowTitle"+ :description="t.currentVersion({ version: currentVersion })"+ :ui="updateStatusUI"+ >+ <template #icon>+ <BrandMark variant="app-icon" decorative class="size-full" />+ </template>+ <template v-if="state.status === 'checking'">+ <icon-lucide-loader-circle :class="ui.spinner" aria-hidden="true" />+ <p>{{ t.checking }}</p>+ </template>+ <AppAlert v-else-if="failure" tone="error" :heading="failure" class="w-full text-start" />+ </AppPlaceholder>++ <footer :class="ui.footer">+ <AppProgress+ v-if="progress"+ :amount="progress.amount"+ :label="progress.label"+ aria-live="polite"+ :class="ui.progress"+ />++ <div :class="ui.actions">+ <AppButton+ v-if="state.status === 'downloading'"+ color="neutral"+ variant="ghost"+ @click="emit('cancel')"+ >+ {{ common.cancel }}+ </AppButton>+ <template v-else-if="state.status !== 'installing'">+ <AppButton color="neutral" variant="ghost" @click="emit('dismiss')">+ {{ release ? t.later : common.close }}+ </AppButton>+ <AppButton+ v-if="state.status === 'failed'"+ color="primary"+ variant="solid"+ @click="emit('retry')"+ >+ {{ t.retry }}+ </AppButton>+ <AppButton+ v-else-if="state.status === 'installed'"+ color="primary"+ variant="solid"+ @click="emit('restart')"+ >+ {{ t.restartNow }}+ </AppButton>+ <AppButton+ v-else-if="state.status === 'available'"+ color="primary"+ variant="solid"+ @click="emit('install')"+ >+ {{ installQuitsApp ? t.installAndRestart : t.install }}+ </AppButton>+ </template>+ </div>+ </footer>+ </div>+</template>diff --git a/src/constants.ts b/src/constants.tsindex 8de718763..d3050a171 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -81,6 +81,15 @@ export const WEB_APP_ORIGIN = 'https://app.openpencil.dev'/** Where the desktop app's installers are published. */export const DESKTOP_DOWNLOAD_URL = 'https://github.com/open-pencil/open-pencil/releases/latest'+/** The running app's version, from `package.json` at build time. */+export const APP_VERSION =+ typeof __OPENPENCIL_APP_VERSION__ === 'string' ? __OPENPENCIL_APP_VERSION__ : ''++/** The published release page, with its full notes, for a desktop version. */+export function releaseNotesURL(version: string): string {+ return `https://github.com/open-pencil/open-pencil/releases/tag/v${version}`+}+export function getShareURL(roomId: string): string {const base = IS_TAURI || !IS_BROWSER ? WEB_APP_ORIGIN : window.location.originreturn `${base}/share/${roomId}`diff --git a/src/theme/feedback/progress.ts b/src/theme/feedback/progress.tsnew file mode 100644index 000000000..40a072fd1--- /dev/null+++ b/src/theme/feedback/progress.ts@@ -0,0 +1,20 @@+const progressTheme = {+ slots: {+ root: 'flex min-w-0 flex-col gap-1',+ track: 'h-1 w-full overflow-hidden rounded-full',+ // Reka marks unmeasurable work `indeterminate`; the bar then pulses in place.+ fill: 'h-full rounded-full transition-[width] duration-150 ease-out motion-reduce:transition-none data-[state=indeterminate]:w-1/3 data-[state=indeterminate]:animate-pulse motion-reduce:data-[state=indeterminate]:animate-none',+ label: 'text-[10px] leading-none tabular-nums'+ },+ variants: {+ tone: {+ /** On panels: an accent bar on a quiet track. */+ accent: { track: 'bg-hover', fill: 'bg-accent', label: 'text-muted' },+ /** On coloured surfaces such as toasts: follows the text colour. */+ current: { track: 'bg-current/25', fill: 'bg-current', label: 'opacity-80' }+ }+ },+ defaultVariants: { tone: 'accent' as const }+} as const++export default progressThemediff --git a/src/theme/feedback/toast.ts b/src/theme/feedback/toast.tsindex eb35fed6a..5ce6ec65c 100644--- a/src/theme/feedback/toast.ts+++ b/src/theme/feedback/toast.ts@@ -7,11 +7,7 @@ const toastTheme = {content: 'min-w-0 flex-1',message: 'select-text',count: 'ml-1.5 opacity-70',- progress: 'mt-1.5 flex flex-col gap-1',- progressTrack: 'h-1 w-full overflow-hidden rounded-full bg-current/25',- progressFill:- 'h-full rounded-full bg-current transition-[width] duration-150 ease-out motion-reduce:transition-none',- progressLabel: 'text-[10px] leading-none tabular-nums opacity-80',+ progress: 'mt-1.5',action:'shrink-0 cursor-pointer rounded px-1.5 py-0.5 text-[10px] font-medium underline-offset-2 hover:underline',control: 'mt-0.5 shrink-0 cursor-pointer rounded p-0.5 opacity-70 hover:opacity-100'@@ -24,15 +20,11 @@ const toastTheme = {},error: { root: 'bg-red-600 text-white' }},- // A determinate bar takes its width from the consumer; an indeterminate one- // pulses in place so the toast still reads as work in progress.+ // Work in progress spins the icon; AppProgress draws the bar.progress: {none: {},determinate: { icon: motionStyles.spinner },- indeterminate: {- icon: motionStyles.spinner,- progressFill: 'motion-reduce:animate-none w-1/3 animate-pulse'- }+ indeterminate: { icon: motionStyles.spinner }}},defaultVariants: { tone: 'default' as const, progress: 'none' as const }diff --git a/src/theme/chat/markdown.ts b/src/theme/markdown/index.tssimilarity index 64%rename from src/theme/chat/markdown.tsrename to src/theme/markdown/index.tsindex 3a4783317..4f3c1a98c 100644--- a/src/theme/chat/markdown.ts+++ b/src/theme/markdown/index.ts@@ -1,10 +1,14 @@import { tv } from 'tailwind-variants'-export const chatMarkdownTheme = tv({+export type MarkdownDensity = 'compact' | 'comfortable'++// vue-stream-markdown styles itself with shadcn variables; map them to app tokens.+// Density rules live in markdown.css, keyed by `data-markdown-density`.+export const markdownTheme = tv({slots: {- root: 'chat-markdown-root',+ root: 'markdown-root',markdown: [- 'chat-markdown',+ 'markdown-content','[--accent:var(--color-hover)]','[--accent-foreground:var(--color-surface)]','[--background:var(--color-input)]',diff --git a/src/theme/chat/markdown.css b/src/theme/markdown/markdown.csssimilarity index 63%rename from src/theme/chat/markdown.cssrename to src/theme/markdown/markdown.cssindex bcb9796b9..b0121fd8d 100644--- a/src/theme/chat/markdown.css+++ b/src/theme/markdown/markdown.css@@ -1,20 +1,23 @@@reference 'tailwindcss';-.chat-markdown-root [data-stream-markdown='code-block'],-.chat-markdown-root .shiki {+.markdown-root [data-stream-markdown='code-block'],+.markdown-root .shiki {background-color: var(--color-input);}-.chat-markdown {+.markdown-content {--shiki-dark-bg: var(--color-input);- &[data-chat-markdown-mode='streaming'] {+ &[data-markdown-mode='streaming'] {[data-stream-markdown='li'],[data-stream-markdown='code-block'],[data-stream-markdown='code-line'] {@apply animate-in fade-in duration-200 motion-reduce:animate-none;}}+}++.markdown-content[data-markdown-density='compact'] {@apply text-[11px] leading-4;[data-stream-markdown='blockquote'],@@ -91,3 +94,45 @@@apply my-2;}}++.markdown-content[data-markdown-density='comfortable'] {+ @apply text-xs leading-5;++ [data-stream-markdown='heading-1'] {+ @apply mt-4 mb-1.5 text-base font-semibold first:mt-0;+ }++ [data-stream-markdown='heading-2'] {+ @apply mt-4 mb-1.5 text-sm font-semibold first:mt-0;+ }++ [data-stream-markdown='heading-3'],+ [data-stream-markdown='heading-4'],+ [data-stream-markdown='heading-5'],+ [data-stream-markdown='heading-6'] {+ @apply mt-3.5 mb-1 text-xs font-semibold first:mt-0;+ }++ [data-stream-markdown='li'],+ [data-stream-markdown='p'] {+ @apply leading-5;+ }++ [data-stream-markdown='li'] {+ @apply py-0.5;+ }++ [data-stream-markdown='p'] {+ @apply my-2;+ }++ [data-stream-markdown='li'] > [data-stream-markdown='p'] {+ @apply my-0;+ }++ [data-stream-markdown='blockquote'],+ [data-stream-markdown='code-block'],+ [data-stream-markdown='thematic-break'] {+ @apply my-3;+ }+}diff --git a/src/theme/updater.ts b/src/theme/updater.tsnew file mode 100644index 000000000..38315865d--- /dev/null+++ b/src/theme/updater.ts@@ -0,0 +1,30 @@+import { tv } from 'tailwind-variants'++export const updatePromptTheme = tv({+ slots: {+ root: 'flex h-full flex-col bg-panel text-surface select-none',+ main: 'flex min-h-0 flex-1 gap-4 px-5 pt-5 pb-4',+ icon: 'size-14 shrink-0',+ content: 'flex min-w-0 flex-1 flex-col',+ alert: 'mb-3',+ title: 'text-sm font-semibold text-surface',+ subtitle: 'mt-0.5 text-xs text-muted',+ notesHeader: 'mt-4 mb-1.5 flex items-baseline justify-between gap-3',+ notesLabel: 'text-xs font-semibold text-surface',+ notes:+ 'min-h-0 flex-1 overflow-y-auto rounded-lg border border-border bg-input px-3.5 py-3 select-text',+ empty: 'text-xs text-muted',+ spinner: 'size-4 text-muted',+ footer: 'flex min-h-14 shrink-0 items-center gap-2 border-t border-border px-5 py-3',+ progress: 'flex-1',+ actions: 'ms-auto flex items-center gap-2'+ }+})++/** AppPlaceholder overrides for the states without a release: a large app icon over the title. */+export const updateStatusUI = {+ icon: 'mb-3 size-16 rounded-none bg-transparent',+ label: 'text-sm font-semibold',+ body: 'mt-4 flex flex-col items-center gap-2 text-xs text-muted',+ content: 'max-w-sm'+}diff --git a/src/updater.ts b/src/updater.tsnew file mode 100644index 000000000..f858748c8--- /dev/null+++ b/src/updater.ts@@ -0,0 +1,16 @@+import { createHead } from '@unhead/vue/client'+import { createApp } from 'vue'++import './app.css'+import { recordRuntimeError } from '@/app/diagnostics'++import UpdaterView from './views/UpdaterView.vue'++// Entry for the desktop Software Update window (`updater.html`). It never+// boots the editor; the main window has already passed the support gate.+const app = createApp(UpdaterView)+app.config.errorHandler = (error, _instance, info) => {+ recordRuntimeError(error, 'vue', info)+ console.error(error)+}+app.use(createHead()).mount('#app')diff --git a/src/views/UpdaterView.vue b/src/views/UpdaterView.vuenew file mode 100644index 000000000..465222176--- /dev/null+++ b/src/views/UpdaterView.vue@@ -0,0 +1,57 @@+<script setup lang="ts">+import { useHead } from '@unhead/vue'+import { computed, onMounted, onScopeDispose } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { animationsEnabled } from '@/app/shell/motion'+import { useAppTheme } from '@/app/shell/theme'+import { createTauriUpdaterBackend, createUpdaterSession } from '@/app/shell/updater/session'+import UpdatePrompt from '@/components/updater/UpdatePrompt.vue'+import { APP_VERSION } from '@/constants'++const { updates, locale } = useI18n()++useHead({+ title: () => updates.value.windowTitle,+ htmlAttrs: {+ lang: locale,+ 'data-motion': computed(() => (animationsEnabled.value ? 'full' : 'off'))+ }+})+useAppTheme()++const backend = createTauriUpdaterBackend()+const session = createUpdaterSession(backend)++let stopCloseGuard: (() => void) | undefined+let disposed = false+onMounted(async () => {+ void session.check()+ const { getCurrentWindow } = await import('@tauri-apps/api/window')+ // Closing mid-install would leave the app half replaced.+ const stop = await getCurrentWindow().onCloseRequested((event) => {+ if (session.state.value.status === 'installing') event.preventDefault()+ })+ if (disposed) stop()+ else stopCloseGuard = stop+})+onScopeDispose(() => {+ disposed = true+ stopCloseGuard?.()+})+</script>++<template>+ <UpdatePrompt+ class="h-dvh"+ :current-version="APP_VERSION"+ :install-quits-app="backend.installQuitsApp"+ :state="session.state.value"+ @install="session.install"+ @cancel="session.cancel"+ @restart="session.restart"+ @retry="session.retry"+ @dismiss="session.dismiss"+ />+</template>diff --git a/tests/app/shell/updater/check.test.ts b/tests/app/shell/updater/check.test.tsnew file mode 100644index 000000000..ffd8d808c--- /dev/null+++ b/tests/app/shell/updater/check.test.ts@@ -0,0 +1,99 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { useI18n } from '@open-pencil/vue'++import { toast } from '@/app/shell/ui'+import { checkForAppUpdate } from '@/app/shell/updater/check'+import { UPDATER_WINDOW_LABEL, UPDATER_WINDOW_URL } from '@/app/shell/updater/window'++import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'++const { updates: messages } = useI18n()++const AVAILABLE_UPDATE = {+ rid: 9,+ currentVersion: '0.11.8',+ version: '0.11.9',+ date: null,+ body: '### Fixed\n\n- Release notes',+ rawJson: '{}'+}++afterEach(async () => {+ await clearTauriMocks()+ for (const entry of toast.toasts.value) toast.remove(entry.id)+})++describe('checkForAppUpdate', () => {+ test('returns quietly when no update is available', async () => {+ const calls: string[] = []+ await mockTauriIPC((cmd) => {+ calls.push(cmd)+ return null+ })++ await checkForAppUpdate({ silent: true, messages })++ expect(calls).toEqual(['plugin:updater|check'])+ expect(toast.toasts.value).toEqual([])+ })++ test('says the app is up to date when asked from the menu', async () => {+ await mockTauriIPC(() => null)++ await checkForAppUpdate({ messages })++ expect(toast.toasts.value.map((entry) => entry.message)).toEqual([messages.value.upToDate])+ })++ test('opens the Software Update window for an available update', async () => {+ const calls: Array<{ cmd: string; args: unknown }> = []+ await mockTauriIPC((cmd, args) => {+ calls.push({ cmd, args })+ if (cmd === 'plugin:updater|check') return AVAILABLE_UPDATE+ if (cmd === 'plugin:window|get_all_windows') return ['main']+ return null+ })++ await checkForAppUpdate({ silent: true, messages })++ const created = calls.find((call) => call.cmd === 'plugin:webview|create_webview_window')+ expect(created?.args).toMatchObject({+ options: {+ label: UPDATER_WINDOW_LABEL,+ url: UPDATER_WINDOW_URL,+ title: messages.value.windowTitle+ }+ })+ // The window checks again for its own handle; this one is released.+ expect(calls.map((call) => call.cmd)).toContain('plugin:resources|close')+ })++ test('focuses the Software Update window when it is already open', async () => {+ const calls: string[] = []+ await mockTauriIPC((cmd) => {+ calls.push(cmd)+ if (cmd === 'plugin:updater|check') return AVAILABLE_UPDATE+ if (cmd === 'plugin:window|get_all_windows') return ['main', UPDATER_WINDOW_LABEL]+ return null+ })++ await checkForAppUpdate({ messages })++ expect(calls).toContain('plugin:window|set_focus')+ expect(calls).not.toContain('plugin:webview|create_webview_window')+ })++ test('reports a failed check from the menu', async () => {+ await mockTauriIPC((cmd) => {+ if (cmd === 'plugin:updater|check') throw new Error('offline')+ return null+ })++ await checkForAppUpdate({ messages })++ expect(toast.toasts.value.map((entry) => entry.message)).toEqual([+ messages.value.checkFailed({ error: 'offline' })+ ])+ })+})diff --git a/tests/app/shell/updater/restart.test.ts b/tests/app/shell/updater/restart.test.tsnew file mode 100644index 000000000..4f6dcb91c--- /dev/null+++ b/tests/app/shell/updater/restart.test.ts@@ -0,0 +1,49 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { requestRestartApproval } from '@/app/shell/updater/restart'++import { clearTauriMocks, installTauriMockWindow } from '#tests/helpers/tauri/mocks'++async function mockWindows(labels: () => string[]) {+ installTauriMockWindow()+ const { mockIPC } = await import('@tauri-apps/api/mocks')+ mockIPC(+ (cmd) => {+ if (cmd === 'plugin:window|get_all_windows') return labels()+ return null+ },+ { shouldMockEvents: true }+ )+}++afterEach(async () => {+ await clearTauriMocks()+})++describe('requestRestartApproval', () => {+ test('approves when no editor window is open', async () => {+ await mockWindows(() => ['updater'])++ await expect(requestRestartApproval()).resolves.toBe(true)+ })++ test('approves once the editor window closes instead of waiting for a reply', async () => {+ await mockWindows(() => ['main', 'updater'])+ const { emit, TauriEvent } = await import('@tauri-apps/api/event')++ const approval = requestRestartApproval()+ await new Promise((resolve) => {+ setTimeout(resolve, 0)+ })+ await emit(TauriEvent.WINDOW_DESTROYED)++ await expect(approval).resolves.toBe(true)+ })++ test('approves when the editor closes before its close event is watched', async () => {+ let lookups = 0+ await mockWindows(() => (++lookups === 1 ? ['main', 'updater'] : ['updater']))++ await expect(requestRestartApproval()).resolves.toBe(true)+ })+})diff --git a/tests/app/shell/updater/session.test.ts b/tests/app/shell/updater/session.test.tsnew file mode 100644index 000000000..e25733471--- /dev/null+++ b/tests/app/shell/updater/session.test.ts@@ -0,0 +1,318 @@+import { describe, expect, test } from 'bun:test'++import type { DownloadEvent } from '@tauri-apps/plugin-updater'++import { createDeferred } from '@/app/runtime/deferred'+import {+ createUpdaterSession,+ type PendingUpdate,+ type UpdaterBackend+} from '@/app/shell/updater/session'++const NOTES = '### Fixed\n\n- Keep the update prompt on screen.\n'++/** An update whose downloads the test finishes by hand. */+function fakeUpdate(options: { failInstall?: string } = {}) {+ const calls: string[] = []+ const downloads: Array<{+ emit: (event: DownloadEvent) => void+ finish: () => void+ fail: (error: Error) => void+ }> = []+ const update: PendingUpdate = {+ version: '0.16.0',+ currentVersion: '0.15.1',+ body: NOTES,+ download(onEvent) {+ calls.push('download')+ const done = createDeferred<undefined>()+ downloads.push({ emit: onEvent, finish: () => done.resolve(undefined), fail: done.reject })+ return done.promise+ },+ async install() {+ calls.push('install')+ if (options.failInstall) throw new Error(options.failInstall)+ },+ async close() {+ calls.push('close')+ }+ }+ return { update, calls, downloads }+}++function fakeBackend(+ check: UpdaterBackend['check'],+ options: { installQuitsApp?: boolean; approve?: boolean | (() => Promise<boolean>) } = {}+) {+ const calls: string[] = []+ const backend: UpdaterBackend = {+ check,+ async confirmRestart() {+ calls.push('confirmRestart')+ const { approve = true } = options+ return typeof approve === 'function' ? approve() : approve+ },+ async relaunch() {+ calls.push('relaunch')+ },+ async closeWindow() {+ calls.push('closeWindow')+ },+ installQuitsApp: options.installQuitsApp ?? false+ }+ return { backend, calls }+}++const settle = () =>+ new Promise((resolve) => {+ setTimeout(resolve, 0)+ })++describe('createUpdaterSession', () => {+ test('shows the release and its trimmed Markdown notes', async () => {+ const { update } = fakeUpdate()+ const session = createUpdaterSession(fakeBackend(async () => update).backend)++ await session.check()++ expect(session.state.value).toEqual({+ status: 'available',+ release: { version: '0.16.0', currentVersion: '0.15.1', notes: NOTES.trim() }+ })+ })++ test('reports when there is nothing to install', async () => {+ const session = createUpdaterSession(fakeBackend(async () => null).backend)++ await session.check()++ expect(session.state.value).toEqual({ status: 'up-to-date' })+ })++ test('retries a failed check', async () => {+ const { update } = fakeUpdate()+ let attempts = 0+ const session = createUpdaterSession(+ fakeBackend(async () => {+ attempts+++ if (attempts === 1) throw new Error('offline')+ return update+ }).backend+ )++ await session.check()+ expect(session.state.value).toEqual({ status: 'failed', step: 'check', error: 'offline' })++ await session.retry()+ expect(session.state.value.status).toBe('available')+ })++ test('downloads with progress, installs, then restarts once documents may close', async () => {+ const { update, calls, downloads } = fakeUpdate()+ const { backend, calls: backendCalls } = fakeBackend(async () => update)+ const session = createUpdaterSession(backend)+ await session.check()++ const installing = session.install()+ downloads[0]?.emit({ event: 'Started', data: { contentLength: 4 } })+ downloads[0]?.emit({ event: 'Progress', data: { chunkLength: 2 } })+ expect(session.state.value).toMatchObject({+ status: 'downloading',+ progress: { downloaded: 2, total: 4 }+ })++ downloads[0]?.finish()+ await installing+ expect(calls).toEqual(['download', 'install'])+ expect(session.state.value).toMatchObject({ status: 'installed' })+ // Installing on macOS and Linux never restarts by itself.+ expect(backendCalls).toEqual([])++ await session.restart()+ expect(backendCalls).toEqual(['confirmRestart', 'relaunch'])+ })++ test('stays installed when the editor keeps its documents open', async () => {+ const { update, downloads } = fakeUpdate()+ const { backend, calls } = fakeBackend(async () => update, { approve: false })+ const session = createUpdaterSession(backend)+ await session.check()+ const installing = session.install()+ downloads[0]?.finish()+ await installing++ await session.restart()++ expect(calls).toEqual(['confirmRestart'])+ expect(session.state.value.status).toBe('installed')+ })++ test('cancels a download at once and reuses it when installing again', async () => {+ const { update, calls, downloads } = fakeUpdate()+ const session = createUpdaterSession(fakeBackend(async () => update).backend)+ await session.check()++ const first = session.install()+ downloads[0]?.emit({ event: 'Progress', data: { chunkLength: 3 } })+ session.cancel()+ expect(session.state.value.status).toBe('available')++ // The detached download finishing must not install anything.+ downloads[0]?.emit({ event: 'Progress', data: { chunkLength: 1 } })+ expect(session.state.value.status).toBe('available')++ const second = session.install()+ expect(session.state.value).toMatchObject({+ status: 'downloading',+ progress: { downloaded: 4 }+ })+ downloads[0]?.finish()+ await Promise.all([first, second])++ expect(calls).toEqual(['download', 'install'])+ expect(session.state.value.status).toBe('installed')+ })++ test('ignores a cancelled download that finishes while detached', async () => {+ const { update, calls, downloads } = fakeUpdate()+ const session = createUpdaterSession(fakeBackend(async () => update).backend)+ await session.check()++ const installing = session.install()+ session.cancel()+ downloads[0]?.finish()+ await installing++ expect(calls).toEqual(['download'])+ expect(session.state.value.status).toBe('available')+ })++ test('reports a failed download and starts a new one on retry', async () => {+ const { update, calls, downloads } = fakeUpdate()+ const session = createUpdaterSession(fakeBackend(async () => update).backend)+ await session.check()++ const installing = session.install()+ downloads[0]?.fail(new Error('connection reset'))+ await installing+ expect(session.state.value).toMatchObject({+ status: 'failed',+ step: 'download',+ error: 'connection reset',+ release: { version: '0.16.0' }+ })++ const retrying = session.retry()+ await settle()+ downloads[1]?.finish()+ await retrying+ expect(calls).toEqual(['download', 'download', 'install'])+ })++ test('keeps the release visible when the install fails', async () => {+ const { update, downloads } = fakeUpdate({ failInstall: 'signature mismatch' })+ const session = createUpdaterSession(fakeBackend(async () => update).backend)+ await session.check()++ const installing = session.install()+ downloads[0]?.finish()+ await installing++ expect(session.state.value).toMatchObject({+ status: 'failed',+ step: 'install',+ error: 'signature mismatch',+ release: { version: '0.16.0' }+ })+ })++ test('closes documents before a Windows installer quits the app', async () => {+ const { update, calls, downloads } = fakeUpdate()+ const { backend, calls: backendCalls } = fakeBackend(async () => update, {+ installQuitsApp: true,+ approve: false+ })+ const session = createUpdaterSession(backend)+ await session.check()++ const installing = session.install()+ downloads[0]?.finish()+ await installing++ expect(backendCalls).toEqual(['confirmRestart'])+ expect(calls).toEqual(['download'])+ expect(session.state.value.status).toBe('available')+ })++ test('a cancel while the editor asks about documents stops a Windows install', async () => {+ const answer = createDeferred<boolean>()+ const { update, calls, downloads } = fakeUpdate()+ const { backend } = fakeBackend(async () => update, {+ installQuitsApp: true,+ approve: () => answer.promise+ })+ const session = createUpdaterSession(backend)+ await session.check()++ const installing = session.install()+ downloads[0]?.finish()+ await settle()+ session.cancel()+ answer.resolve(true)+ await installing++ expect(calls).toEqual(['download'])+ expect(session.state.value.status).toBe('available')+ })++ test('reports a failed document prompt instead of waiting', async () => {+ const { update, calls, downloads } = fakeUpdate()+ const { backend } = fakeBackend(async () => update, {+ installQuitsApp: true,+ approve: () => Promise.reject(new Error('editor closed'))+ })+ const session = createUpdaterSession(backend)+ await session.check()++ const installing = session.install()+ downloads[0]?.finish()+ await installing++ expect(calls).toEqual(['download'])+ expect(session.state.value).toMatchObject({+ status: 'failed',+ step: 'install',+ error: 'editor closed'+ })+ })++ test('asks about documents once however often Restart Now is pressed', async () => {+ const answer = createDeferred<boolean>()+ const { update, downloads } = fakeUpdate()+ const { backend, calls } = fakeBackend(async () => update, { approve: () => answer.promise })+ const session = createUpdaterSession(backend)+ await session.check()+ const installing = session.install()+ downloads[0]?.finish()+ await installing++ const first = session.restart()+ const second = session.restart()+ answer.resolve(true)+ await Promise.all([first, second])++ expect(calls).toEqual(['confirmRestart', 'relaunch'])+ })++ test('releases the update handle when dismissed', async () => {+ const { update, calls } = fakeUpdate()+ const { backend, calls: backendCalls } = fakeBackend(async () => update)+ const session = createUpdaterSession(backend)++ await session.check()+ await session.dismiss()++ expect(calls).toEqual(['close'])+ expect(backendCalls).toEqual(['closeWindow'])+ })+})diff --git a/tests/e2e/chat/markdown.spec.ts b/tests/e2e/chat/markdown.spec.tsindex 1abbcaaff..b88198eb6 100644--- a/tests/e2e/chat/markdown.spec.ts+++ b/tests/e2e/chat/markdown.spec.ts@@ -5,8 +5,8 @@ import { expect, test } from '#tests/helpers/chat/fixture'test('completed responses release streaming parser history', async ({ configuredChat: chat }) => {await chat.submit('Show a code block')- const markdown = chat.page.locator('.chat-markdown').last()- await expect(markdown).toHaveAttribute('data-chat-markdown-mode', 'static')+ const markdown = chat.page.locator('[data-slot="chat-markdown"] .markdown-content').last()+ await expect(markdown).toHaveAttribute('data-markdown-mode', 'static')await expect(markdown.locator('.shiki').first()).toBeVisible()})@@ -25,7 +25,9 @@ test('code blocks follow light and dark themes', async ({ configuredChat: chat }themeModule.useAppTheme().setTheme('light')})await chat.page.waitForFunction(() => document.documentElement.dataset.theme === 'light')- await expect(chat.page.locator('.chat-markdown').last()).toHaveClass(/light/)+ await expect(+ chat.page.locator('[data-slot="chat-markdown"] .markdown-content').last()+ ).toHaveClass(/light/)await expect(code).toHaveCSS('background-color', 'rgb(255, 255, 255)')})diff --git a/tests/e2e/chat/real-llm.spec.ts b/tests/e2e/chat/real-llm.spec.tsindex 1359bb68d..736418124 100644--- a/tests/e2e/chat/real-llm.spec.ts+++ b/tests/e2e/chat/real-llm.spec.ts@@ -26,13 +26,14 @@ test.describe('OpenRouter chat', { tag: '@real-llm' }, () => {)const assistant = chat.assistantMessage()- await expect(assistant.locator('.chat-markdown')).toBeVisible({ timeout: 60_000 })+ await expect(assistant.locator('[data-slot="chat-markdown"] .markdown-content')).toBeVisible({+ timeout: 60_000+ })await expect(assistant.locator('.shiki')).toContainText('const ready = true', {timeout: 60_000})- await expect(assistant.locator('.chat-markdown')).toHaveAttribute(- 'data-chat-markdown-mode',- 'static'- )+ await expect(+ assistant.locator('[data-slot="chat-markdown"] .markdown-content')+ ).toHaveAttribute('data-markdown-mode', 'static')})})diff --git a/tests/e2e/storybook/toast.spec.ts b/tests/e2e/storybook/toast.spec.tsindex 6b1ffb681..26c0de1db 100644--- a/tests/e2e/storybook/toast.spec.ts+++ b/tests/e2e/storybook/toast.spec.ts@@ -5,7 +5,7 @@ test('determinate progress exposes its value and bar width', async ({ page }) =>const toast = page.locator('[data-slot="toast"]')await expect(toast).toHaveAttribute('data-progress', 'determinate')- await expect(toast.locator('[data-slot="toast-progress-label"]')).toHaveText(+ await expect(toast.locator('[data-slot="progress-label"]')).toHaveText('42% · 9.6 MiB of 22.9 MiB')@@ -13,10 +13,7 @@ test('determinate progress exposes its value and bar width', async ({ page }) =>await expect(bar).toHaveAttribute('aria-valuenow', '42')await expect(bar).toHaveAttribute('aria-valuemin', '0')await expect(bar).toHaveAttribute('aria-valuemax', '100')- await expect(toast.locator('[data-slot="toast-progress-fill"]')).toHaveAttribute(- 'style',- /width: 42%/- )+ await expect(toast.locator('[data-slot="progress-fill"]')).toHaveAttribute('style', /width: 42%/)})test('progress without a known total stays indeterminate', async ({ page }) => {@@ -27,7 +24,7 @@ test('progress without a known total stays indeterminate', async ({ page }) => {const toast = page.locator('[data-slot="toast"]')await expect(toast).toHaveAttribute('data-progress', 'indeterminate')await expect(toast.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow', /\d/)- await expect(toast.locator('[data-slot="toast-progress-label"]')).toHaveText('4.2 MiB downloaded')+ await expect(toast.locator('[data-slot="progress-label"]')).toHaveText('4.2 MiB downloaded')})test('a reported total flips between determinate, indeterminate, and cleared', async ({ page }) => {@@ -42,7 +39,7 @@ test('a reported total flips between determinate, indeterminate, and cleared', a// The bar follows the reported work and keeps the toast open instead of expiring.await page.getByRole('button', { name: 'Advance download' }).click()await expect(bar).toHaveAttribute('aria-valuenow', '13')- await expect(toast.locator('[data-slot="toast-progress-label"]')).toHaveText(+ await expect(toast.locator('[data-slot="progress-label"]')).toHaveText('13% · 2.9 MiB of 22.9 MiB')await page.clock.fastForward(3_500)diff --git a/tests/engine/tauri/processes.test.ts b/tests/engine/tauri/processes.test.tsindex 60c129bc5..87c234723 100644--- a/tests/engine/tauri/processes.test.ts+++ b/tests/engine/tauri/processes.test.ts@@ -1,17 +1,12 @@import { afterEach, describe, expect, test, vi } from 'bun:test'-import { ref } from 'vue'-import { spawnACPProcess } from '@/app/ai/acp/process'-import { toast } from '@/app/shell/ui'-import { checkForAppUpdate } from '@/app/shell/updater'import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'afterEach(async () => {await clearTauriMocks()vi.restoreAllMocks()- for (const entry of toast.toasts.value) toast.remove(entry.id)Reflect.deleteProperty(globalThis, 'window')Reflect.deleteProperty(globalThis, 'navigator')})@@ -116,120 +111,3 @@ describe('Tauri process helpers', () => {expect(onUnexpectedClose).toHaveBeenCalled()})})--describe('Tauri updater helper', () => {- const messages = ref({- upToDate: 'Up to date',- availableTitle: 'Update available',- available: ({ version }: { version: string }) => `Version ${version}`,- installPrompt: 'Install now?',- downloading: ({ version }: { version: string }) => `Downloading ${version}`,- downloadProgress: ({- percent,- downloaded,- total- }: {- percent: number- downloaded: string- total: string- }) => `${percent}% of ${total} (${downloaded})`,- downloadProgressUnknown: ({ downloaded }: { downloaded: string }) => `${downloaded} downloaded`,- installedTitle: 'Installed',- installed: ({ version, size }: { version: string; size: string }) =>- `Installed ${version}${size}`,- unavailable: 'Unavailable',- checkFailed: ({ error }: { error: string }) => `Failed: ${error}`- })-- test('returns quietly when no Tauri update is available', async () => {- const calls: string[] = []- await mockTauriIPC((cmd) => {- calls.push(cmd)- if (cmd === 'plugin:updater|check') return null- return null- })-- await checkForAppUpdate({ silent: true, messages })-- expect(calls).toEqual(['plugin:updater|check'])- })-- test('confirms, installs, and relaunches available Tauri updates', async () => {- const calls: Array<{ cmd: string; args: unknown }> = []- await mockTauriIPC((cmd, args) => {- calls.push({ cmd, args })- if (cmd === 'plugin:updater|check') {- return {- rid: 9,- currentVersion: '0.11.8',- version: '0.11.9',- date: null,- body: 'Release notes',- rawJson: '{}'- }- }- if (cmd === 'plugin:dialog|message') {- const options = args as { buttons?: string }- if (options.buttons === 'OkCancel') return 'Ok'- }- if (cmd === 'plugin:updater|download_and_install') {- const onEvent = (args as { onEvent: { onmessage: (event: unknown) => void } }).onEvent- onEvent.onmessage({ event: 'Started', data: { contentLength: 10 } })- onEvent.onmessage({ event: 'Progress', data: { chunkLength: 10 } })- }- return null- })-- await checkForAppUpdate({ messages })-- expect(calls.map((call) => call.cmd)).toEqual([- 'plugin:updater|check',- 'plugin:dialog|message',- 'plugin:updater|download_and_install',- 'plugin:dialog|message',- 'plugin:process|restart'- ])- expect(calls[1]?.args).toMatchObject({- title: 'Update available',- kind: 'info',- buttons: 'OkCancel'- })- expect(calls[2]?.args).toMatchObject({ rid: 9 })- })-- test('reports download progress once and clears the toast on failure', async () => {- await mockTauriIPC((cmd, args) => {- if (cmd === 'plugin:updater|check') {- return {- rid: 9,- currentVersion: '0.11.8',- version: '0.11.9',- date: null,- body: 'Release notes',- rawJson: '{}'- }- }- if (cmd === 'plugin:dialog|message') {- const options = args as { buttons?: string }- if (options.buttons === 'OkCancel') return 'Ok'- }- if (cmd === 'plugin:updater|download_and_install') {- const onEvent = (args as { onEvent: { onmessage: (event: unknown) => void } }).onEvent- onEvent.onmessage({ event: 'Started', data: { contentLength: 4 } })- onEvent.onmessage({ event: 'Progress', data: { chunkLength: 2 } })- expect(toast.toasts.value).toHaveLength(1)- expect(toast.toasts.value[0]?.progress).toEqual({ value: 2, max: 4 })- expect(toast.toasts.value[0]?.progressLabel).toBe('50% of 4 B (2 B)')- throw new Error('download interrupted')- }- return null- })-- await checkForAppUpdate({ messages })-- // The failed progress toast must not linger: it never expires on its own.- expect(toast.toasts.value.map((entry) => entry.message)).toEqual([- 'Failed: download interrupted'- ])- })-})diff --git a/tools/checks/architecture/src/steiger-rules/index.ts b/tools/checks/architecture/src/steiger-rules/index.tsindex a99e370bc..d49da1762 100644--- a/tools/checks/architecture/src/steiger-rules/index.ts+++ b/tools/checks/architecture/src/steiger-rules/index.ts@@ -332,12 +332,14 @@ const noNonUIImportsInSharedUI = createImportRule(})+// The editor's root and router, plus the desktop Software Update window's page entry.+const VIEW_ENTRYPOINTS = new Set(['src/App.vue', 'src/main.ts', 'src/router.ts', 'src/updater.ts'])+const noViewsImportedOutsideEntry = createImportRule('open-pencil/no-views-imported-outside-entry',(sourceRel, _specifier, resolved) => {if (!resolved?.startsWith('src/views/')) return null- if (sourceRel === 'src/App.vue' || sourceRel === 'src/main.ts' || sourceRel === 'src/router.ts')- return null+ if (VIEW_ENTRYPOINTS.has(sourceRel)) return nullreturn 'Views are top-level composition entrypoints and must not be imported by app services or reusable components.'})diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 591b4fa43..15a24f660 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -139,9 +139,9 @@ ja:storage.accessKeyIDja:storage.copyCorsja:storage.providerS3ja:updates.available-ja:updates.availableTitle-ja:updates.downloadingja:updates.installed+ja:updates.restartFailed+ja:updates.restartToFinishja:updates.unavailableja:updates.upToDateja:variables.copyAsCSS@@ -284,9 +284,9 @@ zh-cn:storage.accessKeyIDzh-cn:storage.copyCorszh-cn:storage.providerS3zh-cn:updates.available-zh-cn:updates.availableTitle-zh-cn:updates.downloadingzh-cn:updates.installed+zh-cn:updates.restartFailed+zh-cn:updates.restartToFinishzh-cn:updates.unavailablezh-cn:updates.upToDatezh-cn:variables.copyAsCSSdiff --git a/updater.html b/updater.htmlnew file mode 100644index 000000000..4ef4d5876--- /dev/null+++ b/updater.html@@ -0,0 +1,19 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Software Update</title>+ <style>+ body { margin: 0; background: #1e1e1e; }+ @media (prefers-color-scheme: light) {+ body { background: #f3f4f6; }+ }+ </style>+ </head>++ <body>+ <div id="app"></div>+ <script type="module" src="/src/updater.ts"></script>+ </body>+</html>diff --git a/vite.config.ts b/vite.config.tsindex f394a5723..e61515c71 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,3 +1,4 @@+import { resolve } from 'node:path'import process from 'node:process'import tailwindcss from '@tailwindcss/vite'@@ -55,7 +56,14 @@ export default defineConfig(async ({ command }) => {build: {// Syntax is lowered to the supported browser baseline; APIs are not polyfilled.target: viteBuildTarget(),- chunkSizeWarningLimit: 2500+ chunkSizeWarningLimit: 2500,+ rolldownOptions: {+ // The desktop Software Update window is its own page.+ input: {+ main: resolve(__dirname, 'index.html'),+ updater: resolve(__dirname, 'updater.html')+ }+ }},server: createDevServerOptions(host, __dirname)}